trackflow-python-tensorrt 0.6.1__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.
@@ -0,0 +1,440 @@
1
+ """BoostTrack++ multi-object tracker (Stanojević & Todorović, 2024).
2
+
3
+ A port of the reference implementation (github.com/vukasin-stanojevic/BoostTrack, MIT license)
4
+ with its BoostTrack++ settings, onto Trackflow's track lifecycle. Association is class-aware, and
5
+ each assignment only considers pairs that pass the IoU gate. Camera motion is estimated with
6
+ sparse optical flow (the reference uses ECC), and shape similarity normalizes the height
7
+ difference by height.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from typing import Any
13
+
14
+ import numpy as np
15
+
16
+ from trackflow.tracker import (
17
+ SparseOpticalFlowCMC,
18
+ XywhKalmanFilter,
19
+ _assign,
20
+ _boxes,
21
+ _expand_boxes,
22
+ _SortStyleTracker,
23
+ _SortTrack,
24
+ _xyxy_to_xywh,
25
+ compute_hmiou_matrix,
26
+ compute_ioa_matrix,
27
+ compute_iou_matrix,
28
+ )
29
+ from trackflow.types import Detection, Track
30
+
31
+ Box = tuple[float, float, float, float]
32
+
33
+ # 99% quantile of the chi-square distribution with 4 degrees of freedom.
34
+ _MAHALANOBIS_LIMIT = 13.2767
35
+
36
+
37
+ def _mahalanobis_similarity(dist: np.ndarray) -> np.ndarray:
38
+ """Softmax over detections of ``limit - distance`` for each track; zero beyond the limit."""
39
+ far = dist > _MAHALANOBIS_LIMIT
40
+ weights = np.exp(_MAHALANOBIS_LIMIT - np.minimum(dist, _MAHALANOBIS_LIMIT))
41
+ sim = weights / weights.sum(axis=0, keepdims=True)
42
+ sim[far] = 0.0
43
+ return sim
44
+
45
+
46
+ def _shape_similarity(dets: np.ndarray, tracks: np.ndarray) -> np.ndarray:
47
+ dw = (dets[:, 2] - dets[:, 0])[:, None]
48
+ dh = (dets[:, 3] - dets[:, 1])[:, None]
49
+ tw = (tracks[:, 2] - tracks[:, 0])[None, :]
50
+ th = (tracks[:, 3] - tracks[:, 1])[None, :]
51
+ return np.exp(
52
+ -(
53
+ np.abs(dw - tw) / np.maximum(np.maximum(dw, tw), 1e-6)
54
+ + np.abs(dh - th) / np.maximum(np.maximum(dh, th), 1e-6)
55
+ )
56
+ )
57
+
58
+
59
+ def _soft_buffered_iou(dets: np.ndarray, tracks: np.ndarray, track_conf: np.ndarray) -> np.ndarray:
60
+ """IoU after growing both boxes in proportion to how uncertain the track is."""
61
+ grow = np.minimum(0.75, 1.0 - track_conf)[None, :, None]
62
+ d = dets[:, None, :]
63
+ t = tracks[None, :, :]
64
+ d_size = np.concatenate([d[..., 2:] - d[..., :2]] * 2, axis=-1)
65
+ t_size = np.concatenate([t[..., 2:] - t[..., :2]] * 2, axis=-1)
66
+ sign = np.array([-1.0, -1.0, 1.0, 1.0])
67
+ db = d + sign * d_size * grow * 0.25
68
+ tb = t + sign * t_size * grow * 0.5
69
+ iw = np.maximum(0.0, np.minimum(db[..., 2], tb[..., 2]) - np.maximum(db[..., 0], tb[..., 0]))
70
+ ih = np.maximum(0.0, np.minimum(db[..., 3], tb[..., 3]) - np.maximum(db[..., 1], tb[..., 1]))
71
+ inter = iw * ih
72
+ area_d = (db[..., 2] - db[..., 0]) * (db[..., 3] - db[..., 1])
73
+ area_t = (tb[..., 2] - tb[..., 0]) * (tb[..., 3] - tb[..., 1])
74
+ return inter / np.maximum(area_d + area_t - inter, 1e-6)
75
+
76
+
77
+ def _unit_rows(vectors: list[np.ndarray | None], dim: int) -> tuple[np.ndarray, np.ndarray]:
78
+ out = np.zeros((len(vectors), dim), dtype=np.float64)
79
+ has = np.zeros(len(vectors), dtype=bool)
80
+ for i, v in enumerate(vectors):
81
+ if v is None:
82
+ continue
83
+ norm = float(np.linalg.norm(v))
84
+ if norm > 1e-6 and v.shape[0] == dim:
85
+ out[i] = v / norm
86
+ has[i] = True
87
+ return out, has
88
+
89
+
90
+ class BoostTracker(_SortStyleTracker):
91
+ """BoostTrack++: SORT with a richer similarity and detection-confidence boosting.
92
+
93
+ Each frame:
94
+
95
+ 1. tracks move with camera motion (``use_cmc``), then are predicted;
96
+ 2. detection scores are boosted. A detection that closely matches a track (by Mahalanobis
97
+ distance, shape and a soft buffered IoU) is likely a real object (DLO boost). A
98
+ low-score detection far from every track, and stronger than overlapping such detections,
99
+ is likely a new object (DUO boost). Detections still below ``det_thresh`` are dropped;
100
+ 3. detections <-> tracks by IoU, plus IoU weighted by detection and track confidence,
101
+ Mahalanobis and shape similarity, and appearance when detections carry Re-ID
102
+ embeddings. A pair needs IoU >= ``iou_threshold``, or half that with appearance
103
+ similarity >= 0.75;
104
+ 4. unmatched detections spawn tracks.
105
+
106
+ A track's confidence is low while it is young and decays while it goes unmatched.
107
+ Confirmed tracks report the filter's estimate.
108
+ """
109
+
110
+ name: str = "boosttrack"
111
+
112
+ def __init__(
113
+ self,
114
+ *,
115
+ det_thresh: float = 0.5,
116
+ iou_threshold: float = 0.3,
117
+ max_age: int = 30,
118
+ min_hits: int = 3,
119
+ lambda_iou: float = 0.5,
120
+ lambda_mhd: float = 0.25,
121
+ lambda_shape: float = 0.25,
122
+ dlo_boost: bool = True,
123
+ duo_boost: bool = False,
124
+ use_cmc: bool = True,
125
+ iou_buffer: float = 0.0,
126
+ new_track_thresh: float | None = None,
127
+ ) -> None:
128
+ self.det_thresh = float(det_thresh)
129
+ self.new_track_thresh = (
130
+ float(new_track_thresh)
131
+ if new_track_thresh is not None
132
+ else max(self.det_thresh, min(0.95, self.det_thresh + 0.05))
133
+ )
134
+ self.iou_threshold = float(iou_threshold)
135
+ self.lambda_iou = float(lambda_iou)
136
+ self.lambda_mhd = float(lambda_mhd)
137
+ self.lambda_shape = float(lambda_shape)
138
+ self.lambda_emb = 1.5 * (1.0 + self.lambda_iou + self.lambda_shape + self.lambda_mhd)
139
+ self.dlo_boost = bool(dlo_boost)
140
+ self.duo_boost = bool(duo_boost)
141
+ self.use_cmc = bool(use_cmc)
142
+ # Buffered IoU for association (see iou_buffer_for_interval).
143
+ self.iou_buffer = float(iou_buffer)
144
+ # Keep embeddings available down to low-confidence detections.
145
+ self.embedding_min_confidence = min(0.20, self.det_thresh)
146
+ super().__init__(max_age=max_age, min_hits=min_hits)
147
+
148
+ def reset(self) -> None:
149
+ super().reset()
150
+ self._cmc = SparseOpticalFlowCMC() if self.use_cmc else None
151
+
152
+ def _predict(self) -> None:
153
+ for tr in self._tracks:
154
+ if tr.time_since_update > 0:
155
+ tr.motion.mean[6:] = 0.0 # a missed track keeps moving but stops resizing
156
+ super()._predict()
157
+
158
+ @staticmethod
159
+ def _track_confidence(tr: _SortTrack) -> float:
160
+ if tr.age < 7:
161
+ return 0.9 ** (7 - tr.age)
162
+ return 0.9 ** (tr.time_since_update - 1)
163
+
164
+ @staticmethod
165
+ def _mahalanobis(dets: list[Detection], tracks: list[_SortTrack]) -> np.ndarray:
166
+ """Squared NSA innovation distance of each detection to each track."""
167
+ z = np.array([_xyxy_to_xywh(d.bbox) for d in dets], dtype=np.float64)
168
+ nsa = np.array(
169
+ [max(0.1, 1.0 - min(float(d.confidence), 0.95)) for d in dets], dtype=np.float64
170
+ )
171
+ x = np.array([t.motion.mean[:4] for t in tracks], dtype=np.float64)
172
+ p_diag = np.array([np.diag(t.motion.cov)[:4] for t in tracks], dtype=np.float64)
173
+ r_base = np.array([t.motion.measurement_var() for t in tracks], dtype=np.float64)
174
+ s_diag = np.maximum(p_diag[None, :, :] + nsa[:, None, None] * r_base[None, :, :], 1e-6)
175
+ dist = (((z[:, None, :] - x[None, :, :]) ** 2) / s_diag).sum(axis=2)
176
+ same_class = np.equal.outer([d.class_id for d in dets], [t.class_id for t in tracks])
177
+ return np.where(same_class, dist, np.inf)
178
+
179
+ def _duo_promote(
180
+ self,
181
+ dets: list[Detection],
182
+ tracks: list[_SortTrack],
183
+ scores: np.ndarray,
184
+ ) -> np.ndarray:
185
+ """Promote isolated moderate-confidence detections that are far from existing tracks."""
186
+ promoted = np.zeros(len(dets), dtype=bool)
187
+ if not self.duo_boost or self._frame_id <= 1 or not dets or not tracks:
188
+ return promoted
189
+ duo_floor = max(0.35, self.det_thresh - 0.15)
190
+ mahalanobis = self._mahalanobis(dets, tracks)
191
+ d_boxes = _boxes(dets)
192
+ t_boxes = np.array([t.motion.box for t in tracks], dtype=np.float64)
193
+ max_track_iou = compute_iou_matrix(d_boxes, t_boxes).max(axis=1)
194
+ candidates = np.flatnonzero(
195
+ (mahalanobis.min(axis=1) > _MAHALANOBIS_LIMIT)
196
+ & (max_track_iou < 0.1)
197
+ & (scores >= duo_floor)
198
+ & (scores < self.det_thresh)
199
+ )
200
+ if candidates.size:
201
+ overlap = compute_iou_matrix(d_boxes[candidates], d_boxes[candidates])
202
+ np.fill_diagonal(overlap, 0.0)
203
+ for k, i in enumerate(candidates):
204
+ if scores[i] >= scores[candidates[overlap[k] > 0.3]].max(initial=-np.inf):
205
+ promoted[i] = True
206
+ return promoted
207
+
208
+ def _associate(
209
+ self,
210
+ tracks: list[_SortTrack],
211
+ dets: list[Detection],
212
+ scores: np.ndarray,
213
+ track_conf: np.ndarray,
214
+ ) -> tuple[list[tuple[int, int]], list[int], list[int]]:
215
+ """Match detections (rows) to tracks (columns)."""
216
+ if not tracks or not dets:
217
+ return [], list(range(len(dets))), list(range(len(tracks)))
218
+ d_boxes = _boxes(dets)
219
+ t_boxes = np.array([t.motion.box for t in tracks], dtype=np.float64)
220
+ d_exp = _expand_boxes(d_boxes, self.iou_buffer)
221
+ t_exp = _expand_boxes(t_boxes, self.iou_buffer)
222
+ iou = compute_iou_matrix(d_exp, t_exp)
223
+ sb_iou = _soft_buffered_iou(d_exp, t_exp, track_conf)
224
+ mahalanobis = self._mahalanobis(dets, tracks)
225
+ low_iou_gate = min(self.iou_threshold, 0.20)
226
+ valid = (sb_iou >= self.iou_threshold) | (
227
+ (sb_iou >= low_iou_gate) & (mahalanobis <= _MAHALANOBIS_LIMIT)
228
+ )
229
+ conf = np.where(valid, scores[:, None] * track_conf[None, :], 0.0)
230
+ sim = (
231
+ compute_hmiou_matrix(d_boxes, t_boxes, sb_iou)
232
+ + self.lambda_iou * conf * sb_iou
233
+ + self.lambda_mhd * _mahalanobis_similarity(mahalanobis)
234
+ + self.lambda_shape * conf * _shape_similarity(d_boxes, t_boxes)
235
+ )
236
+
237
+ known = [t.embedding for t in tracks if t.embedding is not None]
238
+ if known and any(d.embedding is not None for d in dets):
239
+ dim = known[0].shape[0]
240
+ d_emb, d_has = _unit_rows([d.embedding for d in dets], dim)
241
+ t_emb, t_has = _unit_rows([t.embedding for t in tracks], dim)
242
+ appearance = (d_emb @ t_emb.T) * np.outer(d_has, t_has)
243
+ sim = sim + self.lambda_emb * appearance
244
+ valid |= (iou >= self.iou_threshold / 2) & (appearance >= 0.75)
245
+
246
+ return _assign(sim, valid & ~np.isinf(mahalanobis))
247
+
248
+ def _associate_low(
249
+ self,
250
+ tracks: list[_SortTrack],
251
+ dets: list[Detection],
252
+ scores: np.ndarray,
253
+ ) -> list[tuple[int, int]]:
254
+ """Second-stage tight-IoU association for active tracks with low-score detections."""
255
+ if not tracks or not dets:
256
+ return []
257
+ d_boxes = _boxes(dets)
258
+ t_boxes = np.array([t.motion.box for t in tracks], dtype=np.float64)
259
+ iou = compute_iou_matrix(d_boxes, t_boxes)
260
+ mahalanobis = self._mahalanobis(dets, tracks)
261
+ mhd_ok = mahalanobis <= _MAHALANOBIS_LIMIT
262
+ valid = ((iou >= 0.45) | ((iou >= 0.35) & mhd_ok & (scores[:, None] >= 0.25))) & ~np.isinf(
263
+ mahalanobis
264
+ )
265
+ sim = (
266
+ iou
267
+ + self.lambda_mhd * _mahalanobis_similarity(mahalanobis)
268
+ + self.lambda_shape * scores[:, None] * _shape_similarity(d_boxes, t_boxes)
269
+ )
270
+ matches, _, _ = _assign(sim, valid)
271
+ return matches
272
+
273
+ def _remove_duplicates(self) -> None:
274
+ tracked = [t for t in self._tracks if t.time_since_update == 0]
275
+ lost = [t for t in self._tracks if 0 < t.time_since_update <= self.track_buffer]
276
+ if not tracked or not lost:
277
+ return
278
+ t_boxes = np.array([t.box for t in tracked], dtype=np.float64)
279
+ l_boxes = np.array([t.motion.box for t in lost], dtype=np.float64)
280
+ iou = compute_iou_matrix(t_boxes, l_boxes)
281
+ drop: set[int] = set()
282
+ for p, q in zip(*np.where(iou > 0.85), strict=False):
283
+ a, b = tracked[int(p)], lost[int(q)]
284
+ if a.class_id != b.class_id:
285
+ continue
286
+ # Never delete an already-confirmed active track that matched this frame; only drop
287
+ # the overlapping lost track, or a newly-spawned tentative duplicate under a confirmed one.
288
+ if a.track_id or a.age >= b.age:
289
+ drop.add(b.uid)
290
+ else:
291
+ drop.add(a.uid)
292
+ if drop:
293
+ self._tracks = [t for t in self._tracks if t.uid not in drop]
294
+
295
+ def update(
296
+ self,
297
+ detections: list[Detection],
298
+ frame_bgr: np.ndarray | None = None,
299
+ ) -> list[Track]:
300
+ """Advance the tracker by one frame and return the tracks reported on it."""
301
+ self._frame_id += 1
302
+ events: list[dict[str, Any]] = []
303
+ if self._cmc is not None and frame_bgr is not None:
304
+ # Estimate on every frame (even with no tracks) so the reference frame never goes stale.
305
+ warp = self._cmc.estimate(frame_bgr, _boxes(detections))
306
+ if warp is not None:
307
+ for tr in self._tracks:
308
+ tr.motion.apply_camera_warp(warp)
309
+ self._predict()
310
+ confirmed = [t for t in self._tracks if t.track_id > 0]
311
+ unconfirmed = [t for t in self._tracks if t.track_id == 0]
312
+ all_tracks = confirmed + unconfirmed
313
+
314
+ raw_scores = np.array([d.confidence for d in detections], dtype=np.float64)
315
+ duo_promoted = self._duo_promote(detections, all_tracks, raw_scores)
316
+ high_mask = (raw_scores >= self.det_thresh) | duo_promoted
317
+ high_indices = np.flatnonzero(high_mask)
318
+ low_indices = np.flatnonzero(~high_mask)
319
+
320
+ high_dets = [detections[i] for i in high_indices]
321
+ high_scores = np.where(
322
+ duo_promoted[high_indices], self.det_thresh + 1e-4, raw_scores[high_indices]
323
+ )
324
+ high_duo = duo_promoted[high_indices]
325
+
326
+ updated_boxes: dict[int, list[Box]] = {}
327
+ matched_uids: set[int] = set()
328
+
329
+ def _apply_match(tr: _SortTrack, det: Detection, score: float, *, blend_emb: bool) -> None:
330
+ tr.motion.update(det.bbox, confidence=det.confidence)
331
+ self._observe(tr, det, tr.motion.box)
332
+ updated_boxes.setdefault(tr.class_id, []).append(tr.box)
333
+ matched_uids.add(tr.uid)
334
+ if blend_emb:
335
+ trust = (score - self.det_thresh) / max(1.0 - self.det_thresh, 1e-6)
336
+ tr.blend_embedding(det.embedding, alpha=0.95 + 0.05 * (1.0 - trust))
337
+
338
+ # Stage 1: match confirmed (active + lost) tracks with high-score detections.
339
+ conf_tconf = np.array([self._track_confidence(t) for t in confirmed], dtype=np.float64)
340
+ matches, u_det, u_conf = self._associate(confirmed, high_dets, high_scores, conf_tconf)
341
+ for di, ti in matches:
342
+ _apply_match(confirmed[ti], high_dets[di], float(high_scores[di]), blend_emb=True)
343
+
344
+ # Stage 2: DLO low-score recovery for remaining active and recently missed confirmed tracks.
345
+ used_low: set[int] = set()
346
+ if self.dlo_boost and low_indices.size:
347
+ active_conf = [confirmed[ti] for ti in u_conf if confirmed[ti].time_since_update == 1]
348
+ dlo_floor = min(0.15, self.det_thresh * 0.5)
349
+ low_keep = [i for i in low_indices.tolist() if raw_scores[i] >= dlo_floor]
350
+ if active_conf and low_keep:
351
+ low_dets = [detections[i] for i in low_keep]
352
+ low_scores = raw_scores[low_keep]
353
+ low_matches = self._associate_low(active_conf, low_dets, low_scores)
354
+ for di, ti in low_matches:
355
+ _apply_match(
356
+ active_conf[ti], low_dets[di], float(low_scores[di]), blend_emb=False
357
+ )
358
+ used_low.add(low_keep[di])
359
+ recent_lost = [
360
+ confirmed[ti]
361
+ for ti in u_conf
362
+ if confirmed[ti].uid not in matched_uids
363
+ and 2 <= confirmed[ti].time_since_update <= 3
364
+ ]
365
+ rec_keep = [
366
+ i for i in low_indices.tolist() if i not in used_low and raw_scores[i] >= 0.30
367
+ ]
368
+ if recent_lost and rec_keep:
369
+ rec_dets = [detections[i] for i in rec_keep]
370
+ rec_scores = raw_scores[rec_keep]
371
+ rec_boxes = _boxes(rec_dets)
372
+ lost_boxes = np.array([t.motion.box for t in recent_lost], dtype=np.float64)
373
+ rec_iou = compute_iou_matrix(rec_boxes, lost_boxes)
374
+ rec_mhd = self._mahalanobis(rec_dets, recent_lost)
375
+ rec_valid = (rec_iou >= 0.50) & (rec_mhd <= _MAHALANOBIS_LIMIT)
376
+ rec_sim = (
377
+ rec_iou
378
+ + self.lambda_mhd * _mahalanobis_similarity(rec_mhd)
379
+ + self.lambda_shape
380
+ * rec_scores[:, None]
381
+ * _shape_similarity(rec_boxes, lost_boxes)
382
+ )
383
+ rec_matches, _, _ = _assign(rec_sim, rec_valid)
384
+ for di, ti in rec_matches:
385
+ _apply_match(
386
+ recent_lost[ti], rec_dets[di], float(rec_scores[di]), blend_emb=False
387
+ )
388
+ used_low.add(rec_keep[di])
389
+
390
+ # Stage 3: match unconfirmed tracks with leftover high-score detections.
391
+ rem_high_dets = [high_dets[di] for di in u_det]
392
+ rem_high_scores = high_scores[u_det] if u_det else np.empty(0, dtype=np.float64)
393
+ unconf_tconf = np.array([self._track_confidence(t) for t in unconfirmed], dtype=np.float64)
394
+ un_matches, u_rem_det, u_unconf = self._associate(
395
+ unconfirmed, rem_high_dets, rem_high_scores, unconf_tconf
396
+ )
397
+ for di, ti in un_matches:
398
+ _apply_match(
399
+ unconfirmed[ti], rem_high_dets[di], float(rem_high_scores[di]), blend_emb=True
400
+ )
401
+
402
+ # When DUO boost is enabled, let DUO-spawned unconfirmed tracks continue on low-score hits.
403
+ if self.duo_boost and self.dlo_boost and u_unconf and low_indices.size:
404
+ rem_unconf = [
405
+ unconfirmed[ti] for ti in u_unconf if unconfirmed[ti].time_since_update == 1
406
+ ]
407
+ dlo_floor = min(0.15, self.det_thresh * 0.5)
408
+ low_keep = [
409
+ i for i in low_indices.tolist() if i not in used_low and raw_scores[i] >= dlo_floor
410
+ ]
411
+ if rem_unconf and low_keep:
412
+ low_dets = [detections[i] for i in low_keep]
413
+ low_scores = raw_scores[low_keep]
414
+ for di, ti in self._associate_low(rem_unconf, low_dets, low_scores):
415
+ _apply_match(
416
+ rem_unconf[ti], low_dets[di], float(low_scores[di]), blend_emb=False
417
+ )
418
+
419
+ # Prune unconfirmed tracks that missed so 1-frame ghosts never linger as zombies.
420
+ self._tracks = [t for t in self._tracks if t.track_id > 0 or t.uid in matched_uids]
421
+
422
+ # Spawn new tracks from leftover high-score detections above new_track_thresh (or DUO-promoted).
423
+ leftovers = sorted(
424
+ (u_det[i] for i in u_rem_det), key=lambda di: float(high_scores[di]), reverse=True
425
+ )
426
+ for di in leftovers:
427
+ det = high_dets[di]
428
+ if not high_duo[di] and det.confidence < self.new_track_thresh:
429
+ continue
430
+ same_class = updated_boxes.get(det.class_id)
431
+ if (
432
+ same_class
433
+ and float(compute_ioa_matrix(_boxes([det]), np.array(same_class)).max()) >= 0.8
434
+ ):
435
+ continue
436
+ tr = self._spawn(det, XywhKalmanFilter(det.bbox, height_scaled=True, min_nsa=0.03))
437
+ tr.blend_embedding(det.embedding, alpha=0.0)
438
+ updated_boxes.setdefault(det.class_id, []).append(det.bbox)
439
+ self._remove_duplicates()
440
+ return self._finish_frame(events)