【发布时间】:2020-11-09 15:11:42
【问题描述】:
我正在使用Nathancy's SO code 从磁盘并行读取两个静态视频,利用多线程。以下修改后的代码对我来说非常好:
from threading import Thread
import cv2, time
class VideoStreamWidget(object):
def __init__(self, src=0):
self.capture = cv2.VideoCapture(src)
# Start the thread to read frames from the video stream
self.thread = Thread(target=self.update, args=())
self.thread.daemon = True
self.thread.start()
def update(self):
# Read the next frame from the stream in a different thread
while True:
if self.capture.isOpened():
(self.status, self.image) = self.capture.read()
self.frame = cv2.resize(self.image, (640, 480))
time.sleep(.01)
def show_frame(self, win_name='frame_1'):
# Display frames in main program
cv2.imshow(win_name, self.frame)
key = cv2.waitKey(1)
if key == ord('q'):
self.capture.release()
cv2.destroyAllWindows()
exit(1)
if __name__ == '__main__':
video_stream_widget1 = VideoStreamWidget(src=r'C:\Users\ab\Documents\Video\ch6.asf')
video_stream_widget2 = VideoStreamWidget(
src=r'C:\Users\ab\Documents\Video\ch4.asf')
while True:
try:
video_stream_widget1.show_frame('frame_1')
video_stream_widget2.show_frame('frame_2')
except AttributeError:
pass
现在我正在尝试调整上面的代码,因为我想在类外部创建一个 while 循环,并从 capture.read() 函数中获取状态和图像,以供其他代码在循环中逐帧使用.但是,它甚至不适用于带有此(断言 fctx->async_lock failed at libavcodec/pthread_frame.c:155)错误的单个视频流。代码如下:
from threading import Thread
import cv2, time
class VideoStreamWidget(object):
def __init__(self, src=0):
self.capture = cv2.VideoCapture(src)
# Start the thread to read frames from the video stream
self.thread = Thread(target=self.update, args=())
self.thread.daemon = True
self.thread.start()
def update(self):
# Read the next frame from the stream in a different thread
while True:
if self.capture.isOpened():
(self.status, self.image) = self.capture.read()
self.frame = cv2.resize(self.image, (640, 480))
# time.sleep(.01)
# def show_frame(self, win_name='frame_1'):
# # Display frames in main program
# cv2.imshow(win_name, self.frame)
# key = cv2.waitKey(1)
# if key == ord('q'):
# self.capture.release()
# cv2.destroyAllWindows()
# exit(1)
if __name__ == '__main__':
video_stream_widget1 = VideoStreamWidget(src=r'C:\Users\ab\Documents\Video\ch6.asf')
# video_stream_widget2 = VideoStreamWidget(
# src=r'C:\Users\ab\Documents\Video\ch4.asf')
# while True:
# try:
# video_stream_widget1.show_frame('frame_1')
# video_stream_widget2.show_frame('frame_2')
# except AttributeError:
# pass
while True:
vflag, image_np = video_stream_widget1.status, video_stream_widget1.frame
print(image_np)
这是一个 setter getter 问题吗?你能帮忙指出我哪里出错了吗?
【问题讨论】:
标签: python-3.x multithreading opencv python-multithreading video-capture