问题描述
我正在使用OpenCV4和python 3来打开摄像头,抓取帧并将其显示在窗口中,就像提供的第一个代码教程此处.但是,获取不同的帧需要花费不同的时间:有时要花0.01 s的时间才能抓取,有时要花0.33 s的时间,当在窗口中显示帧时会产生滞后.
I am using OpenCV4 along with python 3 to open a webcam, grab the frames and display them in a window, just like the first code tutorial provided here. However, it takes a different amount of time grabbing different frames: sometimes it takes 0.01 s to grab, and sometimes it takes 0.33 s, which creates lags when showing the frames in the window.
在抓帧时是否有一种强制固定时间的方式,以便我可以看到视频而不会出现延迟?我认为OpenCV会发生这种情况,因为当我使用默认的Windows摄像头查看器进行查看时视频正常显示.
Is there a way to force a constant time when grabbing frames so that i can see the video without lag? I think it is happening with OpenCV because when i use a default windows camera viewer to see the video it displays it normally.
我已经尝试过的是使用time.sleep()
等待一段时间,然后再次抓取帧.但这无济于事.
What i already tried is wait for some time using time.sleep()
before grabbing a frame again. But this does not help.
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Display the resulting frame
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
推荐答案
一种可能的方法是在循环中设置时间戳,并跟踪显示最后一帧的时间.例如,只有经过一定时间后,您才显示该帧.同时,您不断读取帧以保持缓冲区为空,以确保您拥有最新的帧.您不想使用time.sleep()
,因为它会冻结程序并且不会使缓冲区为空.时间戳击中后,您将显示框架并重置时间戳.
One potential way is to set a timestamp within the loop and keep track of the time the last frame was shown. For instance, only once a certain amount of time has elapsed then you show the frame. At the same time, you constantly read frames to keep the buffer empty to ensure that you have the most recent frame. You don't want to use time.sleep()
because it will freeze the program and not keep the buffer empty. Once the timestamp hits, you show the frame and reset the timestamp.
import cv2
import time
cap = cv2.VideoCapture(0)
# Timeout to display frames in seconds
# FPS = 1/TIMEOUT
# So 1/.025 = 40 FPS
TIMEOUT = .025
old_timestamp = time.time()
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
if (time.time() - old_timestamp) > TIMEOUT:
# Display the resulting frame
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
old_timestamp = time.time()
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
这篇关于使用opencv和python抓帧时如何保持恒定的FPS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!