【发布时间】:2021-04-22 07:16:21
【问题描述】:
我正在尝试将从笔记本电脑摄像头捕获的帧写入循环缓冲区。我想创建一个线程来处理这个任务(以异步方式)。当我尝试获取使用get_last() 方法存储的最后一帧并显示它时,会显示黑屏。我花了相当长的时间找出原因,但一切都在脉络中。恕我直言,这段代码应该有一个小问题,但看不到它。任何帮助将不胜感激。完整的工作代码如下所示:
import cv2
import sys
import time
import threading
class CamBuffer(threading.Thread):
def __init__(self, stream=0):
self.current = 0
self.max_size = 5
self.buffer = [None] * self.max_size
self.capture = cv2.VideoCapture(stream)
if not self.capture.isOpened():
print("Could not open video")
sys.exit()
print("Opened video")
self.running = True
super().__init__()
def run(self):
print('running thread')
while self.running:
print('capturing frame ', self.current)
_, frame = self.capture.read()
if _:
print('saving frame ', self.current)
self.buffer[self.current] = frame
self.current = self.current + 1
if (self.current >= self.max_size):
self.current = 0
self.capture.release()
print('stopped thread')
def terminate(self):
print('terminating thread')
self.running = False
def get_last(self):
current = 0
if self.current > 0:
current = self.current - 1
print('get_last()', current)
return self.buffer[current]
if __name__ == "__main__":
print('Frame buffer test')
stream = 0
cb = CamBuffer(stream)
cb.start()
time.sleep(1.25)
frame = cb.get_last()
if frame is not None:
print('showing frame')
cv2.imshow('Frame', frame)
time.sleep(3)
cb.terminate()
cv2.destroyAllWindows()
print('Frame buffer test [Done]')
【问题讨论】:
-
您必须在
cv2.imshow()之后调用cv2.waitKey(),因为它使用这段时间来更新显示-我发现我需要至少30 作为cv2.waitKey()的参数,而在macOS 上,所以也许从 30 开始。你不应该在任何地方的代码中调用time.sleep()。
标签: python python-3.x opencv python-multithreading circular-buffer