-
Notifications
You must be signed in to change notification settings - Fork 1
/
opencv_webcam_multithread.py
40 lines (33 loc) · 1.05 KB
/
opencv_webcam_multithread.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# coding=utf-8
from threading import Thread, Lock
import cv2
class WebcamVideoStream:
def __init__(self, src=0):
self.thread = Thread(target=self.update, args=())
self.stream = cv2.VideoCapture(src)
(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.start()
return self
def update(self):
while self.started:
(grabbed, stream_frame) = self.stream.read()
self.read_lock.acquire()
self.grabbed, self.frame = grabbed, stream_frame
self.read_lock.release()
def read(self):
self.read_lock.acquire()
cam_frame = self.frame.copy()
self.read_lock.release()
return cam_frame
def stop(self):
self.started = False
self.thread.join()
def __exit__(self, exc_type, exc_value, traceback):
self.stream.release()