Skip to content

Instantly share code, notes, and snippets.

@T1T4N
Created July 27, 2016 14:27
Show Gist options
  • Save T1T4N/845feb4c258045983580ab32bb4fa148 to your computer and use it in GitHub Desktop.
Save T1T4N/845feb4c258045983580ab32bb4fa148 to your computer and use it in GitHub Desktop.
OpenCV webcam capture in a separate thread
class WebcamVideoStream:
def __init__(self, src=0):
# initialize the video camera stream and read the first frame
# from the stream
self.stream = cv2.VideoCapture(src)
(self.grabbed, self.frame) = self.stream.read()
# initialize the variable used to indicate if the thread should
# be stopped
self.stopped = False
self.__thread = Thread(target=self.update, args=())
def start(self):
# start the thread to read frames from the video stream
self.__thread.start()
return self
def update(self):
# keep looping infinitely until the thread is stopped
while True:
# if the thread indicator variable is set, stop the thread
if self.stopped:
return
# otherwise, read the next frame from the stream
(self.grabbed, self.frame) = self.stream.read()
def read(self):
# return the frame most recently read
return self.grabbed, self.frame
def stop(self):
# indicate that the thread should be stopped
self.stopped = True
def get_stream(self):
return self.stream
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment