-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcamera.py
More file actions
38 lines (33 loc) · 1.01 KB
/
Copy pathcamera.py
File metadata and controls
38 lines (33 loc) · 1.01 KB
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 CameraAsync:
def __init__(self, width, height):
self.width = width
self.height = height
self.cap = None
self.ready = False
self.lock = threading.Lock()
threading.Thread(target=self._init_camera, daemon=True).start()
def _init_camera(self):
cam = cv2.VideoCapture(0)
cam.set(cv2.CAP_PROP_FRAME_WIDTH, self.width)
cam.set(cv2.CAP_PROP_FRAME_HEIGHT, self.height)
with self.lock:
self.cap = cam
self.ready = cam.isOpened()
def read(self):
if not self.ready:
return False, None
with self.lock:
if self.cap and self.cap.isOpened():
return self.cap.read()
return False, None
def release(self):
with self.lock:
if self.cap:
try:
self.cap.release()
except Exception:
pass
self.cap = None
self.ready = False