Repository navigation
Expand file tree
/
Copy pathcamera_processor.py
More file actions
477 lines (402 loc) · 16.4 KB
/
Copy pathcamera_processor.py
File metadata and controls
477 lines (402 loc) · 16.4 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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
"""
Camera Processor Module - Traffic Counting Edge Device
High-performance camera capture and AI inference with mode-based filtering.
Runs as a daemon thread to avoid blocking the Flask server.
"""
import threading
import time
from collections.abc import Sequence
from typing import Any, ClassVar
import cv2
import config
import counting
import overlay
import tracks
# Conditional imports for Pi vs development
try:
from picamera2 import Picamera2
PI_CAMERA_AVAILABLE = True
except ImportError:
PI_CAMERA_AVAILABLE = False
print("[WARN] Picamera2 not available - using OpenCV fallback")
try:
from ultralytics import YOLO
YOLO_AVAILABLE = True
except ImportError:
YOLO_AVAILABLE = False
print("[WARN] Ultralytics not available - detection disabled")
class CameraProcessor:
"""
Manages camera capture, YOLO detection, object tracking, and line crossing counting.
Supports mode-based filtering: 'person' or 'vehicle'.
"""
# COCO class definitions
PERSON_CLASSES: ClassVar[list[int]] = [0] # person
VEHICLE_CLASSES: ClassVar[list[int]] = [2, 3, 5, 7] # car, motorcycle, bus, truck
CLASS_NAMES: ClassVar[dict[int, str]] = {
0: "person",
2: "car",
3: "motorcycle",
5: "bus",
7: "truck",
}
def __init__(
self,
resolution: tuple[int, int] = (640, 480),
framerate: int = 30,
video_path: str | None = None,
interval_seconds: float = 5,
) -> None:
self.resolution = resolution
self.framerate = framerate
self.video_path = video_path
self.interval_seconds = interval_seconds
# Thread control
self._running = False
self._thread = None
self._lock = threading.Lock()
# Frame buffer for streaming
self._current_frame = None
self._frame_lock = threading.Lock()
# Counters
self._count_in = 0
self._count_out = 0
# Virtual line coordinates [x1, y1, x2, y2]
self._line = [0, resolution[1] // 2, resolution[0], resolution[1] // 2]
# Detection mode: 'person' or 'vehicle'
self._mode = "person"
# Flip IN/OUT direction
self._flip_direction = False
# ROI (Region of Interest) - None means full frame
# Format: {'enabled': bool, 'x': int, 'y': int, 'width': int, 'height': int}
self._roi = None
self._tracks = tracks.TrackStore()
# Camera and model
self._camera = None
self._model = None
# FPS tracking
self._fps = 0
self._frame_times = []
# Interval JSON records
self._interval_in = 0
self._interval_out = 0
self._interval_start_time = None
self._interval_records = []
self._interval_lock = threading.Lock()
# Load saved configuration
self._load_config()
def _load_config(self):
"""Restore line, mode, direction and ROI from the last run."""
saved = config.load()
if not saved:
return
self._line = saved.get("line", self._line)
self._mode = saved.get("mode", "person")
self._flip_direction = saved.get("flip_direction", False)
self._roi = saved.get("roi", None)
roi_status = f", roi={self._roi['enabled']}" if self._roi else ""
print(
f"[INFO] Config loaded: mode={self._mode}, "
f"flip={self._flip_direction}, line={self._line}{roi_status}"
)
def _save_config(self):
"""Persist the current settings and counters."""
config.save(
{
"line": self._line,
"mode": self._mode,
"flip_direction": self._flip_direction,
"roi": self._roi,
"counts": {"in": self._count_in, "out": self._count_out},
}
)
def _get_active_classes(self):
"""Get YOLO class IDs based on current mode."""
if self._mode == "vehicle":
return self.VEHICLE_CLASSES
return self.PERSON_CLASSES
def _init_camera(self):
"""Initialize camera - video file, Picamera2 on Pi, OpenCV fallback, or test mode."""
if self.video_path:
self._camera = cv2.VideoCapture(self.video_path)
if self._camera.isOpened():
self._test_mode = False
print(f"[INFO] Video file opened: {self.video_path}")
else:
self._camera = None
self._test_mode = True
print(f"[WARN] Could not open video file: {self.video_path} - TEST MODE")
elif PI_CAMERA_AVAILABLE:
self._camera = Picamera2()
config = self._camera.create_preview_configuration(
main={"size": self.resolution, "format": "BGR888"}, buffer_count=4
)
self._camera.configure(config)
self._camera.start()
self._test_mode = False
print(f"[INFO] Picamera2 initialized at {self.resolution}")
else:
self._camera = cv2.VideoCapture(0)
if self._camera.isOpened():
self._camera.set(cv2.CAP_PROP_FRAME_WIDTH, self.resolution[0])
self._camera.set(cv2.CAP_PROP_FRAME_HEIGHT, self.resolution[1])
self._camera.set(cv2.CAP_PROP_FPS, self.framerate)
self._test_mode = False
print("[INFO] OpenCV VideoCapture initialized")
else:
self._camera = None
self._test_mode = True
print("[INFO] No camera found - running in TEST MODE")
def _init_model(self):
"""Initialize YOLO model."""
if YOLO_AVAILABLE:
self._model = YOLO("yolo11n_ncnn_model")
print("[INFO] YOLOv11n NCNN model loaded")
else:
print("[WARN] Running without detection model")
def _capture_frame(self):
"""Capture a frame from the camera."""
if PI_CAMERA_AVAILABLE and self._camera and not self.video_path:
frame = self._camera.capture_array("main")
# Swap R and B channels
return frame[:, :, ::-1].copy()
elif self._camera:
ret, frame = self._camera.read()
if not ret or frame is None:
if self.video_path:
self._camera.set(cv2.CAP_PROP_POS_FRAMES, 0)
self.reset_counts()
return None
h, w = frame.shape[:2]
if (w, h) != self.resolution:
frame = cv2.resize(frame, self.resolution)
return frame
return None
def _process_frame(self, frame):
"""Run detection, tracking, and counting on a frame."""
if frame is None:
return None
display_frame = frame.copy()
overlay.draw_line(display_frame, self._line)
if self._model is None:
self._draw_hud(display_frame)
return display_frame
# ROI processing - crop frame if ROI is enabled
roi_offset_x, roi_offset_y = 0, 0
detect_frame = frame
if self._roi and self._roi.get("enabled", False):
rx = max(0, self._roi.get("x", 0))
ry = max(0, self._roi.get("y", 0))
rw = self._roi.get("width", frame.shape[1])
rh = self._roi.get("height", frame.shape[0])
# Clamp to frame bounds
rx = min(rx, frame.shape[1] - 1)
ry = min(ry, frame.shape[0] - 1)
rw = min(rw, frame.shape[1] - rx)
rh = min(rh, frame.shape[0] - ry)
# Only crop if ROI is large enough (min 100x100)
if rw >= 100 and rh >= 100:
detect_frame = frame[ry : ry + rh, rx : rx + rw]
roi_offset_x, roi_offset_y = rx, ry
overlay.draw_roi(display_frame, rx, ry, rw, rh)
# Run YOLO tracking with mode-based class filtering
active_classes = self._get_active_classes()
results = self._model.track(
detect_frame,
persist=True,
tracker="bytetrack.yaml",
classes=active_classes,
verbose=False,
)
if results[0].boxes is None or results[0].boxes.id is None:
self._draw_hud(display_frame)
return display_frame
boxes = results[0].boxes.xyxy.cpu().numpy()
track_ids = results[0].boxes.id.cpu().numpy().astype(int)
# Apply ROI offset to boxes
if roi_offset_x > 0 or roi_offset_y > 0:
boxes[:, 0] += roi_offset_x # x1
boxes[:, 1] += roi_offset_y # y1
boxes[:, 2] += roi_offset_x # x2
boxes[:, 3] += roi_offset_y # y2
classes = results[0].boxes.cls.cpu().numpy().astype(int)
now = time.time()
for box, track_id, cls in zip(boxes, track_ids, classes, strict=False):
x1, y1, x2, y2 = map(int, box)
center = counting.bottom_center((x1, y1, x2, y2))
self._tracks.seen(track_id, center, now)
movement = self._tracks.previous_and_current(track_id)
if not self._tracks.is_counted(track_id) and movement is not None:
prev_point, curr_point = movement
direction = counting.crossed(
self._line, prev_point, curr_point, self._flip_direction
)
if direction is not None:
with self._lock:
if direction == "in":
self._count_in += 1
else:
self._count_out += 1
self._tracks.mark_counted(track_id)
self._save_config()
with self._interval_lock:
if direction == "in":
self._interval_in += 1
else:
self._interval_out += 1
print(
f"[COUNT] {self.CLASS_NAMES.get(cls, 'obj')} #{track_id} -> "
f"{direction.upper()} | Total: IN={self._count_in}, "
f"OUT={self._count_out}"
)
overlay.draw_detection(
display_frame,
box=(x1, y1, x2, y2),
label=f"{self.CLASS_NAMES.get(cls, 'obj')} #{track_id}",
counted=self._tracks.is_counted(track_id),
trail=self._tracks.trail(track_id),
center=center,
)
forgotten = self._tracks.sweep(now)
if forgotten:
print(f"[INFO] Forgot {forgotten} stale track(s), {len(self._tracks)} still active")
self._draw_hud(display_frame)
return display_frame
def _draw_hud(self, frame):
"""Counters, frame rate and direction arrows."""
overlay.draw_hud(frame, self._fps, self._count_in, self._count_out)
overlay.draw_direction(frame, self._line, self._flip_direction)
def _check_interval(self):
"""Emit a JSON interval record if enough time has passed."""
now = time.time()
if self._interval_start_time is None:
self._interval_start_time = now
return
if now - self._interval_start_time >= self.interval_seconds:
from datetime import datetime
with self._interval_lock:
record = {
"from": datetime.fromtimestamp(self._interval_start_time).strftime(
"%Y-%m-%dT%H:%M:%S"
),
"to": datetime.fromtimestamp(now).strftime("%Y-%m-%dT%H:%M:%S"),
"in": self._interval_in,
"out": self._interval_out,
}
self._interval_in = 0
self._interval_out = 0
self._interval_start_time = now
self._interval_records.append(record)
if len(self._interval_records) > 200:
self._interval_records.pop(0)
print(f"[INTERVAL] {record}")
def _run(self):
"""Main processing loop - runs in daemon thread."""
self._init_camera()
self._init_model()
while self._running:
frame_start = time.time()
frame = self._capture_frame()
if frame is None:
time.sleep(0.01)
continue
self._check_interval()
processed = self._process_frame(frame)
if processed is not None:
_, buffer = cv2.imencode(".jpg", processed, [cv2.IMWRITE_JPEG_QUALITY, 92])
with self._frame_lock:
self._current_frame = buffer.tobytes()
# Calculate FPS
self._frame_times.append(time.time() - frame_start)
if len(self._frame_times) > 30:
self._frame_times.pop(0)
if self._frame_times:
self._fps = 1.0 / (sum(self._frame_times) / len(self._frame_times))
time.sleep(0.001) # Small yield for other threads
# Cleanup
if PI_CAMERA_AVAILABLE and self._camera:
self._camera.stop()
elif self._camera:
self._camera.release()
print("[INFO] Camera processor stopped")
def start(self) -> None:
"""Start the camera processor in a daemon thread."""
if self._running:
return
self._running = True
self._thread = threading.Thread(target=self._run, daemon=True)
self._thread.start()
print("[INFO] Camera processor started")
def stop(self) -> None:
"""Stop the camera processor."""
self._running = False
if self._thread:
self._thread.join(timeout=2)
def get_frame(self) -> bytes | None:
"""The latest frame as encoded JPEG bytes, or None before the first one."""
with self._frame_lock:
return self._current_frame
def get_data(self) -> dict[str, Any]:
"""Everything a client needs: counts, line, mode, roi, fps, resolution."""
with self._lock:
return {
"counts": {"in": self._count_in, "out": self._count_out},
"line": self._line.copy(),
"mode": self._mode,
"flip_direction": self._flip_direction,
"roi": self._roi.copy() if self._roi else None,
"fps": round(self._fps, 1),
"resolution": list(self.resolution),
}
def reset_counts(self) -> None:
"""Reset counters to zero."""
with self._lock:
self._count_in = 0
self._count_out = 0
self._tracks.clear()
self._save_config()
print("[INFO] Counters reset")
def update_config(
self,
line: Sequence[int] | None = None,
mode: str | None = None,
flip_direction: bool | None = None,
) -> None:
"""Update line coordinates, mode, and/or direction."""
with self._lock:
if line is not None:
self._line = [int(x) for x in line]
self._tracks.clear() # a new line invalidates past crossings
if mode is not None and mode in ("person", "vehicle") and mode != self._mode:
self._mode = mode
self._tracks.clear()
if flip_direction is not None:
self._flip_direction = bool(flip_direction)
self._save_config()
print(
f"[INFO] Config updated: mode={self._mode}, "
f"flip={self._flip_direction}, line={self._line}"
)
def update_roi(self, roi: dict[str, Any] | None) -> None:
"""Update ROI configuration."""
with self._lock:
if roi is None:
self._roi = None
else:
self._roi = {
"enabled": bool(roi.get("enabled", False)),
"x": int(roi.get("x", 0)),
"y": int(roi.get("y", 0)),
"width": int(roi.get("width", self.resolution[0])),
"height": int(roi.get("height", self.resolution[1])),
}
self._save_config()
roi_status = f"enabled={self._roi['enabled']}" if self._roi else "disabled"
print(f"[INFO] ROI updated: {roi_status}")
def get_latest_records(self, n: int = 50) -> list[dict[str, Any]]:
"""Get last n interval records (thread-safe)."""
with self._interval_lock:
return list(self._interval_records[-n:])
def get_resolution(self) -> tuple[int, int]:
"""Get camera resolution."""
return self.resolution