栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用实时摄像机预览更新matplotlib中的帧

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用实时摄像机预览更新matplotlib中的帧

互动模式

在matplotlib中更新图的一种方法是使用交互模式(

plt.ion()
)。然后,您不应为捕获的每个帧重新创建新的子图,而应使用图像创建一次绘图,然后再进行更新。

import cv2import matplotlib.pyplot as pltdef grab_frame(cap):    ret,frame = cap.read()    return cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)#Initiate the two camerascap1 = cv2.VideoCapture(0)cap2 = cv2.VideoCapture(1)#create two subplotsax1 = plt.subplot(1,2,1)ax2 = plt.subplot(1,2,2)#create two image plotsim1 = ax1.imshow(grab_frame(cap1))im2 = ax2.imshow(grab_frame(cap2))plt.ion()while True:    im1.set_data(grab_frame(cap1))    im2.set_data(grab_frame(cap2))    plt.pause(0.2)plt.ioff() # due to infinite loop, this gets never called.plt.show()

功能动画

当然,另一种选择是使用matplotlib的内置功能,

FuncAnimation
该内置功能专门设计用于对图进行动画处理。

import cv2import matplotlib.pyplot as pltfrom matplotlib.animation import FuncAnimationdef grab_frame(cap):    ret,frame = cap.read()    return cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)#Initiate the two camerascap1 = cv2.VideoCapture(0)cap2 = cv2.VideoCapture(1)#create two subplotsax1 = plt.subplot(1,2,1)ax2 = plt.subplot(1,2,2)#create two image plotsim1 = ax1.imshow(grab_frame(cap1))im2 = ax2.imshow(grab_frame(cap2))def update(i):    im1.set_data(grab_frame(cap1))    im2.set_data(grab_frame(cap2))ani = FuncAnimation(plt.gcf(), update, interval=200)plt.show()

为了在按键事件时关闭窗口,您可以像这样添加回调

#... other preani = FuncAnimation(plt.gcf(), update, interval=200)def close(event):    if event.key == 'q':        plt.close(event.canvas.figure)cid = plt.gcf().canvas.mpl_connect("key_press_event", close)plt.show()# pre that should be executed after window is closed.


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/638758.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号