|
a |
|
b/utils/webcamvideostream.py |
|
|
1 |
# import the necessary packages |
|
|
2 |
from threading import Thread |
|
|
3 |
import cv2 |
|
|
4 |
|
|
|
5 |
|
|
|
6 |
class WebcamVideoStream: |
|
|
7 |
def __init__(self, resolution, src=0, name="WebcamVideoStream"): |
|
|
8 |
# initialize the video camera stream and read the first frame |
|
|
9 |
# from the stream |
|
|
10 |
assert isinstance(resolution, tuple) and len(resolution) == 2 |
|
|
11 |
self.stream = cv2.VideoCapture(src) |
|
|
12 |
self.stream.set(3, resolution[0]) |
|
|
13 |
self.stream.set(4, resolution[1]) |
|
|
14 |
(self.grabbed, self.frame) = self.stream.read() |
|
|
15 |
|
|
|
16 |
# initialize the thread name |
|
|
17 |
self.name = name |
|
|
18 |
|
|
|
19 |
# initialize the variable used to indicate if the thread should |
|
|
20 |
# be stopped |
|
|
21 |
self.stopped = False |
|
|
22 |
|
|
|
23 |
def start(self): |
|
|
24 |
# start the thread to read frames from the video stream |
|
|
25 |
t = Thread(target=self.update, name=self.name, args=()) |
|
|
26 |
t.daemon = True |
|
|
27 |
t.start() |
|
|
28 |
return self |
|
|
29 |
|
|
|
30 |
def update(self): |
|
|
31 |
# keep looping infinitely until the thread is stopped |
|
|
32 |
while True: |
|
|
33 |
# if the thread indicator variable is set, stop the thread |
|
|
34 |
if self.stopped: |
|
|
35 |
return |
|
|
36 |
|
|
|
37 |
# otherwise, read the next frame from the stream |
|
|
38 |
(self.grabbed, self.frame) = self.stream.read() |
|
|
39 |
|
|
|
40 |
def read(self): |
|
|
41 |
# return the frame most recently read |
|
|
42 |
return self.frame |
|
|
43 |
|
|
|
44 |
def stop(self): |
|
|
45 |
# indicate that the thread should be stopped |
|
|
46 |
self.stopped = True |