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. CentOS7使用yum时File contains no section headers.解决办法

    本文转载于  https://blog.csdn.net/trokey/article/details/84908838 安装好CenOS7后,自带的yum不能直接使用,使用会出现如下问题: 原因是没 ...

  2. 栈帧的内部结构--动态返回地址(Return Address)

    每个栈帧中包含: 局部变量表(Local Variables) 操作数栈(Opreand Stack) 或表达式栈 动态链接 (Dynamic Linking) (或指向运行时常量的方法引用) 动态返 ...

  3. Asp.Net Core SignalR 系列博客

    系列 SignalR+Vue SignalR+Vue 服务端向客户端发送信息 SignalR+Vue+Log4net 实时日志推送 待定...... 源码地址:https://github.com/Q ...

  4. 学会Git玩转GitHub(第一篇) 入门详解 - 精简归纳

    学会Git玩转GitHub(第一篇) 入门详解 - 精简归纳 JERRY_Z. ~ 2020 / 9 / 25 转载请注明出处!️ 目录 学会Git玩转GitHub(第一篇) 入门详解 - 精简归纳 ...

  5. jquery,Datatables插件使用,做根据【日期段】筛选数据的功能 jsp

     时间格式为yyyymmdd,通过转换为int类型进行比较大小 画面: jsp代码: 1 //日期显示控件,使用h-ui框架 2 3 <div class="text-c"& ...

  6. Python练习题 047:Project Euler 020:阶乘结果各数字之和

    本题来自 Project Euler 第20题:https://projecteuler.net/problem=20 ''' Project Euler: Problem 20: Factorial ...

  7. Python练习题 005:三个数字由大到小排序输出

    [Python练习题 005]输入三个整数x,y,z,请把这三个数由小到大输出. ----------------------------------------------------------- ...

  8. matlab中floor 朝负无穷大四舍五入

    来源:https://ww2.mathworks.cn/help/matlab/ref/floor.html?searchHighlight=floor&s_tid=doc_srchtitle ...

  9. Github 太狠了,居然把 "master" 干掉了!

    前段时间栈长有看到 Github 和 master 分支变更的新闻,当时没有注意细节,直到今天我创建仓库时: 看了半天感觉有点不对劲啊... 怎么 master 不见了,之前默认主干分支名称都是叫 m ...

  10. Codeforces Global Round 11 A~D题解

    A.Avoiding Zero 题目链接:https://codeforces.ml/contest/1427 题目大意:给定一个数组a1,a2...,an,要求找出一个a重排后的数组b1,b2,.. ...