File size: 4,682 Bytes
40e0b51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Frame annotation: boxes + labels + traces + HUD overlay."""
from __future__ import annotations

from datetime import datetime

import cv2
import numpy as np
import supervision as sv

from app.config import settings
from app.services.analytics import Snapshot, crowd_status, traffic_status

class FrameAnnotator:
    """Per-camera annotator bundle. `TraceAnnotator` keeps mutable history
    state internally; sharing one instance across threads causes
    `IndexError: boolean index did not match indexed array` when the
    internal xy / tracker_id buffers race. One bundle per camera fixes it."""

    def __init__(self, trace_length: int = 20,
                 class_names: dict[int, str] | None = None):
        self.box = sv.BoxAnnotator(thickness=2)
        self.label = sv.LabelAnnotator(text_scale=0.45, text_thickness=1, text_padding=3)
        self.trace = sv.TraceAnnotator(thickness=1, trace_length=trace_length)
        self.class_names = class_names or {}

    def annotate(self, frame: np.ndarray, detections: sv.Detections) -> np.ndarray:
        out = frame.copy()
        has_tracks = (
            detections.tracker_id is not None
            and len(detections) > 0
            and len(detections.tracker_id) == len(detections)
        )
        if has_tracks:
            try:
                out = self.trace.annotate(scene=out, detections=detections)
            except (IndexError, ValueError):
                # If trace state ever gets out of sync, reset and continue.
                self.trace = sv.TraceAnnotator(thickness=1, trace_length=20)

        out = self.box.annotate(scene=out, detections=detections)

        if has_tracks:
            labels = [
                f"#{int(tid)} {self.class_names.get(int(cid), 'obj')} {float(conf):.2f}"
                for tid, cid, conf in zip(
                    detections.tracker_id,
                    detections.class_id,
                    detections.confidence,
                )
            ]
            out = self.label.annotate(scene=out, detections=detections, labels=labels)
        return out


def overlay_hud(frame: np.ndarray, snap: Snapshot) -> np.ndarray:
    h, w = frame.shape[:2]

    # top banner
    top = frame.copy()
    cv2.rectangle(top, (0, 0), (w, 56), (20, 20, 20), -1)
    frame = cv2.addWeighted(top, 0.55, frame, 0.45, 0)

    title = f"{snap.camera_id}  -  {snap.location[:28]}"
    cv2.putText(frame, title, (8, 22),
                cv2.FONT_HERSHEY_SIMPLEX, 0.55, (255, 255, 255), 1, cv2.LINE_AA)

    ts = datetime.fromtimestamp(snap.timestamp).strftime("%Y-%m-%d %H:%M:%S")
    cv2.putText(frame, ts, (8, 46),
                cv2.FONT_HERSHEY_SIMPLEX, 0.45, (210, 210, 210), 1, cv2.LINE_AA)

    fps_txt = f"cap {snap.fps_capture:4.1f} | proc {snap.fps_process:4.1f}"
    (tw, _), _ = cv2.getTextSize(fps_txt, cv2.FONT_HERSHEY_SIMPLEX, 0.45, 1)
    cv2.putText(frame, fps_txt, (w - tw - 18, 22),
                cv2.FONT_HERSHEY_SIMPLEX, 0.45, (180, 255, 180), 1, cv2.LINE_AA)

    conn = (0, 200, 0) if snap.connected else (0, 0, 220)
    cv2.circle(frame, (w - 12, 44), 5, conn, -1)

    # bottom strip with status chips
    _, t_color = traffic_status(snap.vehicle_count)
    _, c_color = crowd_status(snap.person_count)

    bottom = frame.copy()
    cv2.rectangle(bottom, (0, h - 38), (w, h), (20, 20, 20), -1)
    frame = cv2.addWeighted(bottom, 0.6, frame, 0.4, 0)

    info = f"Vehicles {snap.vehicle_count:3d}   People {snap.person_count:3d}"
    cv2.putText(frame, info, (8, h - 14),
                cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1, cv2.LINE_AA)

    chip_w = 96
    cv2.rectangle(frame, (w - 2*chip_w - 14, h - 30),
                  (w - chip_w - 16, h - 8), t_color, -1)
    cv2.putText(frame, snap.traffic_status, (w - 2*chip_w - 8, h - 14),
                cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 0), 1, cv2.LINE_AA)
    cv2.rectangle(frame, (w - chip_w - 10, h - 30), (w - 10, h - 8), c_color, -1)
    cv2.putText(frame, snap.crowd_status, (w - chip_w - 4, h - 14),
                cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 0), 1, cv2.LINE_AA)
    return frame


def placeholder(width: int, height: int, camera_id: str,
                location: str, message: str) -> np.ndarray:
    tile = np.full((height, width, 3), 30, dtype=np.uint8)
    cv2.putText(tile, camera_id, (12, 28),
                cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2, cv2.LINE_AA)
    cv2.putText(tile, location[:32], (12, 56),
                cv2.FONT_HERSHEY_SIMPLEX, 0.5, (180, 180, 180), 1, cv2.LINE_AA)
    cv2.putText(tile, message, (12, height // 2),
                cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 220), 2, cv2.LINE_AA)
    return tile