forked from Sven97/Obstacle-Alart-Server-Side
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebcam.py
36 lines (27 loc) · 1003 Bytes
/
webcam.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
from threading import Thread
import cv2
# Allows for significant reduction in latency when reading from camera
class WebcamVideoStream:
def __init__(self, src=0):
# Initialize camera stream and read first frame
self.stream = cv2.VideoCapture(src)
_, self.frame = self.stream.read()
# Keep track of whether thread should be stopped
self.stopped = False
def start(self):
# Initialize and start thread responsible for reading frames from camera stream
Thread(target=self.update, args=()).start()
return self
def update(self):
# Continuously read frames until stopped is True
while self.stream.isOpened():
if self.stopped:
return
_, self.frame = self.stream.read()
def read(self):
# Get latest frame
return self.frame
def stop(self):
print("-> Stopping stream")
# Indicate thread should be stopped
self.stopped = True