-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcamera_handler.py
More file actions
105 lines (79 loc) · 2.78 KB
/
Copy pathcamera_handler.py
File metadata and controls
105 lines (79 loc) · 2.78 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
"""
Camera Handler
Manages webcam interface using OpenCV
"""
import cv2
import numpy as np
from typing import Optional, Tuple
class CameraHandler:
def __init__(self, camera_index: int = 0, width: int = 640, height: int = 480):
"""
Initialize camera handler
Args:
camera_index: Camera device index (usually 0 for default webcam)
width: Frame width
height: Frame height
"""
self.camera_index = camera_index
self.width = width
self.height = height
self.capture = None
self.is_active = False
def start(self) -> bool:
"""
Start the camera
Returns:
True if successful, False otherwise
"""
if self.is_active:
return True
self.capture = cv2.VideoCapture(self.camera_index)
if not self.capture.isOpened():
return False
# Set camera properties
self.capture.set(cv2.CAP_PROP_FRAME_WIDTH, self.width)
self.capture.set(cv2.CAP_PROP_FRAME_HEIGHT, self.height)
self.is_active = True
return True
def stop(self):
"""Stop the camera and release resources"""
if self.capture is not None:
self.capture.release()
self.capture = None
self.is_active = False
def read_frame(self) -> Tuple[bool, Optional[np.ndarray]]:
"""
Read a frame from the camera
Returns:
(success, frame) tuple where frame is in RGB format
"""
if not self.is_active or self.capture is None:
return False, None
ret, frame = self.capture.read()
if not ret:
return False, None
# Flip horizontally for mirror effect
frame = cv2.flip(frame, 1)
# Convert BGR to RGB (face_recognition uses RGB)
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
return True, frame_rgb
def get_bgr_frame(self) -> Tuple[bool, Optional[np.ndarray]]:
"""
Read a frame in BGR format (for OpenCV display)
Returns:
(success, frame) tuple where frame is in BGR format
"""
if not self.is_active or self.capture is None:
return False, None
ret, frame = self.capture.read()
if not ret:
return False, None
# Flip horizontally for mirror effect
frame = cv2.flip(frame, 1)
return True, frame
def is_running(self) -> bool:
"""Check if camera is currently active"""
return self.is_active
def __del__(self):
"""Cleanup when object is destroyed"""
self.stop()