Last active
December 7, 2022 15:59
-
-
Save allskyee/7749b9318e914ca45eb0a1000a81bf56 to your computer and use it in GitHub Desktop.
opencv python camera frame grab and display on different threads with safe synchronization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from threading import Thread, Lock | |
import cv2 | |
class WebcamVideoStream : | |
def __init__(self, src = 0, width = 320, height = 240) : | |
self.stream = cv2.VideoCapture(src) | |
self.stream.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH, width) | |
self.stream.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT, height) | |
(self.grabbed, self.frame) = self.stream.read() | |
self.started = False | |
self.read_lock = Lock() | |
def start(self) : | |
if self.started : | |
print "already started!!" | |
return None | |
self.started = True | |
self.thread = Thread(target=self.update, args=()) | |
self.thread.start() | |
return self | |
def update(self) : | |
while self.started : | |
(grabbed, frame) = self.stream.read() | |
self.read_lock.acquire() | |
self.grabbed, self.frame = grabbed, frame | |
self.read_lock.release() | |
def read(self) : | |
self.read_lock.acquire() | |
frame = self.frame.copy() | |
self.read_lock.release() | |
return frame | |
def stop(self) : | |
self.started = False | |
self.thread.join() | |
def __exit__(self, exc_type, exc_value, traceback) : | |
self.stream.release() | |
if __name__ == "__main__" : | |
vs = WebcamVideoStream().start() | |
while True : | |
frame = vs.read() | |
cv2.imshow('webcam', frame) | |
if cv2.waitKey(1) == 27 : | |
break | |
vs.stop() | |
cv2.destroyAllWindows() |
FYI for those who stumble upon this gist, I have written a python library for this exact purpose.
https://github.com/nup002/Threaded-VideoCapture
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Good job ! I want to ask you a question privately, how can I contact you ?