trackflow-python-cuda 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.
trackflow/tracker.py ADDED
@@ -0,0 +1,1219 @@
1
+ """Pure NumPy/SciPy multi-object trackers with Kalman filtering & CMC.
2
+
3
+ This module holds ByteTrack, BoT-SORT, the track lifecycle shared by the SORT-style trackers in
4
+ :mod:`trackflow.ocsort` and :mod:`trackflow.boosttrack`, and :func:`create_tracker`.
5
+
6
+ ``web/tracker.js`` is a direct port of :class:`ByteTracker` for the browser playground. Keep the
7
+ two in sync: ``tests/test_web_parity.py`` replays the same recorded detections through both and
8
+ requires identical IDs and boxes.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import math
14
+ from collections import defaultdict
15
+ from dataclasses import dataclass, field
16
+ from dataclasses import fields as dataclass_fields
17
+ from typing import Any, Protocol
18
+
19
+ import cv2
20
+ import numpy as np
21
+ from scipy.optimize import linear_sum_assignment
22
+
23
+ from trackflow.types import Detection, Track
24
+
25
+
26
+ class Tracker(Protocol):
27
+ """A stateful per-source tracker. Return the observations for the current frame."""
28
+
29
+ def update(
30
+ self, detections: list[Detection], frame_bgr: np.ndarray | None = None
31
+ ) -> list[Track]: ...
32
+
33
+
34
+ def compute_iou_matrix(boxes_a: np.ndarray, boxes_b: np.ndarray) -> np.ndarray:
35
+ """Compute pairwise IoU matrix between two [N, 4] and [M, 4] xyxy arrays (float64)."""
36
+ boxes_a = np.asarray(boxes_a, dtype=np.float64).reshape(-1, 4)
37
+ boxes_b = np.asarray(boxes_b, dtype=np.float64).reshape(-1, 4)
38
+ if len(boxes_a) == 0 or len(boxes_b) == 0:
39
+ return np.zeros((len(boxes_a), len(boxes_b)), dtype=np.float64)
40
+
41
+ ax1, ay1, ax2, ay2 = np.split(boxes_a, 4, axis=1)
42
+ bx1, by1, bx2, by2 = np.split(boxes_b, 4, axis=1)
43
+
44
+ inter_w = np.maximum(0.0, np.minimum(ax2, bx2.T) - np.maximum(ax1, bx1.T))
45
+ inter_h = np.maximum(0.0, np.minimum(ay2, by2.T) - np.maximum(ay1, by1.T))
46
+ inter_area = inter_w * inter_h
47
+
48
+ area_a = np.maximum(0.0, ax2 - ax1) * np.maximum(0.0, ay2 - ay1)
49
+ area_b = np.maximum(0.0, bx2 - bx1) * np.maximum(0.0, by2 - by1)
50
+ union = np.maximum(area_a + area_b.T - inter_area, 1e-6)
51
+ return inter_area / union
52
+
53
+
54
+ def compute_ioa_matrix(boxes_a: np.ndarray, boxes_b: np.ndarray) -> np.ndarray:
55
+ """Fraction of each box in ``boxes_a`` covered by each box in ``boxes_b`` (intersection / area_a)."""
56
+ boxes_a = np.asarray(boxes_a, dtype=np.float64).reshape(-1, 4)
57
+ boxes_b = np.asarray(boxes_b, dtype=np.float64).reshape(-1, 4)
58
+ if len(boxes_a) == 0 or len(boxes_b) == 0:
59
+ return np.zeros((len(boxes_a), len(boxes_b)), dtype=np.float64)
60
+
61
+ ax1, ay1, ax2, ay2 = np.split(boxes_a, 4, axis=1)
62
+ bx1, by1, bx2, by2 = np.split(boxes_b, 4, axis=1)
63
+ inter_w = np.maximum(0.0, np.minimum(ax2, bx2.T) - np.maximum(ax1, bx1.T))
64
+ inter_h = np.maximum(0.0, np.minimum(ay2, by2.T) - np.maximum(ay1, by1.T))
65
+ area_a = np.maximum(np.maximum(0.0, ax2 - ax1) * np.maximum(0.0, ay2 - ay1), 1e-6)
66
+ return (inter_w * inter_h) / area_a
67
+
68
+
69
+ def _xyxy_to_xyah(bbox: tuple[float, float, float, float]) -> np.ndarray:
70
+ x1, y1, x2, y2 = bbox
71
+ w = max(1.0, x2 - x1)
72
+ h = max(1.0, y2 - y1)
73
+ cx = x1 + 0.5 * w
74
+ cy = y1 + 0.5 * h
75
+ a = w / h
76
+ return np.array([cx, cy, a, h], dtype=np.float64)
77
+
78
+
79
+ def _xyah_to_xyxy(xyah: np.ndarray) -> tuple[float, float, float, float]:
80
+ cx, cy, a, h = (
81
+ float(xyah[0]),
82
+ float(xyah[1]),
83
+ max(0.05, float(xyah[2])),
84
+ max(1.0, float(xyah[3])),
85
+ )
86
+ w = a * h
87
+ return (cx - 0.5 * w, cy - 0.5 * h, cx + 0.5 * w, cy + 0.5 * h)
88
+
89
+
90
+ class KalmanBoxFilter:
91
+ """8-state constant-velocity Kalman filter for bounding boxes: [cx, cy, a, h, vx, vy, va, vh]."""
92
+
93
+ def __init__(self, initial_bbox: tuple[float, float, float, float]) -> None:
94
+ self._F = np.eye(8, dtype=np.float64)
95
+ for i in range(4):
96
+ self._F[i, i + 4] = 1.0
97
+ self._H = np.eye(4, 8, dtype=np.float64)
98
+
99
+ self._std_pos = 1.0 / 20.0
100
+ self._std_vel = 1.0 / 160.0
101
+
102
+ meas = _xyxy_to_xyah(initial_bbox)
103
+ self.mean = np.zeros(8, dtype=np.float64)
104
+ self.mean[:4] = meas
105
+
106
+ h = max(10.0, meas[3])
107
+ std = np.array(
108
+ [
109
+ 2 * self._std_pos * h,
110
+ 2 * self._std_pos * h,
111
+ 1e-2,
112
+ 2 * self._std_pos * h,
113
+ 10 * self._std_vel * h,
114
+ 10 * self._std_vel * h,
115
+ 1e-5,
116
+ 10 * self._std_vel * h,
117
+ ],
118
+ dtype=np.float64,
119
+ )
120
+ self.cov = np.diag(std**2)
121
+
122
+ def predict(self) -> tuple[float, float, float, float]:
123
+ h = max(10.0, float(self.mean[3]))
124
+ std = np.array(
125
+ [
126
+ self._std_pos * h,
127
+ self._std_pos * h,
128
+ 1e-2,
129
+ self._std_pos * h,
130
+ self._std_vel * h,
131
+ self._std_vel * h,
132
+ 1e-5,
133
+ self._std_vel * h,
134
+ ],
135
+ dtype=np.float64,
136
+ )
137
+ q = np.diag(std**2)
138
+ self.mean = self._F @ self.mean
139
+ if self.mean[3] < 1.0:
140
+ self.mean[3] = 1.0
141
+ self.mean[7] = 0.0
142
+ self.cov = self._F @ self.cov @ self._F.T + q
143
+ return _xyah_to_xyxy(self.mean[:4])
144
+
145
+ def update(self, bbox: tuple[float, float, float, float]) -> tuple[float, float, float, float]:
146
+ meas = _xyxy_to_xyah(bbox)
147
+ h = max(10.0, float(self.mean[3]))
148
+ r = np.diag(
149
+ np.array(
150
+ [self._std_pos * h, self._std_pos * h, 1e-1, self._std_pos * h], dtype=np.float64
151
+ )
152
+ ** 2
153
+ )
154
+ proj_mean = self._H @ self.mean
155
+ proj_cov = self._H @ self.cov @ self._H.T + r
156
+ kalman_gain = np.linalg.solve(proj_cov, self._H @ self.cov).T
157
+ innovation = meas - proj_mean
158
+ self.mean = self.mean + kalman_gain @ innovation
159
+ self.cov = self.cov - kalman_gain @ proj_cov @ kalman_gain.T
160
+ return _xyah_to_xyxy(self.mean[:4])
161
+
162
+ def apply_camera_warp(self, warp_2x3: np.ndarray) -> None:
163
+ """Apply a 2x3 affine camera motion transform to the predicted center & velocity."""
164
+ rot_scale = warp_2x3[:2, :2]
165
+ trans = warp_2x3[:2, 2]
166
+ self.mean[:2] = rot_scale @ self.mean[:2] + trans
167
+ self.mean[4:6] = rot_scale @ self.mean[4:6]
168
+
169
+
170
+ @dataclass
171
+ class _TrackState:
172
+ uid: int # internal handle, assigned at spawn
173
+ kf: KalmanBoxFilter
174
+ confidence: float
175
+ class_id: int
176
+ class_name: str
177
+ start_frame: int
178
+ track_id: int = 0 # public ID, assigned only once the track is confirmed
179
+ is_activated: bool = False
180
+ age: int = 1
181
+ hits: int = 1
182
+ time_since_update: int = 0
183
+ state: str = "tracked" # tracked | lost
184
+ recovered_now: bool = False
185
+ embedding: np.ndarray | None = field(default=None, repr=False)
186
+
187
+ @property
188
+ def bbox(self) -> tuple[float, float, float, float]:
189
+ return _xyah_to_xyxy(self.kf.mean[:4])
190
+
191
+ def update_embedding(self, emb: np.ndarray | None, alpha: float = 0.9) -> None:
192
+ if emb is None:
193
+ return
194
+ norm = float(np.linalg.norm(emb))
195
+ if norm <= 1e-6:
196
+ return
197
+ unit = emb / norm
198
+ if self.embedding is None:
199
+ self.embedding = unit
200
+ else:
201
+ blended = alpha * self.embedding + (1.0 - alpha) * unit
202
+ bnorm = float(np.linalg.norm(blended))
203
+ self.embedding = blended / max(bnorm, 1e-6)
204
+
205
+ def to_track(self, *, coasting: bool = False) -> Track:
206
+ return Track(
207
+ track_id=self.track_id,
208
+ bbox=self.bbox,
209
+ confidence=self.confidence,
210
+ class_id=self.class_id,
211
+ class_name=self.class_name,
212
+ age=self.age,
213
+ hits=self.hits,
214
+ recovered=self.recovered_now and not coasting,
215
+ coasting=coasting,
216
+ )
217
+
218
+
219
+ class SparseOpticalFlowCMC:
220
+ """Sparse optical-flow camera motion estimate from background corners (BoT-SORT style).
221
+
222
+ Corners are only taken from the background: ``exclude_boxes`` (the objects being tracked) and
223
+ a thin frame border are masked out, so a crowd moving together can't pass for camera motion.
224
+ The estimate falls back to "no camera motion" (``None``) when too few background corners
225
+ survive, when RANSAC keeps too small a share of them, or when the warp is implausible for one
226
+ frame step. ``drop_foreground_flow`` also discards corners whose flow lands inside this
227
+ frame's ``exclude_boxes``.
228
+ """
229
+
230
+ def __init__(self, downscale: int = 2, *, drop_foreground_flow: bool = True) -> None:
231
+ self.downscale = max(1, int(downscale))
232
+ self.drop_foreground_flow = drop_foreground_flow
233
+ self._prev_gray: np.ndarray | None = None
234
+ self._prev_pts: np.ndarray | None = None
235
+
236
+ def _background_mask(self, gray: np.ndarray, boxes: np.ndarray) -> np.ndarray:
237
+ h, w = gray.shape[:2]
238
+ mask = np.zeros((h, w), dtype=np.uint8)
239
+ bh, bw = max(1, int(0.02 * h)), max(1, int(0.02 * w))
240
+ mask[bh : h - bh, bw : w - bw] = 255
241
+ if len(boxes):
242
+ b = np.round(np.asarray(boxes, dtype=np.float64) / self.downscale).astype(np.int64)
243
+ b[:, [0, 2]] = np.clip(b[:, [0, 2]], 0, w)
244
+ b[:, [1, 3]] = np.clip(b[:, [1, 3]], 0, h)
245
+ for x1, y1, x2, y2 in b.tolist():
246
+ mask[y1:y2, x1:x2] = 0
247
+ return mask
248
+
249
+ def estimate(
250
+ self, frame_bgr: np.ndarray | None, exclude_boxes: np.ndarray | None = None
251
+ ) -> np.ndarray | None:
252
+ """2x3 affine warp from the previous frame to ``frame_bgr``, or ``None``."""
253
+ if frame_bgr is None:
254
+ return None
255
+ gray = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2GRAY)
256
+ if self.downscale > 1:
257
+ h, w = gray.shape[:2]
258
+ gray = cv2.resize(gray, (max(32, w // self.downscale), max(32, h // self.downscale)))
259
+ mask = self._background_mask(
260
+ gray, np.zeros((0, 4)) if exclude_boxes is None else exclude_boxes
261
+ )
262
+ has_bg = cv2.countNonZero(mask) >= 0.1 * mask.size
263
+ pts = (
264
+ cv2.goodFeaturesToTrack(
265
+ gray, maxCorners=1000, qualityLevel=0.01, minDistance=1, blockSize=3, mask=mask
266
+ )
267
+ if has_bg
268
+ else None
269
+ )
270
+
271
+ warp: np.ndarray | None = None
272
+ if (
273
+ has_bg
274
+ and self._prev_gray is not None
275
+ and self._prev_gray.shape == gray.shape
276
+ and self._prev_pts is not None
277
+ and len(self._prev_pts) >= 10
278
+ ):
279
+ curr_pts, status, _ = cv2.calcOpticalFlowPyrLK(
280
+ self._prev_gray, gray, self._prev_pts, None
281
+ )
282
+ if curr_pts is not None and status is not None:
283
+ valid = status.ravel() == 1
284
+ p0, p1 = self._prev_pts[valid].reshape(-1, 2), curr_pts[valid].reshape(-1, 2)
285
+ gh, gw = gray.shape[:2]
286
+ if self.drop_foreground_flow:
287
+ x, y = np.rint(p1).astype(np.int64).T
288
+ inside = (x >= 0) & (x < gw) & (y >= 0) & (y < gh)
289
+ in_bg = inside & (mask[np.clip(y, 0, gh - 1), np.clip(x, 0, gw - 1)] > 0)
290
+ p0, p1 = p0[in_bg], p1[in_bg]
291
+ if len(p0) >= 10:
292
+ mat, inliers = cv2.estimateAffinePartial2D(p0, p1, method=cv2.RANSAC)
293
+ if mat is not None and inliers is not None:
294
+ warp = self._checked(
295
+ mat.astype(np.float64), inliers.sum() / len(p0), gh, gw
296
+ )
297
+
298
+ self._prev_gray = gray
299
+ self._prev_pts = pts
300
+ return warp
301
+
302
+ def _checked(self, mat: np.ndarray, inlier_ratio: float, h: int, w: int) -> np.ndarray | None:
303
+ if not np.isfinite(mat).all() or inlier_ratio < 0.5:
304
+ return None
305
+ scale = float(np.sqrt(abs(np.linalg.det(mat[:, :2]))))
306
+ if not 0.9 <= scale <= 1.1 or np.abs(mat[:, 2]).max() > 0.15 * max(h, w):
307
+ return None
308
+ mat[:2, 2] *= float(self.downscale)
309
+ return mat
310
+
311
+
312
+ def compute_hmiou_matrix(
313
+ boxes_a: np.ndarray, boxes_b: np.ndarray, iou: np.ndarray | None = None
314
+ ) -> np.ndarray:
315
+ """Height-modulated IoU (Hybrid-SORT): ``iou * (0.75 + 0.25 * vertical IoU)``.
316
+
317
+ The vertical overlap separates people who cross at different depths in the image. ``iou``
318
+ defaults to the plain IoU of the boxes; pass a soft or buffered IoU of the same pairs to
319
+ modulate that instead.
320
+ """
321
+ a = np.asarray(boxes_a, dtype=np.float64).reshape(-1, 4)
322
+ b = np.asarray(boxes_b, dtype=np.float64).reshape(-1, 4)
323
+ if iou is None:
324
+ iou = compute_iou_matrix(a, b)
325
+ inter = np.minimum(a[:, None, 3], b[None, :, 3]) - np.maximum(a[:, None, 1], b[None, :, 1])
326
+ union = np.maximum(a[:, None, 3], b[None, :, 3]) - np.minimum(a[:, None, 1], b[None, :, 1])
327
+ return iou * (0.75 + 0.25 * np.maximum(inter, 0.0) / np.maximum(union, 1e-6))
328
+
329
+
330
+ def _linear_assignment(
331
+ cost_matrix: np.ndarray,
332
+ max_cost: float,
333
+ ) -> tuple[list[tuple[int, int]], list[int], list[int]]:
334
+ n_rows, n_cols = cost_matrix.shape
335
+ if n_rows == 0 or n_cols == 0:
336
+ return [], list(range(n_rows)), list(range(n_cols))
337
+
338
+ # Cost-limited linear assignment. Each row can take a dummy at the cutoff; a
339
+ # marginal pairing need not displace a strong one just to fill the matrix.
340
+ transpose = n_rows > n_cols
341
+ cost = cost_matrix.T if transpose else cost_matrix
342
+ dummy = np.full((cost.shape[0], cost.shape[0]), np.nextafter(max_cost, np.inf))
343
+ rows, cols = linear_sum_assignment(np.column_stack((cost, dummy)))
344
+ matches: list[tuple[int, int]] = []
345
+ matched_rows: set[int] = set()
346
+ matched_cols: set[int] = set()
347
+
348
+ for row, col in zip(rows.tolist(), cols.tolist(), strict=True):
349
+ if col >= cost.shape[1]:
350
+ continue
351
+ r, c = (col, row) if transpose else (row, col)
352
+ if cost_matrix[r, c] <= max_cost:
353
+ matches.append((r, c))
354
+ matched_rows.add(r)
355
+ matched_cols.add(c)
356
+
357
+ unmatched_rows = [r for r in range(n_rows) if r not in matched_rows]
358
+ unmatched_cols = [c for c in range(n_cols) if c not in matched_cols]
359
+ return matches, unmatched_rows, unmatched_cols
360
+
361
+
362
+ def _boxes(items: list[Any]) -> np.ndarray:
363
+ return np.array([it.bbox for it in items], dtype=np.float64).reshape(-1, 4)
364
+
365
+
366
+ def _expand_boxes(boxes: np.ndarray, scale: float) -> np.ndarray:
367
+ """Grow each xyxy box by ``scale`` x its width/height on every side (buffered IoU)."""
368
+ if scale <= 0.0:
369
+ return boxes
370
+ w = boxes[:, 2] - boxes[:, 0]
371
+ h = boxes[:, 3] - boxes[:, 1]
372
+ return np.stack(
373
+ [
374
+ boxes[:, 0] - scale * w,
375
+ boxes[:, 1] - scale * h,
376
+ boxes[:, 2] + scale * w,
377
+ boxes[:, 3] + scale * h,
378
+ ],
379
+ axis=1,
380
+ )
381
+
382
+
383
+ def _switch_event(
384
+ new_id: int, box: tuple[float, float, float, float], recently_lost: list[tuple[int, Any]]
385
+ ) -> dict[str, Any] | None:
386
+ """Flag a possible ID switch when a new ID appears where another ID was just lost."""
387
+ if not recently_lost:
388
+ return None
389
+ ious = compute_iou_matrix(np.array([box]), np.array([b for _, b in recently_lost]))[0]
390
+ j = int(np.argmax(ious))
391
+ if float(ious[j]) < 0.25:
392
+ return None
393
+ return {
394
+ "type": "possible_id_switch",
395
+ "new_track_id": new_id,
396
+ "previous_track_id": recently_lost[j][0],
397
+ "iou": round(float(ious[j]), 3),
398
+ }
399
+
400
+
401
+ def iou_buffer_for_interval(dt_s: float) -> float:
402
+ """Buffered-IoU scale for a given time between processed frames.
403
+
404
+ Pedestrians move a roughly fixed fraction of their own size per second, so when frames are
405
+ processed far apart (``--skip``, or a slow WASM browser at 2-4 FPS) consecutive boxes of the
406
+ same person stop overlapping and plain IoU fragments IDs. Growing the boxes before computing
407
+ IoU (C-BIoU, Yang et al. WACV 2023) restores the overlap. Calibrated on vtest.avi: no buffer at
408
+ <= 0.1 s (it only adds swaps there), 0.3 at 0.3 s, capped at 0.5.
409
+ """
410
+ return float(min(0.5, max(0.0, 1.5 * (dt_s - 0.1))))
411
+
412
+
413
+ class ByteTracker:
414
+ """ByteTrack multi-object tracker (Zhang et al., ECCV 2022) with diagnostic event reporting.
415
+
416
+ Follows the reference association order:
417
+
418
+ 1. confirmed + lost tracks <-> high-score detections (IoU, optionally buffered)
419
+ 2. remaining tracked tracks <-> low-score detections (IoU)
420
+ 3. unconfirmed tracks <-> remaining high-score detections (IoU, optionally buffered);
421
+ unmatched ones are dropped
422
+ 4. new *unconfirmed* tracks from leftover high-score detections. A track only gets a public
423
+ ID (and is only output) once a second detection confirms it, so one-frame false positives
424
+ never show up as IDs. Detections mostly covered by a track already updated this frame
425
+ (``spawn_overlap_thresh``, intersection over detection area) don't start new tracks, which
426
+ stops partial-body duplicate boxes from spawning ghost IDs.
427
+ 5. tracked/lost tracks overlapping by IoU > ``duplicate_iou`` are de-duplicated (older wins).
428
+ """
429
+
430
+ name: str = "bytetrack"
431
+ # Minimum detection confidence for which the pipeline computes person Re-ID embeddings;
432
+ # None when the tracker doesn't use appearance.
433
+ embedding_min_confidence: float | None = None
434
+
435
+ def __init__(
436
+ self,
437
+ *,
438
+ track_high_thresh: float = 0.5,
439
+ track_low_thresh: float = 0.15,
440
+ new_track_thresh: float = 0.55,
441
+ match_thresh: float = 0.8,
442
+ second_match_thresh: float = 0.5,
443
+ unconfirmed_match_thresh: float = 0.7,
444
+ track_buffer: int = 30,
445
+ spawn_overlap_thresh: float = 0.8,
446
+ duplicate_iou: float = 0.85,
447
+ iou_buffer: float = 0.0,
448
+ ) -> None:
449
+ self.track_high_thresh = float(track_high_thresh)
450
+ self.track_low_thresh = float(track_low_thresh)
451
+ self.new_track_thresh = float(new_track_thresh)
452
+ self.match_thresh = float(match_thresh)
453
+ self.second_match_thresh = float(second_match_thresh)
454
+ self.unconfirmed_match_thresh = float(unconfirmed_match_thresh)
455
+ self.track_buffer = int(track_buffer)
456
+ self.spawn_overlap_thresh = float(spawn_overlap_thresh)
457
+ self.duplicate_iou = float(duplicate_iou)
458
+ # Buffered IoU for high-score association (see iou_buffer_for_interval); may be changed
459
+ # between updates when the processing rate changes.
460
+ self.iou_buffer = float(iou_buffer)
461
+
462
+ self._next_id = 1
463
+ self._next_uid = 1
464
+ self._frame_id = 0
465
+ self._tracks: list[_TrackState] = []
466
+ self.last_events: list[dict[str, Any]] = []
467
+
468
+ def reset(self) -> None:
469
+ self._next_id = 1
470
+ self._next_uid = 1
471
+ self._frame_id = 0
472
+ self._tracks.clear()
473
+ self.last_events = []
474
+
475
+ def _compute_first_stage_cost(
476
+ self,
477
+ pool: list[_TrackState],
478
+ dets: list[Detection],
479
+ ) -> np.ndarray:
480
+ return 1.0 - compute_iou_matrix(
481
+ _expand_boxes(_boxes(pool), self.iou_buffer),
482
+ _expand_boxes(_boxes(dets), self.iou_buffer),
483
+ )
484
+
485
+ def _apply_cmc(self, frame_bgr: np.ndarray | None) -> None:
486
+ """No-op in ByteTrack; overridden by BoT-SORT."""
487
+ _ = frame_bgr
488
+
489
+ def _associate(
490
+ self,
491
+ tracks: list[_TrackState],
492
+ dets: list[Detection],
493
+ max_cost: float,
494
+ *,
495
+ low: bool = False,
496
+ ) -> tuple[list[tuple[int, int]], list[int], list[int]]:
497
+ if not tracks or not dets:
498
+ return [], list(range(len(tracks))), list(range(len(dets)))
499
+ if low:
500
+ cost = 1.0 - compute_iou_matrix(_boxes(tracks), _boxes(dets))
501
+ else:
502
+ cost = self._compute_first_stage_cost(tracks, dets)
503
+ different_class = np.not_equal.outer(
504
+ [t.class_id for t in tracks], [d.class_id for d in dets]
505
+ )
506
+ cost[different_class] = np.inf
507
+ return _linear_assignment(cost, max_cost)
508
+
509
+ def _activate(self, tr: _TrackState, events: list[dict[str, Any]]) -> None:
510
+ tr.is_activated = True
511
+ tr.track_id = self._next_id
512
+ self._next_id += 1
513
+ events.append({"type": "track_started", "track_id": tr.track_id})
514
+ switch = _switch_event(
515
+ tr.track_id,
516
+ tr.bbox,
517
+ [
518
+ (t.track_id, t.bbox)
519
+ for t in self._tracks
520
+ if t.state == "lost"
521
+ and t.class_id == tr.class_id
522
+ and t.is_activated
523
+ and t.time_since_update <= 5
524
+ ],
525
+ )
526
+ if switch is not None:
527
+ events.append(switch)
528
+
529
+ @staticmethod
530
+ def _apply_detection(tr: _TrackState, det: Detection, *, update_class: bool) -> None:
531
+ tr.kf.update(det.bbox)
532
+ tr.confidence = det.confidence
533
+ if update_class:
534
+ tr.class_id = det.class_id
535
+ tr.class_name = det.class_name
536
+ tr.hits += 1
537
+ tr.time_since_update = 0
538
+ tr.update_embedding(det.embedding)
539
+
540
+ def update(
541
+ self,
542
+ detections: list[Detection],
543
+ frame_bgr: np.ndarray | None = None,
544
+ ) -> list[Track]:
545
+ """Advance the tracker by one frame and return the confirmed tracks observed this frame."""
546
+ self._frame_id += 1
547
+ events: list[dict[str, Any]] = []
548
+
549
+ # 1. Predict every track (lost tracks keep position velocity but stop growing/shrinking).
550
+ for t in self._tracks:
551
+ t.recovered_now = False
552
+ if t.state != "tracked":
553
+ t.kf.mean[7] = 0.0
554
+ t.kf.predict()
555
+ t.age += 1
556
+ t.time_since_update += 1
557
+
558
+ # Optional camera motion compensation (active in BoT-SORT)
559
+ self._apply_cmc(frame_bgr)
560
+
561
+ high_dets = [d for d in detections if d.confidence >= self.track_high_thresh]
562
+ low_dets = [
563
+ d for d in detections if self.track_low_thresh <= d.confidence < self.track_high_thresh
564
+ ]
565
+
566
+ confirmed = [t for t in self._tracks if t.is_activated and t.state == "tracked"]
567
+ lost = [t for t in self._tracks if t.state == "lost"]
568
+ unconfirmed = [t for t in self._tracks if not t.is_activated]
569
+ pool = confirmed + lost
570
+ updated: set[int] = set()
571
+
572
+ # 2. First association: confirmed + lost tracks with high-score detections.
573
+ matches, u_pool, u_high = self._associate(pool, high_dets, self.match_thresh)
574
+ for ti, di in matches:
575
+ tr = pool[ti]
576
+ if tr.state == "lost":
577
+ tr.recovered_now = True
578
+ events.append({"type": "track_recovered", "track_id": tr.track_id})
579
+ tr.state = "tracked"
580
+ self._apply_detection(tr, high_dets[di], update_class=True)
581
+ updated.add(tr.uid)
582
+
583
+ # 3. Second association: remaining *tracked* tracks with low-score detections (IoU only).
584
+ rem_tracked = [pool[i] for i in u_pool if pool[i].state == "tracked"]
585
+ if rem_tracked and low_dets:
586
+ low_matches, _, _ = self._associate(
587
+ rem_tracked, low_dets, self.second_match_thresh, low=True
588
+ )
589
+ for ti, di in low_matches:
590
+ self._apply_detection(rem_tracked[ti], low_dets[di], update_class=False)
591
+ updated.add(rem_tracked[ti].uid)
592
+
593
+ # 4. Unconfirmed tracks with the high-score detections left over from stage 1.
594
+ rem_high = [high_dets[i] for i in u_high]
595
+ un_matches, _, u_rem = self._associate(unconfirmed, rem_high, self.unconfirmed_match_thresh)
596
+ for ti, di in un_matches:
597
+ tr = unconfirmed[ti]
598
+ self._apply_detection(tr, rem_high[di], update_class=True)
599
+ updated.add(tr.uid)
600
+ self._activate(tr, events)
601
+
602
+ # 5. Lost-state transitions, expiry, and removal of unconfirmed tracks that missed.
603
+ surviving: list[_TrackState] = []
604
+ for tr in self._tracks:
605
+ if tr.uid in updated:
606
+ surviving.append(tr)
607
+ continue
608
+ if not tr.is_activated:
609
+ continue # unconfirmed and unmatched -> removed
610
+ if tr.state == "tracked":
611
+ tr.state = "lost"
612
+ events.append({"type": "track_lost", "track_id": tr.track_id})
613
+ if tr.time_since_update <= self.track_buffer:
614
+ surviving.append(tr)
615
+ else:
616
+ events.append({"type": "track_ended", "track_id": tr.track_id})
617
+ self._tracks = surviving
618
+
619
+ # 6. Spawn new (unconfirmed) tracks from leftover high-score detections.
620
+ occupied: dict[int, list[tuple[float, float, float, float]]] = defaultdict(list)
621
+ for t in self._tracks:
622
+ if t.uid in updated:
623
+ occupied[t.class_id].append(t.bbox)
624
+ leftovers = sorted((rem_high[i] for i in u_rem), key=lambda d: d.confidence, reverse=True)
625
+ for det in leftovers:
626
+ if det.confidence < self.new_track_thresh:
627
+ continue
628
+ same_class = occupied[det.class_id]
629
+ if same_class and (
630
+ float(compute_ioa_matrix(_boxes([det]), np.array(same_class)).max())
631
+ >= self.spawn_overlap_thresh
632
+ ):
633
+ continue
634
+ tr = _TrackState(
635
+ uid=self._next_uid,
636
+ kf=KalmanBoxFilter(det.bbox),
637
+ confidence=det.confidence,
638
+ class_id=det.class_id,
639
+ class_name=det.class_name,
640
+ start_frame=self._frame_id,
641
+ )
642
+ self._next_uid += 1
643
+ tr.update_embedding(det.embedding)
644
+ self._tracks.append(tr)
645
+ updated.add(tr.uid)
646
+ same_class.append(tr.bbox)
647
+ if self._frame_id == 1:
648
+ self._activate(tr, events)
649
+
650
+ # 7. Remove tracked/lost duplicates (the longer-lived track wins).
651
+ self._remove_duplicates()
652
+
653
+ self.last_events = events
654
+ outputs = [t.to_track() for t in self._tracks if t.is_activated and t.uid in updated]
655
+ outputs.sort(key=lambda t: t.track_id)
656
+ return outputs
657
+
658
+ def _remove_duplicates(self) -> None:
659
+ tracked = [t for t in self._tracks if t.state == "tracked"]
660
+ lost = [t for t in self._tracks if t.state == "lost"]
661
+ if not tracked or not lost:
662
+ return
663
+ iou = compute_iou_matrix(_boxes(tracked), _boxes(lost))
664
+ drop: set[int] = set()
665
+ for p, q in zip(*np.where(iou > self.duplicate_iou), strict=False):
666
+ a, b = tracked[int(p)], lost[int(q)]
667
+ if a.class_id != b.class_id:
668
+ continue
669
+ if (self._frame_id - a.start_frame) > (self._frame_id - b.start_frame):
670
+ drop.add(b.uid)
671
+ else:
672
+ drop.add(a.uid)
673
+ if drop:
674
+ self._tracks = [t for t in self._tracks if t.uid not in drop]
675
+
676
+ def coasting_tracks(self, max_frames: int = 3) -> list[Track]:
677
+ """Confirmed tracks missed for at most ``max_frames`` frames, at their predicted position.
678
+
679
+ Useful for display and anonymization so boxes don't blink when the detector misses a
680
+ frame. These are predictions, not observations; they are never written to exports.
681
+ """
682
+ out = [
683
+ t.to_track(coasting=True)
684
+ for t in self._tracks
685
+ if t.is_activated and t.state == "lost" and t.time_since_update <= max_frames
686
+ ]
687
+ out.sort(key=lambda t: t.track_id)
688
+ return out
689
+
690
+
691
+ def _xyxy_to_xywh(bbox: tuple[float, float, float, float]) -> np.ndarray:
692
+ x1, y1, x2, y2 = bbox
693
+ w = max(1.0, x2 - x1)
694
+ h = max(1.0, y2 - y1)
695
+ return np.array([x1 + 0.5 * w, y1 + 0.5 * h, w, h], dtype=np.float64)
696
+
697
+
698
+ def _xywh_to_xyxy(xywh: np.ndarray) -> tuple[float, float, float, float]:
699
+ cx, cy = float(xywh[0]), float(xywh[1])
700
+ w, h = max(1.0, float(xywh[2])), max(1.0, float(xywh[3]))
701
+ return (cx - 0.5 * w, cy - 0.5 * h, cx + 0.5 * w, cy + 0.5 * h)
702
+
703
+
704
+ class XywhKalmanFilter:
705
+ """Constant-velocity Kalman filter on ``[cx, cy, w, h, vx, vy, vw, vh]`` (BoT-SORT state).
706
+
707
+ Tracking width directly (instead of aspect ratio) and scaling every noise term by the box's
708
+ own size gives tighter boxes for people whose silhouette changes quickly. Each measurement's
709
+ noise shrinks with detector confidence (NSA Kalman), floored at ``min_nsa``, so a confident
710
+ detection pulls the state harder than a marginal one.
711
+
712
+ By default x terms scale with the width and y terms with the height. ``height_scaled`` scales
713
+ both position terms by the height and the width terms by ``max(w, 0.35 h)``, with a 10 px
714
+ floor, which keeps thin or partly visible boxes from being trusted too much (BoostTrack++).
715
+ """
716
+
717
+ _std_pos = 1.0 / 20.0
718
+ _std_vel = 1.0 / 160.0
719
+
720
+ def __init__(
721
+ self,
722
+ initial_bbox: tuple[float, float, float, float],
723
+ *,
724
+ height_scaled: bool = False,
725
+ min_nsa: float = 0.0,
726
+ ) -> None:
727
+ self.height_scaled = height_scaled
728
+ self.min_nsa = float(min_nsa)
729
+ self.mean = np.zeros(8, dtype=np.float64)
730
+ self.mean[:4] = _xyxy_to_xywh(initial_bbox)
731
+ s = self._size_scales()
732
+ self.cov = np.diag(
733
+ np.square(np.concatenate([2 * self._std_pos * s, 10 * self._std_vel * s]))
734
+ )
735
+
736
+ @property
737
+ def box(self) -> tuple[float, float, float, float]:
738
+ return _xywh_to_xyxy(self.mean[:4])
739
+
740
+ def _size_scales(self) -> np.ndarray:
741
+ w = max(1.0, float(self.mean[2]))
742
+ h = max(1.0, float(self.mean[3]))
743
+ if self.height_scaled:
744
+ h = max(10.0, h)
745
+ return np.array([h, h, max(10.0, w, 0.35 * h), h])
746
+ return np.array([w, h, w, h])
747
+
748
+ def measurement_var(self) -> np.ndarray:
749
+ """Diagonal measurement variance before the NSA confidence factor."""
750
+ return np.square(self._std_pos * self._size_scales())
751
+
752
+ def predict(self) -> None:
753
+ w = max(1.0, float(self.mean[2]))
754
+ h = max(1.0, float(self.mean[3]))
755
+ if self.height_scaled:
756
+ h = max(10.0, h)
757
+ s0 = s1 = s3 = h
758
+ s2 = max(10.0, w, 0.35 * h)
759
+ else:
760
+ s0 = s2 = w
761
+ s1 = s3 = h
762
+ sp2 = self._std_pos * self._std_pos
763
+ sv2 = self._std_vel * self._std_vel
764
+ m = self.mean
765
+ m[:4] += m[4:]
766
+ if m[2] < 1.0:
767
+ m[2] = 1.0
768
+ m[6] = 0.0
769
+ if m[3] < 1.0:
770
+ m[3] = 1.0
771
+ m[7] = 0.0
772
+ # F @ P @ F.T for the constant-velocity F = [[I, I], [0, I]], written out blockwise.
773
+ c = self.cov
774
+ pp, pv, vv = c[:4, :4], c[:4, 4:], c[4:, 4:]
775
+ new_pv = pv + vv
776
+ c[:4, :4] = pp + pv + pv.T + vv
777
+ c[:4, 4:] = new_pv
778
+ c[4:, :4] = new_pv.T
779
+ c[0, 0] += sp2 * s0 * s0
780
+ c[1, 1] += sp2 * s1 * s1
781
+ c[2, 2] += sp2 * s2 * s2
782
+ c[3, 3] += sp2 * s3 * s3
783
+ c[4, 4] += sv2 * s0 * s0
784
+ c[5, 5] += sv2 * s1 * s1
785
+ c[6, 6] += sv2 * s2 * s2
786
+ c[7, 7] += sv2 * s3 * s3
787
+
788
+ def update(self, bbox: tuple[float, float, float, float], confidence: float = 1.0) -> None:
789
+ r = self.measurement_var() * max(self.min_nsa, 1e-4, 1.0 - float(confidence))
790
+ s = self.cov[:4, :4].copy()
791
+ s[0, 0] += r[0]
792
+ s[1, 1] += r[1]
793
+ s[2, 2] += r[2]
794
+ s[3, 3] += r[3]
795
+ gain = np.linalg.solve(s, self.cov[:, :4].T).T
796
+ x1, y1, x2, y2 = bbox
797
+ w = max(x2 - x1, 1e-3)
798
+ h = max(y2 - y1, 1e-3)
799
+ m = self.mean
800
+ innov = np.array(
801
+ [x1 + 0.5 * w - m[0], y1 + 0.5 * h - m[1], w - m[2], h - m[3]], dtype=np.float64
802
+ )
803
+ self.mean = m + gain @ innov
804
+ self.cov = self.cov - gain @ s @ gain.T
805
+ if self.mean[2] < 1.0:
806
+ self.mean[2] = 1.0
807
+ if self.mean[3] < 1.0:
808
+ self.mean[3] = 1.0
809
+
810
+ def apply_camera_warp(self, warp_2x3: np.ndarray) -> None:
811
+ """Move the state into the current frame: rotate/translate the center, rotate the
812
+ velocity, scale the box size by the warp's zoom, and transform the covariance alike."""
813
+ rot = warp_2x3[:2, :2]
814
+ det = float(rot[0, 0] * rot[1, 1] - rot[0, 1] * rot[1, 0])
815
+ scale = math.sqrt(abs(det))
816
+ m = self.mean
817
+ m[0:2] = rot @ m[0:2] + warp_2x3[:2, 2]
818
+ m[2:4] *= scale
819
+ m[4:6] = rot @ m[4:6]
820
+ m[6:8] *= scale
821
+ # Block-diagonal T = diag(rot, scale*I, rot, scale*I): compute T @ P @ T.T in two passes.
822
+ c = self.cov
823
+ tmp = np.empty_like(c)
824
+ tmp[0:2] = rot @ c[0:2]
825
+ tmp[2:4] = scale * c[2:4]
826
+ tmp[4:6] = rot @ c[4:6]
827
+ tmp[6:8] = scale * c[6:8]
828
+ rot_t = rot.T
829
+ c[:, 0:2] = tmp[:, 0:2] @ rot_t
830
+ c[:, 2:4] = tmp[:, 2:4] * scale
831
+ c[:, 4:6] = tmp[:, 4:6] @ rot_t
832
+ c[:, 6:8] = tmp[:, 6:8] * scale
833
+
834
+
835
+ @dataclass
836
+ class _BotSortTrackState(_TrackState):
837
+ kf: Any # XywhKalmanFilter
838
+
839
+ @property
840
+ def bbox(self) -> tuple[float, float, float, float]:
841
+ return _xywh_to_xyxy(self.kf.mean[:4])
842
+
843
+
844
+ class BotSortTracker(ByteTracker):
845
+ """BoT-SORT tracker: ByteTrack + camera motion compensation + appearance Re-ID fusion.
846
+
847
+ Differs from :class:`ByteTracker` in three ways:
848
+
849
+ - a Kalman filter on ``[cx, cy, w, h]`` with confidence-scaled measurement noise (see
850
+ :class:`XywhKalmanFilter`);
851
+ - camera motion estimated from background corners only (see :class:`SparseOpticalFlowCMC`),
852
+ warping each track's position, size, velocity and covariance into the current frame;
853
+ - optional appearance fusion with person Re-ID embeddings.
854
+
855
+ Appearance only helps when embeddings come from a person Re-ID model (``--reid osnet``);
856
+ CLIP/SigLIP image embeddings barely separate different people and must not be used here.
857
+ """
858
+
859
+ name: str = "botsort"
860
+
861
+ def __init__(
862
+ self,
863
+ *,
864
+ track_high_thresh: float = 0.5,
865
+ track_low_thresh: float = 0.15,
866
+ new_track_thresh: float = 0.55,
867
+ match_thresh: float = 0.8,
868
+ second_match_thresh: float = 0.5,
869
+ unconfirmed_match_thresh: float = 0.7,
870
+ track_buffer: int = 45,
871
+ spawn_overlap_thresh: float = 0.8,
872
+ iou_buffer: float = 0.0,
873
+ use_cmc: bool = True,
874
+ proximity_thresh: float = 0.5,
875
+ appearance_thresh: float = 0.25,
876
+ ) -> None:
877
+ super().__init__(
878
+ track_high_thresh=track_high_thresh,
879
+ track_low_thresh=track_low_thresh,
880
+ new_track_thresh=new_track_thresh,
881
+ match_thresh=match_thresh,
882
+ second_match_thresh=second_match_thresh,
883
+ unconfirmed_match_thresh=unconfirmed_match_thresh,
884
+ track_buffer=track_buffer,
885
+ spawn_overlap_thresh=spawn_overlap_thresh,
886
+ iou_buffer=iou_buffer,
887
+ )
888
+ self.use_cmc = use_cmc
889
+ self.proximity_thresh = float(proximity_thresh)
890
+ self.appearance_thresh = float(appearance_thresh)
891
+ self._cmc = SparseOpticalFlowCMC(drop_foreground_flow=False) if use_cmc else None
892
+ self._frame_boxes = np.zeros((0, 4), dtype=np.float64)
893
+ # Appearance is fused into the first association, which only sees high-score detections.
894
+ self.embedding_min_confidence = self.track_high_thresh
895
+
896
+ def reset(self) -> None:
897
+ super().reset()
898
+ if self.use_cmc:
899
+ self._cmc = SparseOpticalFlowCMC(drop_foreground_flow=False)
900
+
901
+ def update(
902
+ self,
903
+ detections: list[Detection],
904
+ frame_bgr: np.ndarray | None = None,
905
+ ) -> list[Track]:
906
+ self._frame_boxes = _boxes(detections)
907
+ # ByteTracker zeros mean[7] (vh) for lost tracks; XywhKalmanFilter also tracks width rate
908
+ # in mean[6]. Keep it across brief occlusions, then zero it to prevent long-gap ballooning.
909
+ for tr in self._tracks:
910
+ if (
911
+ tr.state != "tracked"
912
+ and tr.time_since_update > 5
913
+ and isinstance(tr, _BotSortTrackState)
914
+ ):
915
+ tr.kf.mean[6] = 0.0
916
+ outputs = super().update(detections, frame_bgr)
917
+ # ByteTracker spawns tracks with its own [cx, cy, a, h] filter; switch new ones to the
918
+ # BoT-SORT filter. Both start at the detection box, so this frame's outputs are unchanged.
919
+ for i, tr in enumerate(self._tracks):
920
+ if not isinstance(tr, _BotSortTrackState):
921
+ state = {f.name: getattr(tr, f.name) for f in dataclass_fields(tr)}
922
+ state["kf"] = XywhKalmanFilter(tr.bbox)
923
+ self._tracks[i] = _BotSortTrackState(**state)
924
+ return outputs
925
+
926
+ @staticmethod
927
+ def _apply_detection(tr: _TrackState, det: Detection, *, update_class: bool) -> None:
928
+ tr.kf.update(det.bbox, det.confidence)
929
+ tr.confidence = det.confidence
930
+ if update_class:
931
+ tr.class_id = det.class_id
932
+ tr.class_name = det.class_name
933
+ tr.hits += 1
934
+ tr.time_since_update = 0
935
+ tr.update_embedding(det.embedding)
936
+
937
+ def _apply_cmc(self, frame_bgr: np.ndarray | None) -> None:
938
+ if self._cmc is None or frame_bgr is None:
939
+ return
940
+ # Estimate on every frame (even with no tracks) so the reference frame never goes stale.
941
+ warp = self._cmc.estimate(frame_bgr, self._frame_boxes)
942
+ if warp is None:
943
+ return
944
+ for tr in self._tracks:
945
+ tr.kf.apply_camera_warp(warp)
946
+
947
+ def _compute_first_stage_cost(
948
+ self,
949
+ pool: list[_TrackState],
950
+ dets: list[Detection],
951
+ ) -> np.ndarray:
952
+ iou_dist = super()._compute_first_stage_cost(pool, dets)
953
+ t_has = [t.embedding is not None for t in pool]
954
+ d_has = [d.embedding is not None for d in dets]
955
+ if not any(t_has) or not any(d_has):
956
+ return iou_dist
957
+
958
+ dim = next(t.embedding for t in pool if t.embedding is not None).shape[0]
959
+ t_emb = np.zeros((len(pool), dim), dtype=np.float64)
960
+ d_emb = np.zeros((len(dets), dim), dtype=np.float64)
961
+ for i, t in enumerate(pool):
962
+ if t.embedding is not None:
963
+ t_emb[i] = t.embedding
964
+ for j, d in enumerate(dets):
965
+ if d.embedding is not None:
966
+ n = float(np.linalg.norm(d.embedding))
967
+ if n > 1e-6:
968
+ d_emb[j] = d.embedding / n
969
+
970
+ # Reference BoT-SORT fusion: cosine distance / 2, gated by appearance AND IoU proximity.
971
+ emb_dist = np.clip(0.5 * (1.0 - t_emb @ d_emb.T), 0.0, 1.0)
972
+ emb_dist[~np.array(t_has), :] = 1.0
973
+ emb_dist[:, ~np.array(d_has)] = 1.0
974
+ emb_dist[emb_dist > self.appearance_thresh] = 1.0
975
+ emb_dist[iou_dist > self.proximity_thresh] = 1.0
976
+ return np.minimum(iou_dist, emb_dist)
977
+
978
+
979
+ def _assign(
980
+ similarity: np.ndarray, valid: np.ndarray
981
+ ) -> tuple[list[tuple[int, int]], list[int], list[int]]:
982
+ """Pair rows and columns to maximize total ``similarity`` over the ``valid`` pairs only."""
983
+ cost = np.where(valid, -np.maximum(similarity, 0.0), np.inf)
984
+ return _linear_assignment(cost, 0.0)
985
+
986
+
987
+ @dataclass(eq=False)
988
+ class _SortTrack:
989
+ """One track of a SORT-style tracker.
990
+
991
+ ``motion`` is the tracker's per-track model. It provides ``predict()`` and a ``box`` property
992
+ with its current estimate, which is what coasting tracks report.
993
+ """
994
+
995
+ uid: int
996
+ motion: Any
997
+ class_id: int
998
+ class_name: str
999
+ confidence: float
1000
+ box: tuple[float, float, float, float] # reported while the track is observed
1001
+ track_id: int = 0 # public ID, assigned on confirmation
1002
+ age: int = 0 # predictions since the spawn frame
1003
+ hits: int = 1 # matched detections, counting the one that spawned the track
1004
+ hit_streak: int = 0 # consecutive matched frames after the spawn frame
1005
+ time_since_update: int = 0
1006
+ reported: bool = False # output this frame
1007
+ recovering: bool = False # confirmed, missed, matched again, not yet reported again
1008
+ recovered_now: bool = False
1009
+ embedding: np.ndarray | None = field(default=None, repr=False)
1010
+
1011
+ def to_track(self, *, coasting: bool = False) -> Track:
1012
+ return Track(
1013
+ track_id=self.track_id,
1014
+ bbox=self.motion.box if coasting else self.box,
1015
+ confidence=self.confidence,
1016
+ class_id=self.class_id,
1017
+ class_name=self.class_name,
1018
+ age=self.age + 1,
1019
+ hits=self.hits,
1020
+ recovered=self.recovered_now and not coasting,
1021
+ coasting=coasting,
1022
+ )
1023
+
1024
+ def blend_embedding(self, emb: np.ndarray | None, alpha: float) -> None:
1025
+ """Exponential moving average of unit embeddings; ``alpha`` weights the old value."""
1026
+ if emb is None:
1027
+ return
1028
+ norm = float(np.linalg.norm(emb))
1029
+ if norm <= 1e-6:
1030
+ return
1031
+ unit = np.asarray(emb, dtype=np.float64) / norm
1032
+ if self.embedding is None:
1033
+ self.embedding = unit
1034
+ return
1035
+ blended = alpha * self.embedding + (1.0 - alpha) * unit
1036
+ self.embedding = blended / max(float(np.linalg.norm(blended)), 1e-6)
1037
+
1038
+
1039
+ class _SortStyleTracker:
1040
+ """Track lifecycle shared by the SORT-style trackers (OC-SORT, BoostTrack).
1041
+
1042
+ It follows SORT's conventions. Every track is predicted each frame. A track is reported on a
1043
+ frame when that frame ends a run of ``min_hits`` consecutive matched frames; the frame that
1044
+ spawned the track doesn't count. During the first ``min_hits`` frames, a match is enough. A
1045
+ track gets its public ID the first time it is reported. After a miss it is not reported
1046
+ again until it has a new run of ``min_hits`` matches, but :meth:`coasting_tracks` still
1047
+ returns it. A track is dropped after ``max_age`` frames without a match.
1048
+ """
1049
+
1050
+ name: str = "sort"
1051
+ embedding_min_confidence: float | None = None
1052
+
1053
+ def __init__(self, *, max_age: int, min_hits: int) -> None:
1054
+ if max_age < 1 or min_hits < 0:
1055
+ raise ValueError("max_age must be positive and min_hits nonnegative.")
1056
+ # Frames a lost track stays recoverable; Re-ID merging waits this long.
1057
+ self.track_buffer = int(max_age)
1058
+ self.min_hits = int(min_hits)
1059
+ self.reset()
1060
+
1061
+ def reset(self) -> None:
1062
+ self._next_id = 1
1063
+ self._next_uid = 1
1064
+ self._frame_id = 0
1065
+ self._tracks: list[_SortTrack] = []
1066
+ self.last_events: list[dict[str, Any]] = []
1067
+
1068
+ def _spawn(self, det: Detection, motion: Any) -> _SortTrack:
1069
+ tr = _SortTrack(
1070
+ uid=self._next_uid,
1071
+ motion=motion,
1072
+ class_id=det.class_id,
1073
+ class_name=det.class_name,
1074
+ confidence=det.confidence,
1075
+ box=det.bbox,
1076
+ )
1077
+ self._next_uid += 1
1078
+ self._tracks.append(tr)
1079
+ return tr
1080
+
1081
+ def _predict(self) -> None:
1082
+ for tr in self._tracks:
1083
+ tr.recovered_now = False
1084
+ tr.reported = False
1085
+ tr.motion.predict()
1086
+ tr.age += 1
1087
+ if tr.time_since_update > 0:
1088
+ tr.hit_streak = 0
1089
+ tr.time_since_update += 1
1090
+
1091
+ @staticmethod
1092
+ def _observe(
1093
+ tr: _SortTrack,
1094
+ det: Detection,
1095
+ box: tuple[float, float, float, float],
1096
+ ) -> None:
1097
+ """Record that ``tr`` matched ``det`` this frame and will report ``box``."""
1098
+ if tr.track_id and tr.time_since_update > 1:
1099
+ tr.recovering = True
1100
+ tr.time_since_update = 0
1101
+ tr.hits += 1
1102
+ tr.hit_streak += 1
1103
+ tr.confidence = det.confidence
1104
+ tr.box = box
1105
+
1106
+ def _finish_frame(self, events: list[dict[str, Any]]) -> list[Track]:
1107
+ """Confirm, report, and expire tracks once this frame's matches are applied."""
1108
+ for tr in self._tracks:
1109
+ tr.reported = tr.time_since_update == 0 and (
1110
+ tr.hit_streak >= self.min_hits or self._frame_id <= self.min_hits
1111
+ )
1112
+ if not tr.reported:
1113
+ continue
1114
+ if tr.recovering:
1115
+ tr.recovering = False
1116
+ tr.recovered_now = True
1117
+ events.append({"type": "track_recovered", "track_id": tr.track_id})
1118
+ if not tr.track_id:
1119
+ tr.track_id = self._next_id
1120
+ self._next_id += 1
1121
+ events.append({"type": "track_started", "track_id": tr.track_id})
1122
+ switch = _switch_event(
1123
+ tr.track_id,
1124
+ tr.box,
1125
+ [
1126
+ (t.track_id, t.motion.box)
1127
+ for t in self._tracks
1128
+ if t.track_id
1129
+ and t.class_id == tr.class_id
1130
+ and 1 <= t.time_since_update <= 5
1131
+ ],
1132
+ )
1133
+ if switch is not None:
1134
+ events.append(switch)
1135
+
1136
+ outputs: list[Track] = []
1137
+ surviving: list[_SortTrack] = []
1138
+ for tr in self._tracks:
1139
+ if tr.reported:
1140
+ outputs.append(tr.to_track())
1141
+ elif tr.track_id and tr.time_since_update == 1 and not tr.recovering:
1142
+ events.append({"type": "track_lost", "track_id": tr.track_id})
1143
+ if tr.time_since_update > self.track_buffer:
1144
+ if tr.track_id:
1145
+ events.append({"type": "track_ended", "track_id": tr.track_id})
1146
+ continue
1147
+ surviving.append(tr)
1148
+ self._tracks = surviving
1149
+ self.last_events = events
1150
+ outputs.sort(key=lambda t: t.track_id)
1151
+ return outputs
1152
+
1153
+ def coasting_tracks(self, max_frames: int = 3) -> list[Track]:
1154
+ """Confirmed tracks not reported this frame, at the filter's estimate.
1155
+
1156
+ That is tracks missed for at most ``max_frames`` frames, and tracks matched again that
1157
+ are still rebuilding their hit streak. They are never written to exports.
1158
+ """
1159
+ out = [
1160
+ t.to_track(coasting=True)
1161
+ for t in self._tracks
1162
+ if t.track_id and not t.reported and t.time_since_update <= max_frames
1163
+ ]
1164
+ out.sort(key=lambda t: t.track_id)
1165
+ return out
1166
+
1167
+
1168
+ TRACKER_NAMES = ("bytetrack", "botsort", "ocsort", "boosttrack")
1169
+
1170
+
1171
+ def create_tracker(
1172
+ tracker_name: str = "bytetrack",
1173
+ *,
1174
+ track_high_thresh: float = 0.5,
1175
+ track_low_thresh: float = 0.15,
1176
+ new_track_thresh: float = 0.55,
1177
+ track_buffer: int = 30,
1178
+ iou_buffer: float = 0.0,
1179
+ ) -> Tracker:
1180
+ """Factory for the built-in multi-object trackers, named as in :data:`TRACKER_NAMES`."""
1181
+ key = tracker_name.lower().strip().replace("-", "_")
1182
+ if key in ("bytetrack", "byte"):
1183
+ return ByteTracker(
1184
+ track_high_thresh=track_high_thresh,
1185
+ track_low_thresh=track_low_thresh,
1186
+ new_track_thresh=new_track_thresh,
1187
+ track_buffer=track_buffer,
1188
+ iou_buffer=iou_buffer,
1189
+ )
1190
+ if key in ("botsort", "bot_sort"):
1191
+ return BotSortTracker(
1192
+ track_high_thresh=track_high_thresh,
1193
+ track_low_thresh=track_low_thresh,
1194
+ new_track_thresh=new_track_thresh,
1195
+ track_buffer=max(track_buffer, 45),
1196
+ iou_buffer=iou_buffer,
1197
+ )
1198
+ if key in ("ocsort", "oc_sort"):
1199
+ from trackflow.ocsort import OcSortTracker
1200
+
1201
+ return OcSortTracker(
1202
+ det_thresh=track_high_thresh,
1203
+ low_thresh=track_low_thresh,
1204
+ new_track_thresh=new_track_thresh,
1205
+ max_age=track_buffer,
1206
+ iou_buffer=iou_buffer,
1207
+ )
1208
+ if key in ("boosttrack", "boost_track", "boosttrack++", "boosttrackpp"):
1209
+ from trackflow.boosttrack import BoostTracker
1210
+
1211
+ return BoostTracker(
1212
+ det_thresh=track_high_thresh,
1213
+ new_track_thresh=new_track_thresh,
1214
+ max_age=track_buffer,
1215
+ iou_buffer=iou_buffer,
1216
+ )
1217
+ raise ValueError(
1218
+ f"Unknown tracker '{tracker_name}'. Choose one of: {', '.join(TRACKER_NAMES)}."
1219
+ )