trackflow-python 0.1.0__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,558 @@
1
+ """Pure NumPy/SciPy ByteTrack and BoT-SORT multi-object trackers with Kalman filtering & CMC."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import Any
7
+
8
+ import cv2
9
+ import numpy as np
10
+ from scipy.optimize import linear_sum_assignment
11
+
12
+ from trackflow.types import Detection, Track
13
+
14
+
15
+ def compute_iou_matrix(boxes_a: np.ndarray, boxes_b: np.ndarray) -> np.ndarray:
16
+ """Compute pairwise IoU matrix between two [N, 4] and [M, 4] xyxy arrays."""
17
+ if len(boxes_a) == 0 or len(boxes_b) == 0:
18
+ return np.zeros((len(boxes_a), len(boxes_b)), dtype=np.float32)
19
+
20
+ ax1, ay1, ax2, ay2 = np.split(boxes_a, 4, axis=1)
21
+ bx1, by1, bx2, by2 = np.split(boxes_b, 4, axis=1)
22
+
23
+ inter_x1 = np.maximum(ax1, bx1.T)
24
+ inter_y1 = np.maximum(ay1, by1.T)
25
+ inter_x2 = np.minimum(ax2, bx2.T)
26
+ inter_y2 = np.minimum(ay2, by2.T)
27
+
28
+ inter_w = np.maximum(0.0, inter_x2 - inter_x1)
29
+ inter_h = np.maximum(0.0, inter_y2 - inter_y1)
30
+ inter_area = inter_w * inter_h
31
+
32
+ area_a = np.maximum(0.0, ax2 - ax1) * np.maximum(0.0, ay2 - ay1)
33
+ area_b = np.maximum(0.0, bx2 - bx1) * np.maximum(0.0, by2 - by1)
34
+ union = np.maximum(area_a + area_b.T - inter_area, 1e-6)
35
+ return (inter_area / union).astype(np.float32)
36
+
37
+
38
+ def _xyxy_to_xyah(bbox: tuple[float, float, float, float]) -> np.ndarray:
39
+ x1, y1, x2, y2 = bbox
40
+ w = max(1.0, x2 - x1)
41
+ h = max(1.0, y2 - y1)
42
+ cx = x1 + 0.5 * w
43
+ cy = y1 + 0.5 * h
44
+ a = w / h
45
+ return np.array([cx, cy, a, h], dtype=np.float64)
46
+
47
+
48
+ def _xyah_to_xyxy(xyah: np.ndarray) -> tuple[float, float, float, float]:
49
+ cx, cy, a, h = (
50
+ float(xyah[0]),
51
+ float(xyah[1]),
52
+ max(0.05, float(xyah[2])),
53
+ max(1.0, float(xyah[3])),
54
+ )
55
+ w = a * h
56
+ return (cx - 0.5 * w, cy - 0.5 * h, cx + 0.5 * w, cy + 0.5 * h)
57
+
58
+
59
+ class KalmanBoxFilter:
60
+ """8-state constant-velocity Kalman filter for bounding boxes: [cx, cy, a, h, vx, vy, va, vh]."""
61
+
62
+ def __init__(self, initial_bbox: tuple[float, float, float, float]) -> None:
63
+ self._F = np.eye(8, dtype=np.float64)
64
+ for i in range(4):
65
+ self._F[i, i + 4] = 1.0
66
+ self._H = np.eye(4, 8, dtype=np.float64)
67
+
68
+ self._std_pos = 1.0 / 20.0
69
+ self._std_vel = 1.0 / 160.0
70
+
71
+ meas = _xyxy_to_xyah(initial_bbox)
72
+ self.mean = np.zeros(8, dtype=np.float64)
73
+ self.mean[:4] = meas
74
+
75
+ h = max(10.0, meas[3])
76
+ std = np.array(
77
+ [
78
+ 2 * self._std_pos * h,
79
+ 2 * self._std_pos * h,
80
+ 1e-2,
81
+ 2 * self._std_pos * h,
82
+ 10 * self._std_vel * h,
83
+ 10 * self._std_vel * h,
84
+ 1e-5,
85
+ 10 * self._std_vel * h,
86
+ ],
87
+ dtype=np.float64,
88
+ )
89
+ self.cov = np.diag(std**2)
90
+
91
+ def predict(self) -> tuple[float, float, float, float]:
92
+ h = max(10.0, float(self.mean[3]))
93
+ std = np.array(
94
+ [
95
+ self._std_pos * h,
96
+ self._std_pos * h,
97
+ 1e-2,
98
+ self._std_pos * h,
99
+ self._std_vel * h,
100
+ self._std_vel * h,
101
+ 1e-5,
102
+ self._std_vel * h,
103
+ ],
104
+ dtype=np.float64,
105
+ )
106
+ q = np.diag(std**2)
107
+ self.mean = self._F @ self.mean
108
+ if self.mean[3] < 1.0:
109
+ self.mean[3] = 1.0
110
+ self.mean[7] = 0.0
111
+ self.cov = self._F @ self.cov @ self._F.T + q
112
+ return _xyah_to_xyxy(self.mean[:4])
113
+
114
+ def update(self, bbox: tuple[float, float, float, float]) -> tuple[float, float, float, float]:
115
+ meas = _xyxy_to_xyah(bbox)
116
+ h = max(10.0, float(self.mean[3]))
117
+ r = np.diag(
118
+ np.array(
119
+ [self._std_pos * h, self._std_pos * h, 1e-1, self._std_pos * h], dtype=np.float64
120
+ )
121
+ ** 2
122
+ )
123
+ proj_mean = self._H @ self.mean
124
+ proj_cov = self._H @ self.cov @ self._H.T + r
125
+ kalman_gain = np.linalg.solve(proj_cov, self._H @ self.cov).T
126
+ innovation = meas - proj_mean
127
+ self.mean = self.mean + kalman_gain @ innovation
128
+ self.cov = self.cov - kalman_gain @ proj_cov @ kalman_gain.T
129
+ return _xyah_to_xyxy(self.mean[:4])
130
+
131
+ def apply_camera_warp(self, warp_2x3: np.ndarray) -> None:
132
+ """Apply a 2x3 affine camera motion transform to the predicted center & velocity."""
133
+ rot_scale = warp_2x3[:2, :2]
134
+ trans = warp_2x3[:2, 2]
135
+ self.mean[:2] = rot_scale @ self.mean[:2] + trans
136
+ self.mean[4:6] = rot_scale @ self.mean[4:6]
137
+
138
+
139
+ @dataclass
140
+ class _TrackState:
141
+ track_id: int
142
+ kf: KalmanBoxFilter
143
+ confidence: float
144
+ class_id: int
145
+ class_name: str
146
+ age: int = 1
147
+ hits: int = 1
148
+ time_since_update: int = 0
149
+ state: str = "tracked" # tracked | lost
150
+ embedding: np.ndarray | None = field(default=None, repr=False)
151
+
152
+ @property
153
+ def bbox(self) -> tuple[float, float, float, float]:
154
+ return _xyah_to_xyxy(self.kf.mean[:4])
155
+
156
+ def update_embedding(self, emb: np.ndarray | None, alpha: float = 0.85) -> None:
157
+ if emb is None:
158
+ return
159
+ norm = float(np.linalg.norm(emb))
160
+ if norm <= 1e-6:
161
+ return
162
+ unit = emb / norm
163
+ if self.embedding is None:
164
+ self.embedding = unit
165
+ else:
166
+ blended = alpha * self.embedding + (1.0 - alpha) * unit
167
+ bnorm = float(np.linalg.norm(blended))
168
+ self.embedding = blended / max(bnorm, 1e-6)
169
+
170
+
171
+ class SparseOpticalFlowCMC:
172
+ """Fast sparse optical-flow Camera Motion Compensation (BoT-SORT style)."""
173
+
174
+ def __init__(self, downscale: int = 2) -> None:
175
+ self.downscale = max(1, downscale)
176
+ self._prev_gray: np.ndarray | None = None
177
+ self._prev_pts: np.ndarray | None = None
178
+
179
+ def estimate(self, frame_bgr: np.ndarray | None) -> np.ndarray | None:
180
+ if frame_bgr is None:
181
+ return None
182
+ gray = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2GRAY)
183
+ if self.downscale > 1:
184
+ h, w = gray.shape[:2]
185
+ gray = cv2.resize(gray, (max(32, w // self.downscale), max(32, h // self.downscale)))
186
+
187
+ pts = cv2.goodFeaturesToTrack(
188
+ gray,
189
+ maxCorners=200,
190
+ qualityLevel=0.01,
191
+ minDistance=8,
192
+ blockSize=3,
193
+ )
194
+
195
+ if self._prev_gray is None or self._prev_pts is None or len(self._prev_pts) < 6:
196
+ self._prev_gray = gray
197
+ self._prev_pts = pts
198
+ return None
199
+
200
+ curr_pts, status, _ = cv2.calcOpticalFlowPyrLK(self._prev_gray, gray, self._prev_pts, None)
201
+ warp: np.ndarray | None = None
202
+ if curr_pts is not None and status is not None:
203
+ valid = status.ravel() == 1
204
+ p0 = self._prev_pts[valid]
205
+ p1 = curr_pts[valid]
206
+ if len(p0) >= 6:
207
+ mat, _ = cv2.estimateAffinePartial2D(p0, p1, method=cv2.RANSAC)
208
+ if mat is not None:
209
+ mat = mat.astype(np.float64)
210
+ mat[:2, 2] *= float(self.downscale)
211
+ warp = mat
212
+
213
+ self._prev_gray = gray
214
+ self._prev_pts = pts
215
+ return warp
216
+
217
+
218
+ def _linear_assignment(
219
+ cost_matrix: np.ndarray,
220
+ max_cost: float,
221
+ ) -> tuple[list[tuple[int, int]], list[int], list[int]]:
222
+ n_rows, n_cols = cost_matrix.shape
223
+ if n_rows == 0 or n_cols == 0:
224
+ return [], list(range(n_rows)), list(range(n_cols))
225
+
226
+ row_ind, col_ind = linear_sum_assignment(cost_matrix)
227
+ matches: list[tuple[int, int]] = []
228
+ matched_rows: set[int] = set()
229
+ matched_cols: set[int] = set()
230
+
231
+ for r, c in zip(row_ind.tolist(), col_ind.tolist(), strict=False):
232
+ if cost_matrix[r, c] <= max_cost:
233
+ matches.append((r, c))
234
+ matched_rows.add(r)
235
+ matched_cols.add(c)
236
+
237
+ unmatched_rows = [r for r in range(n_rows) if r not in matched_rows]
238
+ unmatched_cols = [c for c in range(n_cols) if c not in matched_cols]
239
+ return matches, unmatched_rows, unmatched_cols
240
+
241
+
242
+ class ByteTracker:
243
+ """Two-stage ByteTrack multi-object tracker with diagnostic event reporting."""
244
+
245
+ name: str = "bytetrack"
246
+
247
+ def __init__(
248
+ self,
249
+ *,
250
+ track_high_thresh: float = 0.5,
251
+ track_low_thresh: float = 0.15,
252
+ new_track_thresh: float = 0.55,
253
+ match_thresh: float = 0.8,
254
+ second_match_thresh: float = 0.5,
255
+ track_buffer: int = 30,
256
+ ) -> None:
257
+ self.track_high_thresh = float(track_high_thresh)
258
+ self.track_low_thresh = float(track_low_thresh)
259
+ self.new_track_thresh = float(new_track_thresh)
260
+ self.match_thresh = float(match_thresh)
261
+ self.second_match_thresh = float(second_match_thresh)
262
+ self.track_buffer = int(track_buffer)
263
+
264
+ self._next_id = 1
265
+ self._frame_id = 0
266
+ self._tracks: list[_TrackState] = []
267
+ self.last_events: list[dict[str, Any]] = []
268
+
269
+ def reset(self) -> None:
270
+ self._next_id = 1
271
+ self._frame_id = 0
272
+ self._tracks.clear()
273
+ self.last_events = []
274
+
275
+ def _compute_first_stage_cost(
276
+ self,
277
+ pool: list[_TrackState],
278
+ dets: list[Detection],
279
+ ) -> np.ndarray:
280
+ t_boxes = np.array([t.bbox for t in pool], dtype=np.float32)
281
+ d_boxes = np.array([d.bbox for d in dets], dtype=np.float32)
282
+ iou = compute_iou_matrix(t_boxes, d_boxes)
283
+ return 1.0 - iou
284
+
285
+ def _apply_cmc(self, frame_bgr: np.ndarray | None) -> None:
286
+ """No-op in ByteTrack; overridden by BoT-SORT."""
287
+ _ = frame_bgr
288
+
289
+ def update(
290
+ self,
291
+ detections: list[Detection],
292
+ frame_bgr: np.ndarray | None = None,
293
+ ) -> list[Track]:
294
+ """Advance the tracker by one frame and return active Tracks."""
295
+ self._frame_id += 1
296
+ events: list[dict[str, Any]] = []
297
+
298
+ # 1. Predict all existing tracked & lost states
299
+ for t in self._tracks:
300
+ t.kf.predict()
301
+ t.age += 1
302
+ t.time_since_update += 1
303
+
304
+ # Optional camera motion compensation (active in BoT-SORT)
305
+ self._apply_cmc(frame_bgr)
306
+
307
+ # Partition detections into high-confidence and low-confidence tiers
308
+ high_dets = [d for d in detections if d.confidence >= self.track_high_thresh]
309
+ low_dets = [
310
+ d for d in detections if self.track_low_thresh <= d.confidence < self.track_high_thresh
311
+ ]
312
+
313
+ pool = list(self._tracks)
314
+ active_outputs: list[Track] = []
315
+ updated_ids: set[int] = set()
316
+
317
+ # 2. First association: all tracks (tracked + lost) with high-confidence detections
318
+ if pool and high_dets:
319
+ cost = self._compute_first_stage_cost(pool, high_dets)
320
+ matches, unmatched_t_idx, unmatched_d_idx = _linear_assignment(
321
+ cost, max_cost=self.match_thresh
322
+ )
323
+ else:
324
+ matches = []
325
+ unmatched_t_idx = list(range(len(pool)))
326
+ unmatched_d_idx = list(range(len(high_dets)))
327
+
328
+ for ti, di in matches:
329
+ tr = pool[ti]
330
+ det = high_dets[di]
331
+ was_lost = tr.state == "lost"
332
+ tr.kf.update(det.bbox)
333
+ tr.confidence = det.confidence
334
+ tr.class_id = det.class_id
335
+ tr.class_name = det.class_name
336
+ tr.hits += 1
337
+ tr.time_since_update = 0
338
+ tr.state = "tracked"
339
+ tr.update_embedding(det.embedding)
340
+ updated_ids.add(tr.track_id)
341
+ if was_lost:
342
+ events.append({"type": "track_recovered", "track_id": tr.track_id})
343
+ active_outputs.append(
344
+ Track(
345
+ track_id=tr.track_id,
346
+ bbox=tr.bbox,
347
+ confidence=tr.confidence,
348
+ class_id=tr.class_id,
349
+ class_name=tr.class_name,
350
+ age=tr.age,
351
+ hits=tr.hits,
352
+ recovered=was_lost,
353
+ )
354
+ )
355
+
356
+ # 3. Second association: remaining *tracked* tracks with low-confidence detections (IoU only)
357
+ rem_tracked = [pool[i] for i in unmatched_t_idx if pool[i].state == "tracked"]
358
+ if rem_tracked and low_dets:
359
+ t_boxes = np.array([t.bbox for t in rem_tracked], dtype=np.float32)
360
+ d_boxes = np.array([d.bbox for d in low_dets], dtype=np.float32)
361
+ cost_low = 1.0 - compute_iou_matrix(t_boxes, d_boxes)
362
+ low_matches, _, _ = _linear_assignment(cost_low, max_cost=self.second_match_thresh)
363
+ for ti, di in low_matches:
364
+ tr = rem_tracked[ti]
365
+ det = low_dets[di]
366
+ tr.kf.update(det.bbox)
367
+ tr.confidence = det.confidence
368
+ tr.hits += 1
369
+ tr.time_since_update = 0
370
+ tr.state = "tracked"
371
+ updated_ids.add(tr.track_id)
372
+ active_outputs.append(
373
+ Track(
374
+ track_id=tr.track_id,
375
+ bbox=tr.bbox,
376
+ confidence=tr.confidence,
377
+ class_id=tr.class_id,
378
+ class_name=tr.class_name,
379
+ age=tr.age,
380
+ hits=tr.hits,
381
+ recovered=False,
382
+ )
383
+ )
384
+
385
+ # 4. Mark unmatched tracks as lost and prune expired tracks
386
+ surviving: list[_TrackState] = []
387
+ recently_lost_boxes: list[tuple[int, tuple[float, float, float, float]]] = []
388
+ for tr in self._tracks:
389
+ if tr.track_id in updated_ids:
390
+ surviving.append(tr)
391
+ else:
392
+ if tr.state == "tracked":
393
+ tr.state = "lost"
394
+ events.append({"type": "track_lost", "track_id": tr.track_id})
395
+ if tr.time_since_update <= self.track_buffer:
396
+ surviving.append(tr)
397
+ if tr.time_since_update <= 5:
398
+ recently_lost_boxes.append((tr.track_id, tr.bbox))
399
+ else:
400
+ events.append({"type": "track_ended", "track_id": tr.track_id})
401
+
402
+ # 5. Spawn new tracks for unmatched high-confidence detections
403
+ for di in unmatched_d_idx:
404
+ det = high_dets[di]
405
+ if det.confidence < self.new_track_thresh:
406
+ continue
407
+ new_id = self._next_id
408
+ self._next_id += 1
409
+ tr = _TrackState(
410
+ track_id=new_id,
411
+ kf=KalmanBoxFilter(det.bbox),
412
+ confidence=det.confidence,
413
+ class_id=det.class_id,
414
+ class_name=det.class_name,
415
+ embedding=None,
416
+ )
417
+ tr.update_embedding(det.embedding)
418
+ surviving.append(tr)
419
+ events.append({"type": "track_started", "track_id": new_id})
420
+
421
+ # Flag possible ID switch if a new track spawns near a recently lost track
422
+ if recently_lost_boxes:
423
+ new_box = np.array([det.bbox], dtype=np.float32)
424
+ lost_arr = np.array([b for _, b in recently_lost_boxes], dtype=np.float32)
425
+ ious = compute_iou_matrix(new_box, lost_arr)[0]
426
+ best_j = int(np.argmax(ious))
427
+ if float(ious[best_j]) >= 0.25:
428
+ events.append(
429
+ {
430
+ "type": "possible_id_switch",
431
+ "new_track_id": new_id,
432
+ "previous_track_id": recently_lost_boxes[best_j][0],
433
+ "iou": round(float(ious[best_j]), 3),
434
+ }
435
+ )
436
+
437
+ active_outputs.append(
438
+ Track(
439
+ track_id=new_id,
440
+ bbox=tr.bbox,
441
+ confidence=tr.confidence,
442
+ class_id=tr.class_id,
443
+ class_name=tr.class_name,
444
+ age=1,
445
+ hits=1,
446
+ recovered=False,
447
+ )
448
+ )
449
+
450
+ self._tracks = surviving
451
+ self.last_events = events
452
+ active_outputs.sort(key=lambda t: t.track_id)
453
+ return active_outputs
454
+
455
+
456
+ class BotSortTracker(ByteTracker):
457
+ """BoT-SORT tracker: ByteTrack + Sparse Optical Flow CMC + Appearance Re-ID fusion."""
458
+
459
+ name: str = "botsort"
460
+
461
+ def __init__(
462
+ self,
463
+ *,
464
+ track_high_thresh: float = 0.5,
465
+ track_low_thresh: float = 0.15,
466
+ new_track_thresh: float = 0.55,
467
+ match_thresh: float = 0.8,
468
+ second_match_thresh: float = 0.5,
469
+ track_buffer: int = 45,
470
+ use_cmc: bool = True,
471
+ proximity_thresh: float = 0.5,
472
+ appearance_thresh: float = 0.35,
473
+ ) -> None:
474
+ super().__init__(
475
+ track_high_thresh=track_high_thresh,
476
+ track_low_thresh=track_low_thresh,
477
+ new_track_thresh=new_track_thresh,
478
+ match_thresh=match_thresh,
479
+ second_match_thresh=second_match_thresh,
480
+ track_buffer=track_buffer,
481
+ )
482
+ self.use_cmc = use_cmc
483
+ self.proximity_thresh = float(proximity_thresh)
484
+ self.appearance_thresh = float(appearance_thresh)
485
+ self._cmc = SparseOpticalFlowCMC() if use_cmc else None
486
+
487
+ def reset(self) -> None:
488
+ super().reset()
489
+ if self.use_cmc:
490
+ self._cmc = SparseOpticalFlowCMC()
491
+
492
+ def _apply_cmc(self, frame_bgr: np.ndarray | None) -> None:
493
+ if self._cmc is None or frame_bgr is None or not self._tracks:
494
+ return
495
+ warp = self._cmc.estimate(frame_bgr)
496
+ if warp is None:
497
+ return
498
+ for tr in self._tracks:
499
+ tr.kf.apply_camera_warp(warp)
500
+
501
+ def _compute_first_stage_cost(
502
+ self,
503
+ pool: list[_TrackState],
504
+ dets: list[Detection],
505
+ ) -> np.ndarray:
506
+ iou_dist = super()._compute_first_stage_cost(pool, dets)
507
+
508
+ # Fuse cosine appearance distance when both track & detection have embeddings
509
+ has_any_emb = any(t.embedding is not None for t in pool) and any(
510
+ d.embedding is not None for d in dets
511
+ )
512
+ if not has_any_emb:
513
+ return iou_dist
514
+
515
+ fused = iou_dist.copy()
516
+ for i, tr in enumerate(pool):
517
+ if tr.embedding is None:
518
+ continue
519
+ for j, det in enumerate(dets):
520
+ if det.embedding is None:
521
+ continue
522
+ if iou_dist[i, j] > self.proximity_thresh:
523
+ continue
524
+ d_norm = float(np.linalg.norm(det.embedding))
525
+ if d_norm <= 1e-6:
526
+ continue
527
+ cos_sim = float(np.dot(tr.embedding, det.embedding / d_norm))
528
+ emb_dist = max(0.0, min(1.0, 0.5 * (1.0 - cos_sim)))
529
+ if emb_dist <= self.appearance_thresh:
530
+ fused[i, j] = min(float(iou_dist[i, j]), emb_dist)
531
+ return fused
532
+
533
+
534
+ def create_tracker(
535
+ tracker_name: str = "bytetrack",
536
+ *,
537
+ track_high_thresh: float = 0.5,
538
+ track_low_thresh: float = 0.15,
539
+ new_track_thresh: float = 0.55,
540
+ track_buffer: int = 30,
541
+ ) -> ByteTracker:
542
+ """Factory for built-in multi-object trackers."""
543
+ key = tracker_name.lower().strip().replace("-", "_")
544
+ if key in ("bytetrack", "byte"):
545
+ return ByteTracker(
546
+ track_high_thresh=track_high_thresh,
547
+ track_low_thresh=track_low_thresh,
548
+ new_track_thresh=new_track_thresh,
549
+ track_buffer=track_buffer,
550
+ )
551
+ if key in ("botsort", "bot_sort"):
552
+ return BotSortTracker(
553
+ track_high_thresh=track_high_thresh,
554
+ track_low_thresh=track_low_thresh,
555
+ new_track_thresh=new_track_thresh,
556
+ track_buffer=max(track_buffer, 45),
557
+ )
558
+ raise ValueError(f"Unknown tracker '{tracker_name}'. Choose 'bytetrack' or 'botsort'.")