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. maven打包(jar)类型错误

    maven项目打包测试环境时部署发现是开发环境.确认打包命令无误, 此情况下将target内容全部删除,重新打包即可.是全部删除.

  2. 2020年的100天——FLAGS

    2020年的100天--FLAGS Reading <爱的博弈>-- 作者: 约翰·戈特曼 (John Gottman) / 娜恩·西尔弗 (Nan Silver) <人间失格> ...

  3. pytest封神之路第四步 内置和自定义marker

    可以通过命令行查看所有marker,包括内置和自定义的 pytest --markers 内置marker 内置marker本文先讲usefixtures .filterwarnings .skip ...

  4. Oracle学习(十五)PLSQL安装

    PS:由于原来一直用的旧版本的PLSQL客户端,查看执行计划有些数据无法展示,所以今天换一波新版本的使用,记录下安装和使用流程. PLSQL(oracle数据可视化工具) 一.下载 我用的13的版本, ...

  5. Spring Boot 知识清单(一)SpringApplication

    爱生活,爱编码,微信搜一搜[架构技术专栏]关注这个喜欢分享的地方.本文 架构技术专栏 已收录,有各种JVM.多线程.源码视频.资料以及技术文章等你来拿. 一.概述 目前Spring Boot已经发展到 ...

  6. 从零搭建Golang开发环境--go修仙序章

    1. 什么是go语言 Go(又称 Golang)是 Google 的 Robert Griesemer,Rob Pike 及 Ken Thompson 开发的一种静态 .强类型.编译型语言 .Go 语 ...

  7. sklearn训练模型的保存与加载

    使用joblib模块保存于加载模型 在机器学习的过程中,我们会进行模型的训练,最常用的就是sklearn中的库,而对于训练好的模型,我们当然是要进行保存的,不然下次需要进行预测的时候就需要重新再进行训 ...

  8. 重装Windows系统 入门详解 - 基础教程

    重装Windows系统 入门详解 - 基础教程 JERRY_Z. ~ 2020 / 10 / 13 转载请注明出处!️ 目录 重装Windows系统 入门详解 - 基础教程 一.说明 二.具体步骤 ( ...

  9. 多测师讲解接口测试 _报错_高级讲师肖sir

  10. 多测师讲解selenium_alert弹框定位_高级讲师肖sir

    from selenium import webdriverfrom time import sleepdrvier=webdriver.Chrome()url=r'F:\dcs\DCS课程安排\se ...