In my program, i want to show the camera stream and gui in apart. I think i have to use thread for this in python but i dont know how to do that?
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Display the resulting frame
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
How can i change above code to open a new window and display the video stream with thread.
I hope I understand you correctly, that you want to run:
Consider then the following code:
import cv2
import threading
from threading import Event
class multi_thread_stream:
def __init__(self, ready=None):
self.ready = ready
self.cap = cv2.VideoCapture(0)
self.frame = {}
#Create the Threads
self.t1 = threading.Thread(target=self.capture_stream)
self.t2 = threading.Thread(target=self.display_image)
self.t1.name = 'capture_thread'
self.t2.name = 'display_thread'
self.t1.start()
self.t2.start()
def capture_stream(self):
while True:
# Capture frame-by-frame
self.ret, self.frame = self.cap.read()
self.ready.set()
if cv2.waitKey(1) & 0xFF == ord('q'):
break
def display_image(self):
while True:
# Display the resulting frame
self.ready.wait()
cv2.imshow('frame_2nd_trhead', self.frame)
self.ready.clear()
if cv2.waitKey(1) & 0xFF == ord('q'):
break;
def __del__(self):
# When everything done, release the capture
self.cap.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
ready = Event()
mts = multi_thread_stream(ready)
mts.t1.join()
mts.t2.join()
There are two functions, that run in two threads. The display-thread waits for a trigger and until the capture-thread has already read a frame and sent a trigger to the display-thread, the display-thread cannot continue further and hence cannot show an image (or throw an error of invalid variable size).
Hope it helps. (or at least it can be a basis for your further solution).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.