-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcamera.py
More file actions
45 lines (39 loc) · 1.45 KB
/
camera.py
File metadata and controls
45 lines (39 loc) · 1.45 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
39
40
41
42
43
44
45
import cv2
import threading
import time
class Camera:
def __init__(self, device_index=0, width=640, height=480, fps=30):
self.device_index = device_index
self.cap = cv2.VideoCapture(self.device_index, cv2.CAP_ANY)
# Try to set format (not all cams will accept)
self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
self.cap.set(cv2.CAP_PROP_FPS, fps)
if not self.cap.isOpened():
raise RuntimeError(f"Could not open video device {device_index}")
self.lock = threading.Lock()
self.frame = None
self.running = True
self.thread = threading.Thread(target=self._reader, daemon=True)
self.thread.start()
def _reader(self):
# Always read the latest frame; drop old frames to reduce latency.
while self.running:
ret, frame = self.cap.read()
if not ret:
time.sleep(0.01)
continue
# JPEG encode for MJPEG streaming
ok, buf = cv2.imencode(".jpg", frame, [int(cv2.IMWRITE_JPEG_QUALITY), 80])
if not ok:
continue
with self.lock:
self.frame = buf.tobytes()
def get_jpeg(self):
with self.lock:
return self.frame
def close(self):
self.running = False
if self.thread.is_alive():
self.thread.join(timeout=1.0)
self.cap.release()