-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcamera.py
More file actions
241 lines (193 loc) Β· 7.54 KB
/
Copy pathcamera.py
File metadata and controls
241 lines (193 loc) Β· 7.54 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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
"""
Camera abstraction: real Pi Camera and simulation modes.
"""
import time
import numpy as np
from abc import ABC, abstractmethod
from typing import Optional, Tuple
# Pi Camera is imported lazily to allow simulation on non-Pi machines
class CameraBase(ABC):
"""Abstract camera interface."""
@abstractmethod
def capture(self) -> Optional[np.ndarray]:
"""Capture a grayscale frame. Returns None on failure."""
...
@abstractmethod
def release(self):
"""Release camera resources."""
...
@property
@abstractmethod
def resolution(self) -> Tuple[int, int]:
"""(width, height) of captured frames."""
...
class PiCamera(CameraBase):
"""Real Pi Camera using picamera2 (Bookworm+)."""
def __init__(self, resolution: Tuple[int, int] = (640, 480), fps: int = 10):
self._resolution = resolution
self._fps = fps
self._camera = None
try:
from picamera2 import Picamera2
self._camera = Picamera2()
config = self._camera.create_preview_configuration(
main={"size": resolution, "format": "YUV420"}
)
self._camera.configure(config)
self._camera.start()
time.sleep(0.5) # Warmup
except ImportError:
raise RuntimeError(
"picamera2 not installed. On Pi: pip install picamera2\n"
"On desktop: use SimCamera for testing."
)
def capture(self) -> Optional[np.ndarray]:
if self._camera is None:
return None
frame = self._camera.capture_array("main")
# YUV420 -> grayscale
y = frame[: self._resolution[1], : self._resolution[0]]
return np.asarray(y, dtype=np.uint8)
def release(self):
if self._camera:
self._camera.stop()
@property
def resolution(self) -> Tuple[int, int]:
return self._resolution
class USBCamera(CameraBase):
"""USB webcam using OpenCV VideoCapture. Works on macOS, Linux, Windows."""
def __init__(self,
device: int = 0,
resolution: Tuple[int, int] = (640, 480),
api_preference: int = None):
"""
Args:
device: Camera index (0 = built-in, 1 = first USB, etc.)
resolution: Desired capture resolution
api_preference: cv2.CAP_AVFOUNDATION (macOS), cv2.CAP_V4L2 (Linux), etc.
Auto-detected if None.
"""
import cv2
self._resolution = resolution
if api_preference is None:
# Auto-detect best backend
import platform
system = platform.system()
if system == "Darwin":
api_preference = cv2.CAP_AVFOUNDATION
elif system == "Linux":
api_preference = cv2.CAP_V4L2
else:
api_preference = cv2.CAP_DSHOW # Windows
self._cap = cv2.VideoCapture(device, api_preference)
if not self._cap.isOpened():
raise RuntimeError(
f"Cannot open camera {device}. Try a different device number (0-3).\n"
f"On macOS, check System Preferences β Privacy β Camera."
)
self._cap.set(cv2.CAP_PROP_FRAME_WIDTH, resolution[0])
self._cap.set(cv2.CAP_PROP_FRAME_HEIGHT, resolution[1])
self._cap.set(cv2.CAP_PROP_FPS, 30)
# Warmup: discard first few frames (auto-exposure settling)
for _ in range(5):
self._cap.read()
# Read actual resolution (camera may not support requested)
actual_w = int(self._cap.get(cv2.CAP_PROP_FRAME_WIDTH))
actual_h = int(self._cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
if (actual_w, actual_h) != resolution:
print(f" Camera actual resolution: {actual_w}x{actual_h} (requested {resolution[0]}x{resolution[1]})")
self._resolution = (actual_w, actual_h)
def capture(self) -> Optional[np.ndarray]:
if self._cap is None:
return None
ret, frame = self._cap.read()
if not ret:
return None
import cv2
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
return gray
def release(self):
if self._cap:
self._cap.release()
self._cap = None
@property
def resolution(self) -> Tuple[int, int]:
return self._resolution
class SimCamera(CameraBase):
"""
Simulated camera for testing on desktop.
Flies a virtual drone over the map image.
"""
def __init__(self,
map_path: str,
resolution: Tuple[int, int] = (640, 480),
altitude_m: float = 50.0,
gsd_cm_per_px: float = 3.0):
import cv2
self._map = cv2.imread(map_path)
if self._map is None:
raise FileNotFoundError(f"Cannot read map: {map_path}")
self._map_gray = cv2.cvtColor(self._map, cv2.COLOR_BGR2GRAY)
self._map_h, self._map_w = self._map_gray.shape
self._resolution = resolution
self._altitude = altitude_m
self._gsd = gsd_cm_per_px
# Drone position on map (center of image)
self._drone_x = self._map_w / 2
self._drone_y = self._map_h / 2
self._heading = 0.0 # degrees, 0=up/north
# Waypoints for figure-8 pattern
self._t = 0.0
def _simulated_position(self) -> Tuple[float, float, float]:
"""
Generate a figure-8 flight path over the map.
Returns (px, py, heading_deg).
"""
self._t += 0.02
# Figure-8: x = sin(t), y = sin(2t)/2
amp_x = self._map_w * 0.35
amp_y = self._map_h * 0.2
offset_x = self._map_w / 2 + np.sin(self._t) * amp_x
offset_y = self._map_h / 2 + np.sin(2 * self._t) * amp_y / 2
# Heading follows the curve tangent
dx = np.cos(self._t) * amp_x
dy = np.cos(2 * self._t) * amp_y
heading = np.degrees(np.arctan2(dx, dy)) % 360
return offset_x, offset_y, heading
def capture(self) -> Optional[np.ndarray]:
self._drone_x, self._drone_y, self._heading = self._simulated_position()
# Extract viewport from map
viewport_m = self._altitude * self._gsd / 100.0 # viewport width in meters
px_per_m = self._map_w / (self._map_w * self._gsd / 100.0) # approximate
viewport_px = int(viewport_m * px_per_m)
viewport_px = min(viewport_px, self._map_w, self._map_h)
half = viewport_px // 2
x0 = int(max(0, self._drone_x - half))
y0 = int(max(0, self._drone_y - half))
x1 = int(min(self._map_w, self._drone_x + half))
y1 = int(min(self._map_h, self._drone_y + half))
if x1 <= x0 or y1 <= y0:
return np.zeros((self._resolution[1], self._resolution[0]), dtype=np.uint8)
crop = self._map_gray[y0:y1, x0:x1]
# Add slight blur to simulate real camera
import cv2
crop = cv2.GaussianBlur(crop, (3, 3), 0.5)
# Resize to camera resolution
frame = cv2.resize(crop, self._resolution)
# Add small noise
noise = np.random.normal(0, 2, frame.shape).astype(np.uint8)
frame = cv2.add(frame, noise)
return frame
@property
def ground_truth(self) -> dict:
"""Return true position for evaluation."""
return {
"x_px": self._drone_x,
"y_px": self._drone_y,
"heading_deg": self._heading,
}
def release(self):
pass
@property
def resolution(self) -> Tuple[int, int]:
return self._resolution