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