trackflow-python 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
trackflow/detector.py ADDED
@@ -0,0 +1,362 @@
1
+ """Apache-2.0 ONNX Runtime detector supporting D-FINE, RT-DETRv2, and RF-DETR."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from collections.abc import Sequence
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ import cv2
11
+ import numpy as np
12
+ import onnxruntime as ort
13
+
14
+ from trackflow.models import Precision, resolve_detector_artifacts
15
+ from trackflow.types import Detection
16
+
17
+ DEFAULT_COCO_LABELS: dict[int, str] = {
18
+ 0: "person",
19
+ 1: "bicycle",
20
+ 2: "car",
21
+ 3: "motorbike",
22
+ 4: "aeroplane",
23
+ 5: "bus",
24
+ 6: "train",
25
+ 7: "truck",
26
+ 8: "boat",
27
+ 9: "traffic light",
28
+ 10: "fire hydrant",
29
+ 11: "stop sign",
30
+ 12: "parking meter",
31
+ 13: "bench",
32
+ 14: "bird",
33
+ 15: "cat",
34
+ 16: "dog",
35
+ 17: "horse",
36
+ 18: "sheep",
37
+ 19: "cow",
38
+ 20: "elephant",
39
+ 21: "bear",
40
+ 22: "zebra",
41
+ 23: "giraffe",
42
+ 24: "backpack",
43
+ 25: "umbrella",
44
+ 26: "handbag",
45
+ 27: "tie",
46
+ 28: "suitcase",
47
+ 29: "frisbee",
48
+ 30: "skis",
49
+ 31: "snowboard",
50
+ 32: "sports ball",
51
+ 33: "kite",
52
+ 34: "baseball bat",
53
+ 35: "baseball glove",
54
+ 36: "skateboard",
55
+ 37: "surfboard",
56
+ 38: "tennis racket",
57
+ 39: "bottle",
58
+ 40: "wine glass",
59
+ 41: "cup",
60
+ 42: "fork",
61
+ 43: "knife",
62
+ 44: "spoon",
63
+ 45: "bowl",
64
+ 46: "banana",
65
+ 47: "apple",
66
+ 48: "sandwich",
67
+ 49: "orange",
68
+ 50: "broccoli",
69
+ 51: "carrot",
70
+ 52: "hot dog",
71
+ 53: "pizza",
72
+ 54: "donut",
73
+ 55: "cake",
74
+ 56: "chair",
75
+ 57: "sofa",
76
+ 58: "pottedplant",
77
+ 59: "bed",
78
+ 60: "diningtable",
79
+ 61: "toilet",
80
+ 62: "tvmonitor",
81
+ 63: "laptop",
82
+ 64: "mouse",
83
+ 65: "remote",
84
+ 66: "keyboard",
85
+ 67: "cell phone",
86
+ 68: "microwave",
87
+ 69: "oven",
88
+ 70: "toaster",
89
+ 71: "sink",
90
+ 72: "refrigerator",
91
+ 73: "book",
92
+ 74: "clock",
93
+ 75: "vase",
94
+ 76: "scissors",
95
+ 77: "teddy bear",
96
+ 78: "hair drier",
97
+ 79: "toothbrush",
98
+ }
99
+
100
+
101
+ def select_providers(device: str = "auto") -> list[str]:
102
+ """Choose ONNX Runtime execution providers based on requested device."""
103
+ available = ort.get_available_providers()
104
+ req = device.lower().strip()
105
+
106
+ if req == "cpu":
107
+ return ["CPUExecutionProvider"]
108
+ if req == "cuda":
109
+ return [p for p in ("CUDAExecutionProvider", "CPUExecutionProvider") if p in available]
110
+ if req == "coreml":
111
+ return [p for p in ("CoreMLExecutionProvider", "CPUExecutionProvider") if p in available]
112
+ if req == "tensorrt":
113
+ return [
114
+ p
115
+ for p in ("TensorrtExecutionProvider", "CUDAExecutionProvider", "CPUExecutionProvider")
116
+ if p in available
117
+ ]
118
+
119
+ # Auto-selection: prefer GPU / Apple Neural Engine / Metal via CoreML, then CPU.
120
+ preferred = [
121
+ "CUDAExecutionProvider",
122
+ "CoreMLExecutionProvider",
123
+ "CPUExecutionProvider",
124
+ ]
125
+ selected = [p for p in preferred if p in available]
126
+ return selected or ["CPUExecutionProvider"]
127
+
128
+
129
+ def create_onnx_session(
130
+ onnx_path: Path,
131
+ device: str = "auto",
132
+ ) -> tuple[ort.InferenceSession, str]:
133
+ """Create an ONNX Runtime session with safe fallback to CPU if an EP fails."""
134
+ providers = select_providers(device)
135
+ sess_opts = ort.SessionOptions()
136
+ sess_opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
137
+
138
+ try:
139
+ session = ort.InferenceSession(str(onnx_path), sess_options=sess_opts, providers=providers)
140
+ except Exception:
141
+ session = ort.InferenceSession(
142
+ str(onnx_path),
143
+ sess_options=sess_opts,
144
+ providers=["CPUExecutionProvider"],
145
+ )
146
+
147
+ active = session.get_providers()
148
+ active_name = active[0] if active else "CPUExecutionProvider"
149
+ return session, active_name
150
+
151
+
152
+ def sigmoid(x: np.ndarray) -> np.ndarray:
153
+ """Numerically stable sigmoid."""
154
+ x_clip = np.clip(x, -60.0, 60.0)
155
+ return 1.0 / (1.0 + np.exp(-x_clip))
156
+
157
+
158
+ def _nms_class_aware(detections: list[Detection], iou_threshold: float) -> list[Detection]:
159
+ """Deduplicate overlapping same-class DETR queries so duplicate boxes don't spawn ghost tracks."""
160
+ if len(detections) <= 1 or iou_threshold <= 0.0 or iou_threshold >= 1.0:
161
+ return detections
162
+
163
+ kept: list[Detection] = []
164
+ for det in detections:
165
+ x1, y1, x2, y2 = det.bbox
166
+ area_a = max(0.0, x2 - x1) * max(0.0, y2 - y1)
167
+ duplicate = False
168
+ for prev in kept:
169
+ if prev.class_id != det.class_id:
170
+ continue
171
+ px1, py1, px2, py2 = prev.bbox
172
+ iw = max(0.0, min(x2, px2) - max(x1, px1))
173
+ ih = max(0.0, min(y2, py2) - max(y1, py1))
174
+ inter = iw * ih
175
+ if inter <= 0.0:
176
+ continue
177
+ area_b = max(0.0, px2 - px1) * max(0.0, py2 - py1)
178
+ iou = inter / max(area_a + area_b - inter, 1e-6)
179
+ if iou >= iou_threshold:
180
+ duplicate = True
181
+ break
182
+ if not duplicate:
183
+ kept.append(det)
184
+ return kept
185
+
186
+
187
+ def postprocess_detr_outputs(
188
+ logits: np.ndarray,
189
+ pred_boxes: np.ndarray,
190
+ orig_hw: tuple[int, int],
191
+ id2label: dict[int, str],
192
+ threshold: float = 0.45,
193
+ allowed_classes: set[str] | None = None,
194
+ max_detections: int = 300,
195
+ nms_iou: float = 0.65,
196
+ ) -> list[Detection]:
197
+ """Convert DETR/RT-DETR/D-FINE/RF-DETR raw logits + normalized cxcywh boxes into Detections."""
198
+ # Squeeze batch dimension [1, N, C] -> [N, C]
199
+ if logits.ndim == 3:
200
+ logits = logits[0]
201
+ if pred_boxes.ndim == 3:
202
+ pred_boxes = pred_boxes[0]
203
+
204
+ probs = sigmoid(logits)
205
+ class_ids = np.argmax(probs, axis=-1)
206
+ scores = probs[np.arange(probs.shape[0]), class_ids]
207
+
208
+ keep = scores >= threshold
209
+ if not np.any(keep):
210
+ return []
211
+
212
+ kept_scores = scores[keep]
213
+ kept_classes = class_ids[keep]
214
+ kept_boxes = pred_boxes[keep]
215
+
216
+ order = np.argsort(-kept_scores)[:max_detections]
217
+ orig_h, orig_w = orig_hw
218
+
219
+ detections: list[Detection] = []
220
+ for idx in order:
221
+ cid = int(kept_classes[idx])
222
+ cname = id2label.get(cid, str(cid))
223
+ if allowed_classes is not None and cname.lower() not in allowed_classes:
224
+ continue
225
+
226
+ cx, cy, w, h = kept_boxes[idx].tolist()
227
+ # Handle both normalized [0, 1] and already-pixel coordinates safely.
228
+ if max(cx, cy, w, h) <= 2.0:
229
+ x1 = (cx - 0.5 * w) * orig_w
230
+ y1 = (cy - 0.5 * h) * orig_h
231
+ x2 = (cx + 0.5 * w) * orig_w
232
+ y2 = (cy + 0.5 * h) * orig_h
233
+ else:
234
+ x1, y1, x2, y2 = cx - 0.5 * w, cy - 0.5 * h, cx + 0.5 * w, cy + 0.5 * h
235
+
236
+ x1 = float(np.clip(x1, 0.0, orig_w))
237
+ y1 = float(np.clip(y1, 0.0, orig_h))
238
+ x2 = float(np.clip(x2, 0.0, orig_w))
239
+ y2 = float(np.clip(y2, 0.0, orig_h))
240
+
241
+ if x2 - x1 < 2.0 or y2 - y1 < 2.0:
242
+ continue
243
+
244
+ detections.append(
245
+ Detection(
246
+ bbox=(x1, y1, x2, y2),
247
+ confidence=float(kept_scores[idx]),
248
+ class_id=cid,
249
+ class_name=cname,
250
+ )
251
+ )
252
+
253
+ return _nms_class_aware(detections, iou_threshold=nms_iou)
254
+
255
+
256
+ class OnnxDetrDetector:
257
+ """End-to-end transformer object detector powered by ONNX Runtime."""
258
+
259
+ def __init__(
260
+ self,
261
+ model: str = "rtdetr-v2-r18",
262
+ *,
263
+ precision: Precision = "fp32",
264
+ device: str = "auto",
265
+ threshold: float = 0.45,
266
+ classes: Sequence[str] | None = ("person",),
267
+ cache_dir: str | Path | None = None,
268
+ ) -> None:
269
+ self.model_name = model
270
+ self.precision = precision
271
+ self.threshold = float(threshold)
272
+ self.allowed_classes = (
273
+ None
274
+ if not classes or any(c.lower() in ("*", "all") for c in classes)
275
+ else {c.lower().strip() for c in classes}
276
+ )
277
+
278
+ onnx_path, config_path, prep_path = resolve_detector_artifacts(
279
+ model=model,
280
+ precision=precision,
281
+ cache_dir=cache_dir,
282
+ )
283
+ self.onnx_path = onnx_path
284
+ self.id2label = self._load_labels(config_path)
285
+ self.input_hw, self.do_rescale, self.do_normalize, self.mean, self.std = (
286
+ self._load_preprocess_config(prep_path)
287
+ )
288
+
289
+ # CoreML EP on int8 quantized DETR graphs can occasionally fail or degrade; prefer CPU for int8.
290
+ effective_device = "cpu" if (device == "auto" and precision == "int8") else device
291
+ self.session, self.active_provider = create_onnx_session(onnx_path, device=effective_device)
292
+
293
+ self.input_name = self.session.get_inputs()[0].name
294
+ self.input_dtype = (
295
+ np.float16 if "float16" in self.session.get_inputs()[0].type else np.float32
296
+ )
297
+ self.output_names = [o.name for o in self.session.get_outputs()]
298
+
299
+ @staticmethod
300
+ def _load_labels(config_path: Path | None) -> dict[int, str]:
301
+ if config_path is None or not config_path.is_file():
302
+ return dict(DEFAULT_COCO_LABELS)
303
+ raw: dict[str, Any] = json.loads(config_path.read_text(encoding="utf-8"))
304
+ id2label_raw = raw.get("id2label")
305
+ if not isinstance(id2label_raw, dict):
306
+ return dict(DEFAULT_COCO_LABELS)
307
+ return {int(k): str(v) for k, v in id2label_raw.items()}
308
+
309
+ @staticmethod
310
+ def _load_preprocess_config(
311
+ prep_path: Path | None,
312
+ ) -> tuple[tuple[int, int], bool, bool, np.ndarray, np.ndarray]:
313
+ default_mean = np.array([0.485, 0.456, 0.406], dtype=np.float32).reshape(3, 1, 1)
314
+ default_std = np.array([0.229, 0.224, 0.225], dtype=np.float32).reshape(3, 1, 1)
315
+ if prep_path is None or not prep_path.is_file():
316
+ return (640, 640), True, False, default_mean, default_std
317
+
318
+ cfg: dict[str, Any] = json.loads(prep_path.read_text(encoding="utf-8"))
319
+ size = cfg.get("size", {})
320
+ h = int(size.get("height", 640))
321
+ w = int(size.get("width", 640))
322
+ do_rescale = bool(cfg.get("do_rescale", True))
323
+ do_normalize = bool(cfg.get("do_normalize", False))
324
+ mean = np.array(cfg.get("image_mean", [0.485, 0.456, 0.406]), dtype=np.float32).reshape(
325
+ 3, 1, 1
326
+ )
327
+ std = np.array(cfg.get("image_std", [0.229, 0.224, 0.225]), dtype=np.float32).reshape(
328
+ 3, 1, 1
329
+ )
330
+ return (h, w), do_rescale, do_normalize, mean, std
331
+
332
+ def preprocess(self, frame_bgr: np.ndarray) -> np.ndarray:
333
+ """Convert OpenCV BGR uint8 frame to NCHW float tensor."""
334
+ target_h, target_w = self.input_hw
335
+ rgb = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2RGB)
336
+ resized = cv2.resize(rgb, (target_w, target_h), interpolation=cv2.INTER_LINEAR)
337
+ arr = resized.astype(np.float32)
338
+ if self.do_rescale:
339
+ arr *= 1.0 / 255.0
340
+ chw = np.transpose(arr, (2, 0, 1))
341
+ if self.do_normalize:
342
+ chw = (chw - self.mean) / self.std
343
+ return np.expand_dims(chw, axis=0).astype(self.input_dtype, copy=False)
344
+
345
+ def detect(self, frame_bgr: np.ndarray, threshold: float | None = None) -> list[Detection]:
346
+ """Run object detection on a single BGR frame."""
347
+ orig_h, orig_w = frame_bgr.shape[:2]
348
+ tensor = self.preprocess(frame_bgr)
349
+ outputs = self.session.run(None, {self.input_name: tensor})
350
+
351
+ by_name = dict(zip(self.output_names, outputs, strict=False))
352
+ logits = by_name.get("logits", outputs[0])
353
+ pred_boxes = by_name.get("pred_boxes", outputs[1])
354
+
355
+ return postprocess_detr_outputs(
356
+ logits=np.asarray(logits, dtype=np.float32),
357
+ pred_boxes=np.asarray(pred_boxes, dtype=np.float32),
358
+ orig_hw=(orig_h, orig_w),
359
+ id2label=self.id2label,
360
+ threshold=self.threshold if threshold is None else threshold,
361
+ allowed_classes=self.allowed_classes,
362
+ )
@@ -0,0 +1,222 @@
1
+ """4-point floorplan homography calibration, bird's-eye projection, heatmaps, and dwell zones."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from dataclasses import dataclass, field
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ import cv2
11
+ import numpy as np
12
+
13
+
14
+ @dataclass(slots=True)
15
+ class DwellZone:
16
+ """Named polygon in top-down floorplan coordinates."""
17
+
18
+ name: str
19
+ polygon: list[tuple[float, float]]
20
+ color: str = "#38bdf8"
21
+
22
+ def contains(self, x: float, y: float) -> bool:
23
+ pts = np.array(self.polygon, dtype=np.float32).reshape(-1, 1, 2)
24
+ return cv2.pointPolygonTest(pts, (float(x), float(y)), False) >= 0
25
+
26
+ def to_dict(self) -> dict[str, Any]:
27
+ return {
28
+ "name": self.name,
29
+ "polygon": [[round(float(x), 3), round(float(y), 3)] for x, y in self.polygon],
30
+ "color": self.color,
31
+ }
32
+
33
+
34
+ @dataclass
35
+ class FloorplanHomography:
36
+ """Maps 2D camera ground points onto a top-down bird's-eye floorplan via 4-point homography."""
37
+
38
+ image_points: list[tuple[float, float]]
39
+ world_points: list[tuple[float, float]]
40
+ width_m: float = 10.0
41
+ height_m: float = 10.0
42
+ zones: list[DwellZone] = field(default_factory=list)
43
+ _matrix: np.ndarray = field(init=False, repr=False)
44
+ _heatmap: np.ndarray = field(init=False, repr=False)
45
+ _trajectories: dict[int, list[tuple[float, float]]] = field(default_factory=dict, repr=False)
46
+ zone_dwell_totals_s: dict[str, float] = field(default_factory=dict)
47
+
48
+ def __post_init__(self) -> None:
49
+ if len(self.image_points) != 4 or len(self.world_points) != 4:
50
+ raise ValueError(
51
+ "FloorplanHomography requires exactly 4 image_points and 4 world_points."
52
+ )
53
+ src = np.array(self.image_points, dtype=np.float32)
54
+ dst = np.array(self.world_points, dtype=np.float32)
55
+ self._matrix = cv2.getPerspectiveTransform(src, dst)
56
+ self._heatmap = np.zeros((100, 100), dtype=np.float32)
57
+ for z in self.zones:
58
+ self.zone_dwell_totals_s.setdefault(z.name, 0.0)
59
+
60
+ @classmethod
61
+ def from_json(cls, path: str | Path) -> FloorplanHomography:
62
+ data = json.loads(Path(path).read_text(encoding="utf-8"))
63
+ img_pts = [(float(p[0]), float(p[1])) for p in data["image_points"]]
64
+ wld_pts = [(float(p[0]), float(p[1])) for p in data["world_points"]]
65
+ zones = [
66
+ DwellZone(
67
+ name=str(z["name"]),
68
+ polygon=[(float(p[0]), float(p[1])) for p in z["polygon"]],
69
+ color=str(z.get("color", "#38bdf8")),
70
+ )
71
+ for z in data.get("zones", [])
72
+ ]
73
+ width_m = float(data.get("width_m", max(p[0] for p in wld_pts) or 10.0))
74
+ height_m = float(data.get("height_m", max(p[1] for p in wld_pts) or 10.0))
75
+ return cls(
76
+ image_points=img_pts,
77
+ world_points=wld_pts,
78
+ width_m=width_m,
79
+ height_m=height_m,
80
+ zones=zones,
81
+ )
82
+
83
+ def to_dict(self) -> dict[str, Any]:
84
+ return {
85
+ "image_points": [
86
+ [round(float(x), 2), round(float(y), 2)] for x, y in self.image_points
87
+ ],
88
+ "world_points": [
89
+ [round(float(x), 3), round(float(y), 3)] for x, y in self.world_points
90
+ ],
91
+ "width_m": round(float(self.width_m), 3),
92
+ "height_m": round(float(self.height_m), 3),
93
+ "zones": [z.to_dict() for z in self.zones],
94
+ }
95
+
96
+ def save_json(self, path: str | Path) -> None:
97
+ Path(path).write_text(json.dumps(self.to_dict(), indent=2), encoding="utf-8")
98
+
99
+ def project(self, image_xy: tuple[float, float]) -> tuple[float, float]:
100
+ """Project a single 2D image pixel point (e.g. foot point) into floorplan (x, y)."""
101
+ pt = np.array([[[float(image_xy[0]), float(image_xy[1])]]], dtype=np.float32)
102
+ out = cv2.perspectiveTransform(pt, self._matrix)[0, 0]
103
+ return (float(out[0]), float(out[1]))
104
+
105
+ def locate_zone(self, world_xy: tuple[float, float]) -> str | None:
106
+ for zone in self.zones:
107
+ if zone.contains(world_xy[0], world_xy[1]):
108
+ return zone.name
109
+ return None
110
+
111
+ def observe(
112
+ self,
113
+ track_id: int,
114
+ foot_xy: tuple[float, float],
115
+ dt_s: float = 0.0,
116
+ ) -> tuple[tuple[float, float], str | None]:
117
+ """Project a track observation, accumulate heatmap & dwell metrics, and return (world_xy, zone)."""
118
+ wx, wy = self.project(foot_xy)
119
+ self._trajectories.setdefault(track_id, []).append((wx, wy))
120
+
121
+ gx = int(
122
+ np.clip(
123
+ (wx / max(self.width_m, 1e-3)) * (self._heatmap.shape[1] - 1),
124
+ 0,
125
+ self._heatmap.shape[1] - 1,
126
+ )
127
+ )
128
+ gy = int(
129
+ np.clip(
130
+ (wy / max(self.height_m, 1e-3)) * (self._heatmap.shape[0] - 1),
131
+ 0,
132
+ self._heatmap.shape[0] - 1,
133
+ )
134
+ )
135
+ self._heatmap[gy, gx] += 1.0
136
+
137
+ zone = self.locate_zone((wx, wy))
138
+ if zone is not None:
139
+ self.zone_dwell_totals_s[zone] = self.zone_dwell_totals_s.get(zone, 0.0) + max(
140
+ 0.0, dt_s
141
+ )
142
+ return (wx, wy), zone
143
+
144
+ def render_floorplan(
145
+ self, out_path: str | Path, canvas_size: tuple[int, int] = (800, 600)
146
+ ) -> Path:
147
+ """Render a high-contrast bird's-eye floorplan PNG with heatmap, dwell zones, and trajectories."""
148
+ cw, ch = canvas_size
149
+ canvas = np.full((ch, cw, 3), (15, 20, 30), dtype=np.uint8)
150
+
151
+ # Draw grid lines (1-meter spacing)
152
+ for mx in range(int(self.width_m) + 1):
153
+ px = int((mx / max(self.width_m, 1e-3)) * (cw - 1))
154
+ cv2.line(canvas, (px, 0), (px, ch), (30, 38, 54), 1)
155
+ for my in range(int(self.height_m) + 1):
156
+ py = int((my / max(self.height_m, 1e-3)) * (ch - 1))
157
+ cv2.line(canvas, (0, py), (cw, py), (30, 38, 54), 1)
158
+
159
+ # Overlay smoothed density heatmap
160
+ if float(self._heatmap.max()) > 0:
161
+ heat = cv2.GaussianBlur(self._heatmap, (11, 11), 0)
162
+ norm = np.clip((heat / max(float(heat.max()), 1e-6)) * 255.0, 0, 255).astype(np.uint8)
163
+ resized = cv2.resize(norm, (cw, ch), interpolation=cv2.INTER_CUBIC)
164
+ colored = cv2.applyColorMap(resized, cv2.COLORMAP_INFERNO)
165
+ mask = (resized > 15).astype(np.float32)[:, :, None] * 0.55
166
+ canvas = np.clip(canvas * (1.0 - mask) + colored * mask, 0, 255).astype(np.uint8)
167
+
168
+ def to_px(wx: float, wy: float) -> tuple[int, int]:
169
+ x = int(np.clip((wx / max(self.width_m, 1e-3)) * (cw - 1), 0, cw - 1))
170
+ y = int(np.clip((wy / max(self.height_m, 1e-3)) * (ch - 1), 0, ch - 1))
171
+ return (x, y)
172
+
173
+ # Draw dwell zones
174
+ for zone in self.zones:
175
+ pts = np.array([to_px(x, y) for x, y in zone.polygon], dtype=np.int32)
176
+ if len(pts) >= 3:
177
+ overlay = canvas.copy()
178
+ cv2.fillPoly(overlay, [pts], (60, 120, 180))
179
+ canvas = cv2.addWeighted(overlay, 0.22, canvas, 0.78, 0)
180
+ cv2.polylines(canvas, [pts], True, (110, 210, 255), 2, cv2.LINE_AA)
181
+ cx, cy = int(pts[:, 0].mean()), int(pts[:, 1].mean())
182
+ dwell = self.zone_dwell_totals_s.get(zone.name, 0.0)
183
+ cv2.putText(
184
+ canvas,
185
+ f"{zone.name} ({dwell:.1f}s)",
186
+ (max(6, cx - 40), max(20, cy)),
187
+ cv2.FONT_HERSHEY_SIMPLEX,
188
+ 0.5,
189
+ (230, 245, 255),
190
+ 1,
191
+ cv2.LINE_AA,
192
+ )
193
+
194
+ # Draw trajectories
195
+ palette = [
196
+ (92, 214, 148),
197
+ (250, 173, 72),
198
+ (140, 130, 255),
199
+ (110, 235, 255),
200
+ (255, 130, 210),
201
+ ]
202
+ for tid, pts in self._trajectories.items():
203
+ if len(pts) < 2:
204
+ continue
205
+ color = palette[tid % len(palette)]
206
+ px_pts = np.array([to_px(x, y) for x, y in pts], dtype=np.int32)
207
+ cv2.polylines(canvas, [px_pts], False, color, 2, cv2.LINE_AA)
208
+ cv2.circle(canvas, tuple(px_pts[-1]), 4, (255, 255, 255), -1, cv2.LINE_AA)
209
+
210
+ cv2.putText(
211
+ canvas,
212
+ f"Trackflow Bird's-Eye Floorplan ({self.width_m:.1f}m x {self.height_m:.1f}m)",
213
+ (14, 26),
214
+ cv2.FONT_HERSHEY_SIMPLEX,
215
+ 0.55,
216
+ (225, 235, 245),
217
+ 1,
218
+ cv2.LINE_AA,
219
+ )
220
+ out = Path(out_path)
221
+ cv2.imwrite(str(out), canvas)
222
+ return out