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/__init__.py +44 -0
- trackflow/benchmark.py +253 -0
- trackflow/cli.py +395 -0
- trackflow/detector.py +362 -0
- trackflow/homography.py +222 -0
- trackflow/inspector.py +282 -0
- trackflow/inspector_ui.html +451 -0
- trackflow/models.py +184 -0
- trackflow/pipeline.py +406 -0
- trackflow/privacy.py +143 -0
- trackflow/reid.py +417 -0
- trackflow/sinks.py +308 -0
- trackflow/tracker.py +558 -0
- trackflow/types.py +224 -0
- trackflow_python-0.1.0.dist-info/METADATA +178 -0
- trackflow_python-0.1.0.dist-info/RECORD +19 -0
- trackflow_python-0.1.0.dist-info/WHEEL +4 -0
- trackflow_python-0.1.0.dist-info/entry_points.txt +3 -0
- trackflow_python-0.1.0.dist-info/licenses/LICENSE +199 -0
trackflow/pipeline.py
ADDED
|
@@ -0,0 +1,406 @@
|
|
|
1
|
+
"""End-to-end Trackflow video/webcam/directory tracking pipeline."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import contextlib
|
|
6
|
+
import json
|
|
7
|
+
import time
|
|
8
|
+
from collections import defaultdict
|
|
9
|
+
from collections.abc import Callable, Iterator, Sequence
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
import cv2
|
|
14
|
+
import numpy as np
|
|
15
|
+
|
|
16
|
+
from trackflow.detector import OnnxDetrDetector
|
|
17
|
+
from trackflow.homography import FloorplanHomography
|
|
18
|
+
from trackflow.models import Precision
|
|
19
|
+
from trackflow.privacy import AnonymizeMode, PrivacyAnonymizer
|
|
20
|
+
from trackflow.reid import AppearanceEmbedder, ReidBackend, TrackCardIndex
|
|
21
|
+
from trackflow.sinks import draw_tracks, write_csv, write_html_report, write_jsonl, write_parquet
|
|
22
|
+
from trackflow.tracker import create_tracker
|
|
23
|
+
from trackflow.types import Detection, FrameResult, RunSummary
|
|
24
|
+
|
|
25
|
+
IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".bmp", ".webp"}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _iter_frames(
|
|
29
|
+
source: str | int,
|
|
30
|
+
*,
|
|
31
|
+
max_frames: int | None = None,
|
|
32
|
+
) -> tuple[Iterator[tuple[int, float, np.ndarray]], float, int, int, int]:
|
|
33
|
+
"""Open a video file, webcam index, or directory of images."""
|
|
34
|
+
if isinstance(source, int) or str(source).isdigit() or str(source).lower() == "camera":
|
|
35
|
+
cam_idx = 0 if str(source).lower() == "camera" else int(source)
|
|
36
|
+
cap = cv2.VideoCapture(cam_idx)
|
|
37
|
+
if not cap.isOpened():
|
|
38
|
+
raise RuntimeError(f"Could not open webcam index {cam_idx}")
|
|
39
|
+
fps = cap.get(cv2.CAP_PROP_FPS) or 30.0
|
|
40
|
+
w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH) or 640)
|
|
41
|
+
h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT) or 480)
|
|
42
|
+
|
|
43
|
+
def _gen_cam() -> Iterator[tuple[int, float, np.ndarray]]:
|
|
44
|
+
idx = 0
|
|
45
|
+
try:
|
|
46
|
+
while True:
|
|
47
|
+
ok, frame = cap.read()
|
|
48
|
+
if not ok:
|
|
49
|
+
break
|
|
50
|
+
yield idx, idx / fps, frame
|
|
51
|
+
idx += 1
|
|
52
|
+
if max_frames is not None and idx >= max_frames:
|
|
53
|
+
break
|
|
54
|
+
finally:
|
|
55
|
+
cap.release()
|
|
56
|
+
|
|
57
|
+
return _gen_cam(), float(fps), w, h, max_frames or 0
|
|
58
|
+
|
|
59
|
+
src_path = Path(str(source))
|
|
60
|
+
if src_path.is_dir():
|
|
61
|
+
imgs = sorted(p for p in src_path.iterdir() if p.suffix.lower() in IMAGE_EXTS)
|
|
62
|
+
if not imgs:
|
|
63
|
+
raise FileNotFoundError(f"No images found in directory: {src_path}")
|
|
64
|
+
first = cv2.imread(str(imgs[0]))
|
|
65
|
+
if first is None:
|
|
66
|
+
raise RuntimeError(f"Failed to read image: {imgs[0]}")
|
|
67
|
+
h, w = first.shape[:2]
|
|
68
|
+
fps = 25.0
|
|
69
|
+
total = min(len(imgs), max_frames) if max_frames is not None else len(imgs)
|
|
70
|
+
|
|
71
|
+
def _gen_dir() -> Iterator[tuple[int, float, np.ndarray]]:
|
|
72
|
+
for idx, p in enumerate(imgs[:total]):
|
|
73
|
+
frame = cv2.imread(str(p))
|
|
74
|
+
if frame is not None:
|
|
75
|
+
yield idx, idx / fps, frame
|
|
76
|
+
|
|
77
|
+
return _gen_dir(), fps, w, h, total
|
|
78
|
+
|
|
79
|
+
if not src_path.is_file():
|
|
80
|
+
raise FileNotFoundError(f"Video source not found: {src_path}")
|
|
81
|
+
|
|
82
|
+
cap = cv2.VideoCapture(str(src_path))
|
|
83
|
+
if not cap.isOpened():
|
|
84
|
+
raise RuntimeError(f"Failed to open video file: {src_path}")
|
|
85
|
+
|
|
86
|
+
fps = cap.get(cv2.CAP_PROP_FPS)
|
|
87
|
+
if not fps or fps <= 0 or np.isnan(fps):
|
|
88
|
+
fps = 30.0
|
|
89
|
+
w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
|
90
|
+
h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
|
91
|
+
total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0)
|
|
92
|
+
if max_frames is not None and (total == 0 or max_frames < total):
|
|
93
|
+
total = max_frames
|
|
94
|
+
|
|
95
|
+
def _gen_vid() -> Iterator[tuple[int, float, np.ndarray]]:
|
|
96
|
+
idx = 0
|
|
97
|
+
try:
|
|
98
|
+
while True:
|
|
99
|
+
ok, frame = cap.read()
|
|
100
|
+
if not ok:
|
|
101
|
+
break
|
|
102
|
+
yield idx, idx / fps, frame
|
|
103
|
+
idx += 1
|
|
104
|
+
if max_frames is not None and idx >= max_frames:
|
|
105
|
+
break
|
|
106
|
+
finally:
|
|
107
|
+
cap.release()
|
|
108
|
+
|
|
109
|
+
return _gen_vid(), float(fps), w, h, total
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class TrackflowPipeline:
|
|
113
|
+
"""Unified real-time tracking pipeline combining detection, MOT, Re-ID/NL query, privacy & floorplan."""
|
|
114
|
+
|
|
115
|
+
def __init__(
|
|
116
|
+
self,
|
|
117
|
+
*,
|
|
118
|
+
model: str = "rtdetr-v2-r18",
|
|
119
|
+
precision: Precision = "fp32",
|
|
120
|
+
tracker: str = "bytetrack",
|
|
121
|
+
device: str = "auto",
|
|
122
|
+
threshold: float = 0.45,
|
|
123
|
+
classes: Sequence[str] | None = ("person",),
|
|
124
|
+
reid: ReidBackend = "none",
|
|
125
|
+
query: str | None = None,
|
|
126
|
+
query_threshold: float = 0.22,
|
|
127
|
+
anonymize: AnonymizeMode = "none",
|
|
128
|
+
homography: FloorplanHomography | str | Path | None = None,
|
|
129
|
+
detector: Any | None = None,
|
|
130
|
+
embedder: AppearanceEmbedder | None = None,
|
|
131
|
+
) -> None:
|
|
132
|
+
self.model_name = model
|
|
133
|
+
self.tracker_name = tracker
|
|
134
|
+
self.threshold = float(threshold)
|
|
135
|
+
self.classes = list(classes) if classes else ["all"]
|
|
136
|
+
self.query = query.strip() if query else None
|
|
137
|
+
self.query_threshold = float(query_threshold)
|
|
138
|
+
self.anonymize_mode: AnonymizeMode = anonymize
|
|
139
|
+
|
|
140
|
+
# Automatically enable CLIP when a natural-language --query is passed without --reid
|
|
141
|
+
effective_reid: ReidBackend = reid
|
|
142
|
+
if self.query and effective_reid in ("none", "color") and embedder is None:
|
|
143
|
+
effective_reid = "clip"
|
|
144
|
+
self.reid_backend: ReidBackend = effective_reid
|
|
145
|
+
|
|
146
|
+
self.detector = (
|
|
147
|
+
detector
|
|
148
|
+
if detector is not None
|
|
149
|
+
else OnnxDetrDetector(
|
|
150
|
+
model=model,
|
|
151
|
+
precision=precision,
|
|
152
|
+
device=device,
|
|
153
|
+
threshold=min(0.15, threshold), # keep low-conf tier for ByteTrack 2nd stage!
|
|
154
|
+
classes=classes,
|
|
155
|
+
)
|
|
156
|
+
)
|
|
157
|
+
self.embedder = (
|
|
158
|
+
embedder
|
|
159
|
+
if embedder is not None
|
|
160
|
+
else (
|
|
161
|
+
AppearanceEmbedder(backend=self.reid_backend, device=device)
|
|
162
|
+
if self.reid_backend != "none"
|
|
163
|
+
else None
|
|
164
|
+
)
|
|
165
|
+
)
|
|
166
|
+
self.anonymizer = PrivacyAnonymizer(mode=anonymize)
|
|
167
|
+
if isinstance(homography, (str, Path)):
|
|
168
|
+
self.homography: FloorplanHomography | None = FloorplanHomography.from_json(homography)
|
|
169
|
+
else:
|
|
170
|
+
self.homography = homography
|
|
171
|
+
|
|
172
|
+
def run(
|
|
173
|
+
self,
|
|
174
|
+
source: str | int,
|
|
175
|
+
*,
|
|
176
|
+
output_dir: str | Path = "runs/latest",
|
|
177
|
+
skip: int = 0,
|
|
178
|
+
max_frames: int | None = None,
|
|
179
|
+
save_video: bool = True,
|
|
180
|
+
exports: Sequence[str] = ("parquet", "jsonl", "html"),
|
|
181
|
+
display: bool = False,
|
|
182
|
+
progress_callback: Callable[[int, int, float], None] | None = None,
|
|
183
|
+
) -> RunSummary:
|
|
184
|
+
"""Execute tracking on ``source`` and write requested artifacts into ``output_dir``."""
|
|
185
|
+
out_dir = Path(output_dir)
|
|
186
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
187
|
+
export_set = {e.lower().strip() for e in exports}
|
|
188
|
+
|
|
189
|
+
frame_iter, src_fps, width, height, total_frames = _iter_frames(
|
|
190
|
+
source, max_frames=max_frames
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
tracker = create_tracker(
|
|
194
|
+
self.tracker_name,
|
|
195
|
+
track_high_thresh=self.threshold,
|
|
196
|
+
track_low_thresh=max(0.10, self.threshold * 0.35),
|
|
197
|
+
new_track_thresh=min(0.95, self.threshold + 0.05),
|
|
198
|
+
)
|
|
199
|
+
card_index = TrackCardIndex(
|
|
200
|
+
embedder=self.embedder,
|
|
201
|
+
query=self.query,
|
|
202
|
+
query_threshold=self.query_threshold,
|
|
203
|
+
crops_dir=out_dir / "crops",
|
|
204
|
+
)
|
|
205
|
+
|
|
206
|
+
video_writer: cv2.VideoWriter | None = None
|
|
207
|
+
video_path = out_dir / "annotated.mp4"
|
|
208
|
+
if save_video:
|
|
209
|
+
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
|
|
210
|
+
out_fps = src_fps / max(1, skip + 1)
|
|
211
|
+
video_writer = cv2.VideoWriter(str(video_path), fourcc, out_fps, (width, height))
|
|
212
|
+
|
|
213
|
+
frame_results: list[FrameResult] = []
|
|
214
|
+
records: list[dict[str, Any]] = []
|
|
215
|
+
trails: dict[int, list[tuple[int, int]]] = defaultdict(list)
|
|
216
|
+
all_events: list[dict[str, Any]] = []
|
|
217
|
+
|
|
218
|
+
total_dets = 0
|
|
219
|
+
recovered_count = 0
|
|
220
|
+
inf_ms_list: list[float] = []
|
|
221
|
+
trk_ms_list: list[float] = []
|
|
222
|
+
frame_dt_s = (skip + 1) / max(src_fps, 1e-3)
|
|
223
|
+
|
|
224
|
+
t_start = time.perf_counter()
|
|
225
|
+
processed = 0
|
|
226
|
+
seen_frames = 0
|
|
227
|
+
|
|
228
|
+
try:
|
|
229
|
+
for frame_idx, timestamp_s, frame_bgr in frame_iter:
|
|
230
|
+
seen_frames += 1
|
|
231
|
+
if skip > 0 and (frame_idx % (skip + 1) != 0):
|
|
232
|
+
continue
|
|
233
|
+
|
|
234
|
+
t0 = time.perf_counter()
|
|
235
|
+
dets: list[Detection] = self.detector.detect(frame_bgr)
|
|
236
|
+
inf_ms = (time.perf_counter() - t0) * 1000.0
|
|
237
|
+
inf_ms_list.append(inf_ms)
|
|
238
|
+
total_dets += len(dets)
|
|
239
|
+
|
|
240
|
+
# Attach per-detection embeddings when BoT-SORT uses Re-ID
|
|
241
|
+
if (
|
|
242
|
+
self.tracker_name.lower().replace("-", "_") == "botsort"
|
|
243
|
+
and self.embedder is not None
|
|
244
|
+
and self.embedder.backend != "none"
|
|
245
|
+
):
|
|
246
|
+
for d in dets:
|
|
247
|
+
if d.confidence >= self.threshold:
|
|
248
|
+
x1, y1, x2, y2 = [int(round(v)) for v in d.bbox]
|
|
249
|
+
x1, y1 = max(0, x1), max(0, y1)
|
|
250
|
+
x2, y2 = min(width, x2), min(height, y2)
|
|
251
|
+
if x2 - x1 >= 4 and y2 - y1 >= 4:
|
|
252
|
+
d.embedding = self.embedder.encode_image(frame_bgr[y1:y2, x1:x2])
|
|
253
|
+
|
|
254
|
+
t1 = time.perf_counter()
|
|
255
|
+
tracks = tracker.update(dets, frame_bgr=frame_bgr)
|
|
256
|
+
trk_ms = (time.perf_counter() - t1) * 1000.0
|
|
257
|
+
trk_ms_list.append(trk_ms)
|
|
258
|
+
|
|
259
|
+
# Spatial homography projection & dwell zones
|
|
260
|
+
if self.homography is not None:
|
|
261
|
+
for tr in tracks:
|
|
262
|
+
wxy, zone = self.homography.observe(
|
|
263
|
+
tr.track_id, tr.foot_point, dt_s=frame_dt_s
|
|
264
|
+
)
|
|
265
|
+
tr.world_xy = wxy
|
|
266
|
+
tr.zone = zone
|
|
267
|
+
|
|
268
|
+
# Persistent Track Cards, cross-exit Re-ID merges, and NL query scoring
|
|
269
|
+
reid_events = card_index.update(
|
|
270
|
+
frame_idx=frame_idx,
|
|
271
|
+
timestamp_s=timestamp_s,
|
|
272
|
+
frame_bgr=frame_bgr,
|
|
273
|
+
tracks=tracks,
|
|
274
|
+
frame_dt_s=frame_dt_s,
|
|
275
|
+
)
|
|
276
|
+
|
|
277
|
+
frame_events = list(tracker.last_events) + reid_events
|
|
278
|
+
for ev in frame_events:
|
|
279
|
+
all_events.append(
|
|
280
|
+
{"frame_idx": frame_idx, "timestamp_s": round(timestamp_s, 3), **ev}
|
|
281
|
+
)
|
|
282
|
+
|
|
283
|
+
for tr in tracks:
|
|
284
|
+
if tr.recovered:
|
|
285
|
+
recovered_count += 1
|
|
286
|
+
fx, fy = tr.foot_point
|
|
287
|
+
trails[tr.track_id].append((int(round(fx)), int(round(fy))))
|
|
288
|
+
if len(trails[tr.track_id]) > 48:
|
|
289
|
+
trails[tr.track_id] = trails[tr.track_id][-48:]
|
|
290
|
+
records.append(tr.to_record(frame_idx, timestamp_s))
|
|
291
|
+
|
|
292
|
+
fr = FrameResult(
|
|
293
|
+
frame_idx=frame_idx,
|
|
294
|
+
timestamp_s=timestamp_s,
|
|
295
|
+
tracks=tracks,
|
|
296
|
+
num_detections=len(dets),
|
|
297
|
+
inference_ms=inf_ms,
|
|
298
|
+
tracking_ms=trk_ms,
|
|
299
|
+
events=frame_events,
|
|
300
|
+
)
|
|
301
|
+
frame_results.append(fr)
|
|
302
|
+
processed += 1
|
|
303
|
+
|
|
304
|
+
elapsed_now = max(time.perf_counter() - t_start, 1e-6)
|
|
305
|
+
live_fps = processed / elapsed_now
|
|
306
|
+
|
|
307
|
+
if save_video or display:
|
|
308
|
+
anon_frame = self.anonymizer.apply(frame_bgr, tracks)
|
|
309
|
+
rendered = draw_tracks(
|
|
310
|
+
anon_frame,
|
|
311
|
+
tracks,
|
|
312
|
+
trails=trails,
|
|
313
|
+
fps=live_fps,
|
|
314
|
+
query=self.query,
|
|
315
|
+
anonymize_mode=self.anonymize_mode,
|
|
316
|
+
)
|
|
317
|
+
if video_writer is not None:
|
|
318
|
+
video_writer.write(rendered)
|
|
319
|
+
if display:
|
|
320
|
+
try:
|
|
321
|
+
cv2.imshow("Trackflow", rendered)
|
|
322
|
+
if cv2.waitKey(1) & 0xFF == ord("q"):
|
|
323
|
+
break
|
|
324
|
+
except cv2.error:
|
|
325
|
+
display = False
|
|
326
|
+
|
|
327
|
+
if progress_callback is not None:
|
|
328
|
+
progress_callback(processed, total_frames, live_fps)
|
|
329
|
+
finally:
|
|
330
|
+
if video_writer is not None:
|
|
331
|
+
video_writer.release()
|
|
332
|
+
if display:
|
|
333
|
+
with contextlib.suppress(cv2.error):
|
|
334
|
+
cv2.destroyAllWindows()
|
|
335
|
+
|
|
336
|
+
elapsed_s = max(time.perf_counter() - t_start, 1e-6)
|
|
337
|
+
avg_fps = processed / elapsed_s
|
|
338
|
+
avg_inf = float(np.mean(inf_ms_list)) if inf_ms_list else 0.0
|
|
339
|
+
avg_trk = float(np.mean(trk_ms_list)) if trk_ms_list else 0.0
|
|
340
|
+
|
|
341
|
+
device_label = getattr(self.detector, "active_provider", "custom")
|
|
342
|
+
output_files: dict[str, str] = {}
|
|
343
|
+
if save_video and video_path.is_file():
|
|
344
|
+
output_files["video"] = str(video_path)
|
|
345
|
+
|
|
346
|
+
# Persist Track Cards & diagnostic events (always written for `trackflow inspect` / `search`)
|
|
347
|
+
cards_path = out_dir / "track_cards.json"
|
|
348
|
+
card_index.save_json(cards_path, reid_backend=self.reid_backend)
|
|
349
|
+
output_files["track_cards"] = str(cards_path)
|
|
350
|
+
|
|
351
|
+
events_path = out_dir / "events.json"
|
|
352
|
+
events_path.write_text(json.dumps(all_events, indent=2), encoding="utf-8")
|
|
353
|
+
output_files["events"] = str(events_path)
|
|
354
|
+
|
|
355
|
+
if "parquet" in export_set:
|
|
356
|
+
output_files["parquet"] = str(write_parquet(records, out_dir / "tracks.parquet"))
|
|
357
|
+
if "jsonl" in export_set:
|
|
358
|
+
output_files["jsonl"] = str(write_jsonl(records, out_dir / "tracks.jsonl"))
|
|
359
|
+
if "csv" in export_set:
|
|
360
|
+
output_files["csv"] = str(write_csv(records, out_dir / "tracks.csv"))
|
|
361
|
+
|
|
362
|
+
if self.homography is not None:
|
|
363
|
+
fp_png = self.homography.render_floorplan(out_dir / "floorplan.png")
|
|
364
|
+
fp_json = out_dir / "homography.json"
|
|
365
|
+
self.homography.save_json(fp_json)
|
|
366
|
+
output_files["floorplan"] = str(fp_png)
|
|
367
|
+
output_files["homography"] = str(fp_json)
|
|
368
|
+
|
|
369
|
+
summary = RunSummary(
|
|
370
|
+
source=str(source),
|
|
371
|
+
model=self.model_name,
|
|
372
|
+
tracker=self.tracker_name,
|
|
373
|
+
device=device_label,
|
|
374
|
+
total_frames=seen_frames,
|
|
375
|
+
processed_frames=processed,
|
|
376
|
+
source_fps=src_fps,
|
|
377
|
+
avg_fps=avg_fps,
|
|
378
|
+
avg_inference_ms=avg_inf,
|
|
379
|
+
avg_tracking_ms=avg_trk,
|
|
380
|
+
total_detections=total_dets,
|
|
381
|
+
total_track_observations=len(records),
|
|
382
|
+
unique_tracks=len(card_index.cards),
|
|
383
|
+
recovered_tracks=recovered_count,
|
|
384
|
+
reid_merges=card_index.reid_merges,
|
|
385
|
+
elapsed_s=elapsed_s,
|
|
386
|
+
frame_width=width,
|
|
387
|
+
frame_height=height,
|
|
388
|
+
classes=self.classes,
|
|
389
|
+
query=self.query,
|
|
390
|
+
anonymize_mode=self.anonymize_mode,
|
|
391
|
+
output_files=output_files,
|
|
392
|
+
zone_dwell_totals_s=(
|
|
393
|
+
dict(self.homography.zone_dwell_totals_s) if self.homography is not None else {}
|
|
394
|
+
),
|
|
395
|
+
)
|
|
396
|
+
|
|
397
|
+
if "html" in export_set:
|
|
398
|
+
html_path = write_html_report(
|
|
399
|
+
summary, frame_results, card_index.sorted_cards(), out_dir / "report.html"
|
|
400
|
+
)
|
|
401
|
+
summary.output_files["html"] = str(html_path)
|
|
402
|
+
|
|
403
|
+
summary_path = out_dir / "summary.json"
|
|
404
|
+
summary_path.write_text(json.dumps(summary.to_dict(), indent=2), encoding="utf-8")
|
|
405
|
+
summary.output_files["summary"] = str(summary_path)
|
|
406
|
+
return summary
|
trackflow/privacy.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""Privacy-first anonymization: Gaussian blur, pixelation, head/face blur, and skeleton-only mode."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Literal
|
|
6
|
+
|
|
7
|
+
import cv2
|
|
8
|
+
import numpy as np
|
|
9
|
+
|
|
10
|
+
from trackflow.types import Track
|
|
11
|
+
|
|
12
|
+
AnonymizeMode = Literal["none", "blur", "pixelate", "face-blur", "skeleton"]
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _track_color(track_id: int) -> tuple[int, int, int]:
|
|
16
|
+
"""Deterministic vibrant BGR color per track ID."""
|
|
17
|
+
palette = [
|
|
18
|
+
(92, 214, 148),
|
|
19
|
+
(250, 173, 72),
|
|
20
|
+
(140, 130, 255),
|
|
21
|
+
(240, 200, 70),
|
|
22
|
+
(110, 235, 255),
|
|
23
|
+
(255, 130, 210),
|
|
24
|
+
(135, 255, 190),
|
|
25
|
+
(195, 155, 255),
|
|
26
|
+
]
|
|
27
|
+
return palette[track_id % len(palette)]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class PrivacyAnonymizer:
|
|
31
|
+
"""Applies privacy-preserving transformations so identifiable PII never hits disk."""
|
|
32
|
+
|
|
33
|
+
def __init__(self, mode: AnonymizeMode = "none", *, strength: int = 31) -> None:
|
|
34
|
+
valid = ("none", "blur", "pixelate", "face-blur", "skeleton")
|
|
35
|
+
if mode not in valid:
|
|
36
|
+
raise ValueError(f"Unknown anonymize mode '{mode}'. Choose from: {valid}")
|
|
37
|
+
self.mode: AnonymizeMode = mode
|
|
38
|
+
# Ensure odd kernel size >= 9
|
|
39
|
+
self.kernel_size = max(9, int(strength) | 1)
|
|
40
|
+
|
|
41
|
+
def apply(self, frame_bgr: np.ndarray, tracks: list[Track]) -> np.ndarray:
|
|
42
|
+
"""Return an anonymized copy of ``frame_bgr`` for the given tracked people."""
|
|
43
|
+
if self.mode == "none":
|
|
44
|
+
return frame_bgr
|
|
45
|
+
|
|
46
|
+
if self.mode == "skeleton":
|
|
47
|
+
return self._render_skeleton_canvas(frame_bgr, tracks)
|
|
48
|
+
|
|
49
|
+
out = frame_bgr.copy()
|
|
50
|
+
h, w = out.shape[:2]
|
|
51
|
+
|
|
52
|
+
for tr in tracks:
|
|
53
|
+
x1 = max(0, min(w - 1, int(round(tr.bbox[0]))))
|
|
54
|
+
y1 = max(0, min(h - 1, int(round(tr.bbox[1]))))
|
|
55
|
+
x2 = max(x1 + 1, min(w, int(round(tr.bbox[2]))))
|
|
56
|
+
y2 = max(y1 + 1, min(h, int(round(tr.bbox[3]))))
|
|
57
|
+
if x2 - x1 < 4 or y2 - y1 < 4:
|
|
58
|
+
continue
|
|
59
|
+
|
|
60
|
+
if self.mode == "blur":
|
|
61
|
+
roi = out[y1:y2, x1:x2]
|
|
62
|
+
out[y1:y2, x1:x2] = cv2.GaussianBlur(roi, (self.kernel_size, self.kernel_size), 0)
|
|
63
|
+
elif self.mode == "pixelate":
|
|
64
|
+
roi = out[y1:y2, x1:x2]
|
|
65
|
+
bw, bh = max(4, (x2 - x1) // 10), max(4, (y2 - y1) // 10)
|
|
66
|
+
small = cv2.resize(roi, (bw, bh), interpolation=cv2.INTER_LINEAR)
|
|
67
|
+
out[y1:y2, x1:x2] = cv2.resize(
|
|
68
|
+
small, (x2 - x1, y2 - y1), interpolation=cv2.INTER_NEAREST
|
|
69
|
+
)
|
|
70
|
+
elif self.mode == "face-blur":
|
|
71
|
+
# Blur upper head/face ellipse (top 30% of person bounding box)
|
|
72
|
+
head_h = max(8, int((y2 - y1) * 0.30))
|
|
73
|
+
fy2 = min(h, y1 + head_h)
|
|
74
|
+
roi = out[y1:fy2, x1:x2]
|
|
75
|
+
blurred = cv2.GaussianBlur(roi, (self.kernel_size, self.kernel_size), 0)
|
|
76
|
+
mask = np.zeros((fy2 - y1, x2 - x1), dtype=np.uint8)
|
|
77
|
+
cv2.ellipse(
|
|
78
|
+
mask,
|
|
79
|
+
((x2 - x1) // 2, (fy2 - y1) // 2),
|
|
80
|
+
(max(2, int((x2 - x1) * 0.42)), max(2, int((fy2 - y1) * 0.48))),
|
|
81
|
+
0,
|
|
82
|
+
0,
|
|
83
|
+
360,
|
|
84
|
+
255,
|
|
85
|
+
-1,
|
|
86
|
+
)
|
|
87
|
+
out[y1:fy2, x1:x2] = np.where(mask[:, :, None] > 0, blurred, roi)
|
|
88
|
+
|
|
89
|
+
return out
|
|
90
|
+
|
|
91
|
+
@staticmethod
|
|
92
|
+
def _render_skeleton_canvas(frame_bgr: np.ndarray, tracks: list[Track]) -> np.ndarray:
|
|
93
|
+
"""Render zero-PII pose-skeleton figures on a subtle dark grid canvas."""
|
|
94
|
+
h, w = frame_bgr.shape[:2]
|
|
95
|
+
canvas = np.full((h, w, 3), (18, 20, 26), dtype=np.uint8)
|
|
96
|
+
|
|
97
|
+
# Subtle analytics grid
|
|
98
|
+
step = max(32, min(w, h) // 12)
|
|
99
|
+
for gx in range(0, w, step):
|
|
100
|
+
cv2.line(canvas, (gx, 0), (gx, h), (28, 32, 42), 1)
|
|
101
|
+
for gy in range(0, h, step):
|
|
102
|
+
cv2.line(canvas, (0, gy), (w, gy), (28, 32, 42), 1)
|
|
103
|
+
|
|
104
|
+
for tr in tracks:
|
|
105
|
+
x1, y1, x2, y2 = tr.bbox
|
|
106
|
+
bw = max(8.0, x2 - x1)
|
|
107
|
+
bh = max(16.0, y2 - y1)
|
|
108
|
+
cx = int(round((x1 + x2) * 0.5))
|
|
109
|
+
color = _track_color(tr.track_id)
|
|
110
|
+
|
|
111
|
+
# Anatomical landmarks scaled to bounding box
|
|
112
|
+
head_y = int(round(y1 + bh * 0.12))
|
|
113
|
+
head_r = max(3, int(round(min(bw * 0.18, bh * 0.08))))
|
|
114
|
+
neck = (cx, int(round(y1 + bh * 0.22)))
|
|
115
|
+
hip = (cx, int(round(y1 + bh * 0.56)))
|
|
116
|
+
l_shoulder = (int(round(cx - bw * 0.24)), int(round(y1 + bh * 0.26)))
|
|
117
|
+
r_shoulder = (int(round(cx + bw * 0.24)), int(round(y1 + bh * 0.26)))
|
|
118
|
+
l_hand = (int(round(cx - bw * 0.34)), int(round(y1 + bh * 0.52)))
|
|
119
|
+
r_hand = (int(round(cx + bw * 0.34)), int(round(y1 + bh * 0.52)))
|
|
120
|
+
l_knee = (int(round(cx - bw * 0.15)), int(round(y1 + bh * 0.78)))
|
|
121
|
+
r_knee = (int(round(cx + bw * 0.15)), int(round(y1 + bh * 0.78)))
|
|
122
|
+
l_foot = (int(round(cx - bw * 0.18)), int(round(y2 - 2)))
|
|
123
|
+
r_foot = (int(round(cx + bw * 0.18)), int(round(y2 - 2)))
|
|
124
|
+
|
|
125
|
+
# Head & skeleton limbs
|
|
126
|
+
cv2.circle(canvas, (cx, head_y), head_r, color, 2, cv2.LINE_AA)
|
|
127
|
+
bones = [
|
|
128
|
+
(neck, hip),
|
|
129
|
+
(l_shoulder, r_shoulder),
|
|
130
|
+
(l_shoulder, l_hand),
|
|
131
|
+
(r_shoulder, r_hand),
|
|
132
|
+
(hip, l_knee),
|
|
133
|
+
(l_knee, l_foot),
|
|
134
|
+
(hip, r_knee),
|
|
135
|
+
(r_knee, r_foot),
|
|
136
|
+
]
|
|
137
|
+
for p1, p2 in bones:
|
|
138
|
+
cv2.line(canvas, p1, p2, color, 2, cv2.LINE_AA)
|
|
139
|
+
|
|
140
|
+
for joint in (neck, hip, l_shoulder, r_shoulder, l_knee, r_knee):
|
|
141
|
+
cv2.circle(canvas, joint, 3, (240, 245, 255), -1, cv2.LINE_AA)
|
|
142
|
+
|
|
143
|
+
return canvas
|