-
-
Save allskyee/7749b9318e914ca45eb0a1000a81bf56 to your computer and use it in GitHub Desktop.
#!/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() |
I am getting this error:
AttributeError: module 'cv2.cv2' has no attribute 'cv'
I am getting this error:
AttributeError: module 'cv2.cv2' has no attribute 'cv'
You probably need to change them to cv2.CAP_PROP_FRAME_WIDTH and HEIGHT respectively, that should solve the problem
Thank you! Very cool.
If someone else gets AttributeError: 'NoneType' object has no attribute 'copy'
, make sure your webcam is connected... :)
The code is working fine. But I want to implement it for restarted source. E.g. if I am running in background. If the camera is going to restart after 2-3 hours the code should accept it without re-run it. Cloud it be possible?
Good job ! I want to ask you a question privately, how can I contact you ?
FYI for those who stumble upon this gist, I have written a python library for this exact purpose.
https://github.com/nup002/Threaded-VideoCapture
Do you suppose the read method along with imshow also could be threaded? So that it is always reading and displaying from stream while the main function is idle? (i.e : you can do other stuff in the main function)