I am using Nathancy's SO code to read two static videos from disk in parallel, leveraging multithreading. The below modified code works perfectly fine for me:
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
Now I'm trying to tweak through the above code as I want to create a while loop outside the class and get status and image from capture.read() function to be used by other codes in a loop, frame by frame. But, it is not working for even single video stream with this (Assertion fctx->async_lock failed at libavcodec/pthread_frame.c:155) error. Code is as follows:
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)
Is it a setter getter problem? Can you help point out where am I going wrong?