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