在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.
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)