opencv-python的默认读取相机视频方式是一帧一帧读入采集的图像,如果处理速率跟不上相机读取速率,就会发现opencv-python处理的不是当前帧,而是之前积压的帧。
所以需要每次读取最新帧。
import cv2, Queue, threading, time
# bufferless VideoCapture
class VideoCapture:
def __init__(self, name):
self.cap = cv2.VideoCapture(name)
self.q = Queue.Queue()
t = threading.Thread(target=self._reader)
t.daemon = True
t.start()
# read frames as soon as they are available, keeping only most recent one
def _reader(self):
while True:
ret, frame = self.cap.read()
if not ret:
break
if not self.q.empty():
try:
self.q.get_nowait() # discard previous (unprocessed) frame
except Queue.Empty:
pass
self.q.put(frame)
def read(self):
return self.q.get()
cap = VideoCapture(0)
while True:
time.sleep(.5) # simulate time between events
frame = cap.read()
cv2.imshow("frame", frame)
if chr(cv2.waitKey(1)&255) == 'q':
break
本文介绍了一种使用Opencv-Python进行实时视频处理的方法,通过创建一个自定义的VideoCapture类,确保每次都能读取到最新的帧,避免了由于处理速率跟不上相机读取速率而导致的帧积压问题。

被折叠的 条评论
为什么被折叠?



