trackflow-python-tensorrt 0.7.0__cp310-abi3-win_amd64.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/privacy.py ADDED
@@ -0,0 +1,266 @@
1
+ """Privacy anonymization: Gaussian blur, pixelation, head/face blur, and stick-figure-only mode.
2
+
3
+ Best effort, not a guarantee: every box the detector produced (any score, including people not yet
4
+ confirmed as tracks) plus briefly-missed tracks is anonymized, with a margin. A person the detector
5
+ never finds in a frame is not. ``face-blur`` assumes the head is in the top 30% of the box.
6
+ ``skeleton`` draws a fixed stick figure inside each track box (no pose estimation) on a blank
7
+ canvas, so no video pixels are written at all.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from collections.abc import Sequence
13
+ from typing import Literal
14
+
15
+ import cv2
16
+ import numpy as np
17
+
18
+ from trackflow.types import Detection, Track
19
+
20
+ AnonymizeMode = Literal["none", "blur", "pixelate", "face-blur", "skeleton"]
21
+
22
+
23
+ def _track_color(track_id: int) -> tuple[int, int, int]:
24
+ """Deterministic vibrant BGR color per track ID."""
25
+ palette = [
26
+ (92, 214, 148),
27
+ (250, 173, 72),
28
+ (140, 130, 255),
29
+ (240, 200, 70),
30
+ (110, 235, 255),
31
+ (255, 130, 210),
32
+ (135, 255, 190),
33
+ (195, 155, 255),
34
+ ]
35
+ return palette[track_id % len(palette)]
36
+
37
+
38
+ def _fast_gaussian_blur(roi: np.ndarray, kernel_size: int) -> np.ndarray:
39
+ """Gaussian blur with 2x downscale-blur-upsample for large ROIs and wide kernels."""
40
+ rh, rw = roi.shape[:2]
41
+ if kernel_size >= 21 and rh >= 32 and rw >= 32:
42
+ half_k = max(5, (kernel_size // 2) | 1)
43
+ small = cv2.resize(roi, (max(2, rw // 2), max(2, rh // 2)), interpolation=cv2.INTER_AREA)
44
+ blurred_small = cv2.GaussianBlur(small, (half_k, half_k), 0)
45
+ return cv2.resize(blurred_small, (rw, rh), interpolation=cv2.INTER_LINEAR)
46
+ return cv2.GaussianBlur(roi, (kernel_size, kernel_size), 0)
47
+
48
+
49
+ def _dedup_boxes_preserving_coverage(
50
+ rects: list[tuple[int, int, int, int]],
51
+ *,
52
+ merge_iou: float = 0.85,
53
+ ) -> list[tuple[int, int, int, int]]:
54
+ """Collapse redundant overlapping rects without ever uncovering any pixel.
55
+
56
+ Drops boxes strictly contained inside an already-kept box, and merges near-identical
57
+ overlapping boxes (``IoU >= merge_iou``, e.g. a track box and its raw detection box)
58
+ into their enclosing union rectangle so every original pixel stays covered in one pass.
59
+ """
60
+ if len(rects) <= 1:
61
+ return rects
62
+ # Largest first so strictly contained boxes are eliminated immediately.
63
+ ordered = sorted(rects, key=lambda r: (r[2] - r[0]) * (r[3] - r[1]), reverse=True)
64
+ kept: list[tuple[int, int, int, int]] = []
65
+ for x1, y1, x2, y2 in ordered:
66
+ area_a = (x2 - x1) * (y2 - y1)
67
+ merged = False
68
+ for i, (kx1, ky1, kx2, ky2) in enumerate(kept):
69
+ if kx1 <= x1 and ky1 <= y1 and kx2 >= x2 and ky2 >= y2:
70
+ merged = True
71
+ break
72
+ iw = min(x2, kx2) - max(x1, kx1)
73
+ ih = min(y2, ky2) - max(y1, ky1)
74
+ if iw > 0 and ih > 0:
75
+ inter = iw * ih
76
+ area_b = (kx2 - kx1) * (ky2 - ky1)
77
+ if inter / (area_a + area_b - inter) >= merge_iou:
78
+ kept[i] = (min(x1, kx1), min(y1, ky1), max(x2, kx2), max(y2, ky2))
79
+ merged = True
80
+ break
81
+ if not merged:
82
+ kept.append((x1, y1, x2, y2))
83
+ return kept
84
+
85
+
86
+ def _cluster_head_boxes(
87
+ head_rects: list[tuple[int, int, int, int]],
88
+ *,
89
+ cluster_iou: float = 0.50,
90
+ ) -> list[tuple[tuple[int, int, int, int], list[tuple[int, int, int, int]]]]:
91
+ """Group overlapping head rects so face-blur runs one blur per cluster with exact ellipses."""
92
+ if not head_rects:
93
+ return []
94
+ # Deduplicate exact identical head rects first (order-independent for union of ellipses).
95
+ unique_rects = list(dict.fromkeys(head_rects))
96
+ clusters: list[list[tuple[int, int, int, int]]] = []
97
+ unions: list[tuple[int, int, int, int]] = []
98
+ for r in sorted(unique_rects, key=lambda b: (b[2] - b[0]) * (b[3] - b[1]), reverse=True):
99
+ x1, y1, x2, y2 = r
100
+ area_a = (x2 - x1) * (y2 - y1)
101
+ placed = False
102
+ for i, (ux1, uy1, ux2, uy2) in enumerate(unions):
103
+ if ux1 <= x1 and uy1 <= y1 and ux2 >= x2 and uy2 >= y2:
104
+ clusters[i].append(r)
105
+ placed = True
106
+ break
107
+ iw = min(x2, ux2) - max(x1, ux1)
108
+ ih = min(y2, uy2) - max(y1, uy1)
109
+ if iw > 0 and ih > 0:
110
+ inter = iw * ih
111
+ area_b = (ux2 - ux1) * (uy2 - uy1)
112
+ if inter / (area_a + area_b - inter) >= cluster_iou:
113
+ clusters[i].append(r)
114
+ unions[i] = (min(x1, ux1), min(y1, uy1), max(x2, ux2), max(y2, uy2))
115
+ placed = True
116
+ break
117
+ if not placed:
118
+ clusters.append([r])
119
+ unions.append(r)
120
+ return list(zip(unions, clusters, strict=True))
121
+
122
+
123
+ class PrivacyAnonymizer:
124
+ """Applies privacy-preserving transformations to every detected person box."""
125
+
126
+ def __init__(
127
+ self, mode: AnonymizeMode = "none", *, strength: int = 31, margin: float = 0.08
128
+ ) -> None:
129
+ valid = ("none", "blur", "pixelate", "face-blur", "skeleton")
130
+ if mode not in valid:
131
+ raise ValueError(f"Unknown anonymize mode '{mode}'. Choose from: {valid}")
132
+ self.mode: AnonymizeMode = mode
133
+ # Ensure odd kernel size >= 9
134
+ self.kernel_size = max(9, int(strength) | 1)
135
+ self.margin = float(margin)
136
+
137
+ def apply(
138
+ self,
139
+ frame_bgr: np.ndarray,
140
+ tracks: Sequence[Track],
141
+ *,
142
+ detections: Sequence[Detection] = (),
143
+ coasting: Sequence[Track] = (),
144
+ ) -> np.ndarray:
145
+ """Return an anonymized copy of ``frame_bgr``.
146
+
147
+ Anonymizes the boxes of ``tracks``, of briefly-missed ``coasting`` tracks, and of all raw
148
+ ``detections`` (pass every detection, not only the ones that became tracks).
149
+ """
150
+ if self.mode == "none":
151
+ return frame_bgr
152
+
153
+ if self.mode == "skeleton":
154
+ return self._render_skeleton_canvas(frame_bgr, [*tracks, *coasting])
155
+
156
+ out = frame_bgr.copy()
157
+ h, w = out.shape[:2]
158
+
159
+ rects: list[tuple[int, int, int, int]] = []
160
+ for box in (
161
+ *(t.bbox for t in tracks),
162
+ *(t.bbox for t in coasting),
163
+ *(d.bbox for d in detections),
164
+ ):
165
+ bx1, by1, bx2, by2 = box
166
+ mx, my = (bx2 - bx1) * self.margin, (by2 - by1) * self.margin
167
+ x1 = max(0, min(w - 1, int(round(bx1 - mx))))
168
+ y1 = max(0, min(h - 1, int(round(by1 - my))))
169
+ x2 = max(x1 + 1, min(w, int(round(bx2 + mx))))
170
+ y2 = max(y1 + 1, min(h, int(round(by2 + my))))
171
+ if x2 - x1 < 4 or y2 - y1 < 4:
172
+ continue
173
+ rects.append((x1, y1, x2, y2))
174
+
175
+ if not rects:
176
+ return out
177
+
178
+ if self.mode == "face-blur":
179
+ head_rects = [
180
+ (x1, y1, x2, min(h, y1 + max(8, int((y2 - y1) * 0.30))))
181
+ for x1, y1, x2, y2 in rects
182
+ ]
183
+ for (ux1, uy1, ux2, uy2), members in _cluster_head_boxes(head_rects):
184
+ roi = out[uy1:uy2, ux1:ux2]
185
+ blurred = _fast_gaussian_blur(roi, self.kernel_size)
186
+ mask = np.zeros((uy2 - uy1, ux2 - ux1), dtype=np.uint8)
187
+ for rx1, ry1, rx2, ry2 in members:
188
+ cv2.ellipse(
189
+ mask,
190
+ ((rx1 + rx2) // 2 - ux1, (ry1 + ry2) // 2 - uy1),
191
+ (max(2, int((rx2 - rx1) * 0.42)), max(2, int((ry2 - ry1) * 0.48))),
192
+ 0,
193
+ 0,
194
+ 360,
195
+ 255,
196
+ -1,
197
+ )
198
+ out[uy1:uy2, ux1:ux2] = np.where(mask[:, :, None] > 0, blurred, roi)
199
+ return out
200
+
201
+ for x1, y1, x2, y2 in _dedup_boxes_preserving_coverage(rects):
202
+ roi = out[y1:y2, x1:x2]
203
+ if self.mode == "blur":
204
+ out[y1:y2, x1:x2] = _fast_gaussian_blur(roi, self.kernel_size)
205
+ elif self.mode == "pixelate":
206
+ bw, bh = max(4, (x2 - x1) // 10), max(4, (y2 - y1) // 10)
207
+ small = cv2.resize(roi, (bw, bh), interpolation=cv2.INTER_LINEAR)
208
+ out[y1:y2, x1:x2] = cv2.resize(
209
+ small, (x2 - x1, y2 - y1), interpolation=cv2.INTER_NEAREST
210
+ )
211
+
212
+ return out
213
+
214
+ @staticmethod
215
+ def _render_skeleton_canvas(frame_bgr: np.ndarray, tracks: Sequence[Track]) -> np.ndarray:
216
+ """Render box-based stick figures (no pose estimation) on a blank grid canvas."""
217
+ h, w = frame_bgr.shape[:2]
218
+ canvas = np.full((h, w, 3), (18, 20, 26), dtype=np.uint8)
219
+
220
+ # Subtle analytics grid
221
+ step = max(32, min(w, h) // 12)
222
+ for gx in range(0, w, step):
223
+ cv2.line(canvas, (gx, 0), (gx, h), (28, 32, 42), 1)
224
+ for gy in range(0, h, step):
225
+ cv2.line(canvas, (0, gy), (w, gy), (28, 32, 42), 1)
226
+
227
+ for tr in tracks:
228
+ x1, y1, x2, y2 = tr.bbox
229
+ bw = max(8.0, x2 - x1)
230
+ bh = max(16.0, y2 - y1)
231
+ cx = int(round((x1 + x2) * 0.5))
232
+ color = _track_color(tr.track_id)
233
+
234
+ # Anatomical landmarks scaled to bounding box
235
+ head_y = int(round(y1 + bh * 0.12))
236
+ head_r = max(3, int(round(min(bw * 0.18, bh * 0.08))))
237
+ neck = (cx, int(round(y1 + bh * 0.22)))
238
+ hip = (cx, int(round(y1 + bh * 0.56)))
239
+ l_shoulder = (int(round(cx - bw * 0.24)), int(round(y1 + bh * 0.26)))
240
+ r_shoulder = (int(round(cx + bw * 0.24)), int(round(y1 + bh * 0.26)))
241
+ l_hand = (int(round(cx - bw * 0.34)), int(round(y1 + bh * 0.52)))
242
+ r_hand = (int(round(cx + bw * 0.34)), int(round(y1 + bh * 0.52)))
243
+ l_knee = (int(round(cx - bw * 0.15)), int(round(y1 + bh * 0.78)))
244
+ r_knee = (int(round(cx + bw * 0.15)), int(round(y1 + bh * 0.78)))
245
+ l_foot = (int(round(cx - bw * 0.18)), int(round(y2 - 2)))
246
+ r_foot = (int(round(cx + bw * 0.18)), int(round(y2 - 2)))
247
+
248
+ # Head & skeleton limbs
249
+ cv2.circle(canvas, (cx, head_y), head_r, color, 2, cv2.LINE_AA)
250
+ bones = [
251
+ (neck, hip),
252
+ (l_shoulder, r_shoulder),
253
+ (l_shoulder, l_hand),
254
+ (r_shoulder, r_hand),
255
+ (hip, l_knee),
256
+ (l_knee, l_foot),
257
+ (hip, r_knee),
258
+ (r_knee, r_foot),
259
+ ]
260
+ for p1, p2 in bones:
261
+ cv2.line(canvas, p1, p2, color, 2, cv2.LINE_AA)
262
+
263
+ for joint in (neck, hip, l_shoulder, r_shoulder, l_knee, r_knee):
264
+ cv2.circle(canvas, joint, 3, (240, 245, 255), -1, cv2.LINE_AA)
265
+
266
+ return canvas
trackflow/py.typed ADDED
@@ -0,0 +1 @@
1
+