Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
opencv python camera frame grab and display on different threads with safe synchronization
#!/usr/bin/env python
from threading import Thread, Lock
import cv2
class WebcamVideoStream :
def __init__(self, src = 0, width = 320, height = 240) : = cv2.VideoCapture(src), width), height)
(self.grabbed, self.frame) =
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=())
return self
def update(self) :
while self.started :
(grabbed, frame) =
self.grabbed, self.frame = grabbed, frame
def read(self) :
frame = self.frame.copy()
return frame
def stop(self) :
self.started = False
def __exit__(self, exc_type, exc_value, traceback) :
if __name__ == "__main__" :
vs = WebcamVideoStream().start()
while True :
frame =
cv2.imshow('webcam', frame)
if cv2.waitKey(1) == 27 :
Copy link

tejasa97 commented Aug 31, 2018

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)

Copy link

dscha09 commented Sep 5, 2018

I am getting this error:

AttributeError: module 'cv2.cv2' has no attribute 'cv'

Copy link

ecyoung3 commented Sep 13, 2018

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

Copy link

raggot commented Sep 26, 2018

Thank you! Very cool.
If someone else gets AttributeError: 'NoneType' object has no attribute 'copy', make sure your webcam is connected... :)

Copy link

jishang1602 commented Oct 31, 2020

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?

Copy link

KerolosMelad commented Jun 19, 2021

Good job ! I want to ask you a question privately, how can I contact you ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment