python的plot如何实时更新_python-使用实时摄像机预览更新matplotlib中的...

互动模式

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

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

import cv2

import matplotlib.pyplot as plt

def grab_frame(cap):

ret,frame = cap.read()

return cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)

#Initiate the two cameras

cap1 = cv2.VideoCapture(0)

cap2 = cv2.VideoCapture(1)

#create two subplots

ax1 = plt.subplot(1,2,1)

ax2 = plt.subplot(1,2,2)

#create two image plots

im1 = 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 cv2

import matplotlib.pyplot as plt

from matplotlib.animation import FuncAnimation

def grab_frame(cap):

ret,frame = cap.read()

return cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)

#Initiate the two cameras

cap1 = cv2.VideoCapture(0)

cap2 = cv2.VideoCapture(1)

#create two subplots

ax1 = plt.subplot(1,2,1)

ax2 = plt.subplot(1,2,2)

#create two image plots

im1 = 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 code

ani = 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()

# code that should be executed after window is closed.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值