import torch
from models.models import Model
import cv2
from PIL import Image
import numpy as np from matplotlib.animation import FFMpegWriter
import time
import matplotlib.pyplot as plt from torchvision.transforms import functional exp_name = './xxxx_results'
dataRoot = 'xxxx.mp4'
model_path = './checkpoint_best.pth' def pre_image(image):
image = Image.fromarray(cv2.cvtColor(image,cv2.COLOR_BGR2RGB))
input_image = image.copy()
# image.show()
height, width = image.size[1], image.size[0]
height = round(height / 16) * 16
width = round(width / 16) * 16
image = image.resize((width, height), Image.BILINEAR) image = functional.to_tensor(image)
image = functional.normalize(image, [0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
return input_image,torch.unsqueeze(image,0) if __name__ == '__main__': device = torch.device('cuda:0') # load model
model=Model()
checkpoint = torch.load(model_path)
model.load_state_dict(checkpoint['model']) model.cuda()
model.eval() # input video
video = cv2.VideoCapture(dataRoot)
fps = video.get(cv2.CAP_PROP_FPS)
print(fps)
frameCount = video.get(cv2.CAP_PROP_FRAME_COUNT)
print(frameCount)
size = (int(video.get(cv2.CAP_PROP_FRAME_WIDTH)), int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))) # metadata = dict(title='Video Test', artist='Matplotlib', comment='Movie support!')
# writer = FFMpegWriter(fps=25, metadata=metadata) # videoWriter = cv2.VideoWriter('trans.mp4', cv2.VideoWriter_fourcc(*'MP4V'), fps, size)
success, frame = video.read()
index = 1 figure = plt.figure()
while success:
# time1=time.time()
src_image,frame = pre_image(frame)
images = frame.to(device) # time1 = time.time() # ground truth
# gt_path = dataRoot + '/den/' + filename_no_ext + '.csv' # predict
dense_map,atten_map = model(images)
# test = time.time() - time1 dense_map = dense_map.cpu().data.numpy()[0,0,:,:]
# test=time.time()-time1 dense_pred_count = np.sum(dense_map)
dense_map = dense_map/np.max(dense_map+1e-20) # cv2.imshow("image", dense_map)
# cv2.waitKey(0) plt.subplot(121)
plt.imshow(src_image)
# plt.title('original image')
plt.axis('off') plt.subplot(122)
plt.imshow(dense_map)
# plt.title('dense map')
plt.text(25, 25, 'pred crowd count:%.4f ' % dense_pred_count, fontdict={'size': 10, 'color': 'red'})
plt.axis('off') plt.tight_layout(pad=0.3, w_pad=0, h_pad=1) # anni=animation.FuncAnimation(fig, animate, init_func=init,frames=200, interval=20, blit=True)
# anim.save('sin.gif', fps=75, writer='imagemagick')
plt.savefig(exp_name + '/'+ str('%05d' % index) + '_' + str(int(dense_pred_count)) + '.png', bbox_inches='tight', pad_inches=0, dpi=150) # plt.show()
plt.clf() success, frame = video.read()
index += 1 video.release()

matplotlib中plt用法实例的更多相关文章

  1. Matplotlib中plt.rcParams用法(设置图像细节)

    import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap %mat ...

  2. Nhibernate中CreateSQLQuery用法实例

    说明: 使用原生SQL查询时,若要通过addEntity方法引入对象,则查询结果列中必须包含该对象的所有属性,否则会抛出System.IndexOutOfRangeException异常. 结论: 若 ...

  3. matplotlib中plt.scatter()参数详解

    scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, l ...

  4. C#中FormsAuthentication用法实例

    ....本文纯属抄袭....   using System; using System.Web; using System.Web.Security;   namespace AuthTest {   ...

  5. .NET中StringBuilder用法实例分析

    string s1 = "33"; string s2 = "44"; string s3 = "55"; //需求是把s1 s2 s3拼接 ...

  6. matplotlib中 plt.plot() 函数中**kwargs的参数形式

    plt.plot(x, y, **kwargs) **kwargs的参数大致有如下几种: color: 颜色 linestyle: 线条样式 marker: 标记风格 markerfacecolor: ...

  7. matplotlib中subplots的用法

    1.matplotlib中如果只画一张图的话,可以直接用pyplot,一般的做法是: import matplotlib.pyplot as plt plt.figure(figsize=(20,8) ...

  8. c#初学-多线程中lock用法的经典实例

    本文转载自:http://www.cnblogs.com/promise-7/articles/2354077.html 一.Lock定义     lock 关键字可以用来确保代码块完成运行,而不会被 ...

  9. php中的curl使用入门教程和常见用法实例

    摘要: [目录] php中的curl使用入门教程和常见用法实例 一.curl的优势 二.curl的简单使用步骤 三.错误处理 四.获取curl请求的具体信息 五.使用curl发送post请求 六.文件 ...

随机推荐

  1. selenium过豆瓣滑动验证码

    首先是加速度代码 def get_tracks(distance): """ 拿到移动轨迹,模仿人的滑动行为,先匀加速后匀减速 匀变速运动基本公式: ①v = v0+at ...

  2. c++中清空输入缓冲区的方法(做cf的时候炸了)

    C/C++ 四种清空输入缓冲区的方法 比较实用的一种 char c; while(c=getchar()!='\n'); 或者是这种 cin.ignore(count,c); count代表要清除的字 ...

  3. 【读书】Into The Air:进入空气稀薄地带

    珠穆朗玛峰,世界第一高峰,北部在中国境内,南部在尼泊尔境内.喜欢户外运动的人,曾经在20多岁的时候曾经"大言不惭"说这一辈子一定要去一次珠峰.<Into the Air> ...

  4. 趣图:普通人讲故事 VS 程序员讲故事

      扩展阅读 趣图:我说自己菜 vs 大佬说自己菜 趣图:客户需求VS客户预算 趣图:在外行人眼中的程序员 如何处理前任程序员留下的代码 一个故事讲清楚NIO

  5. JVM学习(四)JVM调优

    一.调优命令 Sun JDK监控和故障处理命令有jps.jstat.jmap.jhat.jstack.jinfo jps,JVM Process Status Tool,显示指定系统内所有的HotSp ...

  6. RocketMQ系列:rocketmq运维控制台使用详解(全网独家)

    搭建好了RocketMQ的console之后,直接在浏览器打开http://{你的ip}:8080 默认会进入到驾驶舱(dashboard). 总览 整体横向菜单分为八个部分: 运维:主要是设置nam ...

  7. kafk学习笔记(一)

    kafka消费模式 1.点对点模式:消费者主动拉取消息,消费之后删除数据. 2.发布/订阅模式:如果生产者推给消费者,可能会有些消费者消费比较慢,直接爆炸.或者有些消费者消费很快,资源浪费:一般是消费 ...

  8. linux系统修改不成功/无法修改密码

    1.问题描述 新上架的60台浪潮服务器使用某带外装机平台进行统一安装,安装完成后修改用户密码时统一无法修改,使用root账户无法修改其他用户密码,自身根密码也无法修改成功 2.排查问题 因带外装机平台 ...

  9. Spring AOP系列(一)— 代理模式

    Spring AOP系列(一)- 代理模式 AOP(Aspect Oriented Programming)并没有创造或使用新的技术,其底层就是基于代理模式实现.因此我们先来学习一下代理模式. 基本概 ...

  10. mysql-11-DML

    #DML语言 /* 数据操作语言 插入:insert 修改:update 删除:delete */ #一.插入语句 /* 语法: insert into 表名(列名...) values(新值...) ...