forked from Sadaqaty/ASCII-Camera
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcamera_stream.py
More file actions
38 lines (33 loc) · 971 Bytes
/
camera_stream.py
File metadata and controls
38 lines (33 loc) · 971 Bytes
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
import cv2
import threading
class CameraStream:
def __init__(self, src=0):
"""
src: Camera index (default 0)
"""
self.src = src
self.cap = cv2.VideoCapture(self.src)
self.frame = None
self.running = False
self.thread = None
self.lock = threading.Lock()
def start(self):
if self.running:
return
self.running = True
self.thread = threading.Thread(target=self._update, daemon=True)
self.thread.start()
def _update(self):
while self.running:
ret, frame = self.cap.read()
if ret:
with self.lock:
self.frame = frame.copy()
def get_frame(self):
with self.lock:
return self.frame.copy() if self.frame is not None else None
def stop(self):
self.running = False
if self.thread:
self.thread.join()
self.cap.release()