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/ocsort.py ADDED
@@ -0,0 +1,406 @@
1
+ """OC-SORT multi-object tracker (Cao et al., "Observation-Centric SORT", CVPR 2023).
2
+
3
+ A port of the reference implementation (github.com/noahcao/OC_SORT, MIT license) onto Trackflow's
4
+ track lifecycle. Association is class-aware, and each assignment only considers pairs that pass
5
+ the IoU gate.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import math
11
+ from typing import Any
12
+
13
+ import numpy as np
14
+
15
+ from trackflow._accel import native_module
16
+ from trackflow.tracker import (
17
+ SparseOpticalFlowCMC,
18
+ _assign,
19
+ _boxes,
20
+ _expand_boxes,
21
+ _SortStyleTracker,
22
+ _SortTrack,
23
+ compute_hmiou_matrix,
24
+ compute_ioa_matrix,
25
+ compute_iou_matrix,
26
+ )
27
+ from trackflow.types import Detection, Track
28
+
29
+ Box = tuple[float, float, float, float]
30
+
31
+
32
+ def _box_to_z(box: Box) -> np.ndarray:
33
+ """``[cx, cy, area, w/h]``, SORT's measurement vector."""
34
+ x1, y1, x2, y2 = box
35
+ w = max(x2 - x1, 1e-3)
36
+ h = max(y2 - y1, 1e-3)
37
+ return np.array([x1 + 0.5 * w, y1 + 0.5 * h, w * h, w / h], dtype=np.float64)
38
+
39
+
40
+ def _z_to_box(z: np.ndarray) -> Box:
41
+ area = max(float(z[2]), 1e-6)
42
+ ratio = max(float(z[3]), 1e-6)
43
+ w = float(np.sqrt(area * ratio))
44
+ h = area / w
45
+ cx, cy = float(z[0]), float(z[1])
46
+ return (cx - 0.5 * w, cy - 0.5 * h, cx + 0.5 * w, cy + 0.5 * h)
47
+
48
+
49
+ def _centers(boxes: np.ndarray) -> np.ndarray:
50
+ return np.stack([(boxes[:, 0] + boxes[:, 2]) / 2, (boxes[:, 1] + boxes[:, 3]) / 2], axis=1)
51
+
52
+
53
+ def _direction(a: Box, b: Box) -> np.ndarray:
54
+ """Unit vector ``(dy, dx)`` from the center of ``a`` to the center of ``b``."""
55
+ dx = 0.5 * ((b[0] + b[2]) - (a[0] + a[2]))
56
+ dy = 0.5 * ((b[1] + b[3]) - (a[1] + a[3]))
57
+ inv = 1.0 / (math.hypot(dy, dx) + 1e-6)
58
+ return np.array([dy * inv, dx * inv], dtype=np.float64)
59
+
60
+
61
+ def _transition(n: int) -> np.ndarray:
62
+ f = np.eye(n, dtype=np.float64)
63
+ for i in range(n - 4):
64
+ f[i, i + 4] = 1.0
65
+ return f
66
+
67
+
68
+ def _soft_iou(tracks: np.ndarray, detections: np.ndarray) -> np.ndarray:
69
+ """Blend IoU with expanded IoU to tolerate small prediction errors."""
70
+ raw = compute_iou_matrix(tracks, detections)
71
+ buffered = compute_iou_matrix(_expand_boxes(tracks, 0.15), _expand_boxes(detections, 0.15))
72
+ return (raw + buffered) / 2
73
+
74
+
75
+ def _hm_soft_iou(tracks: np.ndarray, detections: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
76
+ """Soft IoU for gating and its height-modulated version (Hybrid-SORT HMIoU) for cost."""
77
+ iou = _soft_iou(tracks, detections)
78
+ return iou, compute_hmiou_matrix(tracks, detections, iou)
79
+
80
+
81
+ class _OcSortMotion:
82
+ """SORT's Kalman filter on ``[cx, cy, area, w/h]`` plus the observations OC-SORT uses.
83
+
84
+ While a track goes unmatched the filter coasts on its prediction. When it matches again, the
85
+ state is rolled back to the first missed frame and re-updated along a straight line from the
86
+ last observation to the new one (observation-centric re-update), which undoes the drift
87
+ accumulated while coasting.
88
+ """
89
+
90
+ _F = _transition(7)
91
+ _H = np.eye(4, 7, dtype=np.float64)
92
+ _Q = np.diag([1.0, 1.0, 1.0, 1.0, 1e-2, 1e-2, 1e-4])
93
+ _R = np.diag([1.0, 1.0, 10.0, 10.0])
94
+
95
+ def __init__(self, box: Box, delta_t: int) -> None:
96
+ self.x = np.zeros(7, dtype=np.float64)
97
+ self.x[:4] = _box_to_z(box)
98
+ self.P = np.diag([10.0, 10.0, 10.0, 10.0, 1e4, 1e4, 1e4])
99
+ self.delta_t = delta_t
100
+ self.observations: dict[int, Box] = {0: box} # track age -> observed box
101
+ self.last_observation = box
102
+ self.direction = np.zeros(2) # unit (dy, dx) of recent motion, zero until known
103
+ self._frozen: tuple[np.ndarray, np.ndarray] | None = None
104
+ self._missed = 0
105
+
106
+ @property
107
+ def box(self) -> Box:
108
+ return _z_to_box(self.x)
109
+
110
+ def predict(self) -> None:
111
+ if self.x[6] + self.x[2] <= 0:
112
+ self.x[6] = 0.0
113
+ self._predict()
114
+
115
+ def compensate(self, warp: np.ndarray, jacobian: np.ndarray, scale: float) -> None:
116
+ """Map the filter and its stored observations into the current frame."""
117
+ shift = warp[:, 2]
118
+ linear = warp[:, :2]
119
+ self.x = jacobian @ self.x
120
+ self.x[:2] += shift
121
+ self.P = jacobian @ self.P @ jacobian.T
122
+ if self._frozen is not None:
123
+ state, covariance = self._frozen
124
+ state = jacobian @ state
125
+ state[:2] += shift
126
+ self._frozen = (state, jacobian @ covariance @ jacobian.T)
127
+ self.direction = (linear @ self.direction[::-1])[::-1] / scale
128
+
129
+ def move(box: Box) -> Box:
130
+ x1, y1, x2, y2 = box
131
+ cx, cy = linear @ ((x1 + x2) / 2, (y1 + y2) / 2) + shift
132
+ hw, hh = (x2 - x1) * scale / 2, (y2 - y1) * scale / 2
133
+ return (cx - hw, cy - hh, cx + hw, cy + hh)
134
+
135
+ self.last_observation = move(self.last_observation)
136
+ self.observations = {age: move(box) for age, box in self.observations.items()}
137
+
138
+ def _predict(self) -> None:
139
+ self.x = self._F @ self.x
140
+ self.P = self._F @ self.P @ self._F.T + self._Q
141
+
142
+ def _correct(self, z: np.ndarray) -> None:
143
+ s = self._H @ self.P @ self._H.T + self._R
144
+ gain = np.linalg.solve(s, self._H @ self.P).T
145
+ self.x = self.x + gain @ (z - self._H @ self.x)
146
+ i_kh = np.eye(7) - gain @ self._H
147
+ self.P = i_kh @ self.P @ i_kh.T + gain @ self._R @ gain.T
148
+
149
+ def reference_observation(self, age: int) -> Box:
150
+ """The observation ``delta_t`` frames back, else the closest later one."""
151
+ for dt in range(self.delta_t, 0, -1):
152
+ obs = self.observations.get(age - dt)
153
+ if obs is not None:
154
+ return obs
155
+ return self.last_observation
156
+
157
+ def miss(self) -> None:
158
+ if self._frozen is None:
159
+ self._frozen = (self.x.copy(), self.P.copy())
160
+ self._missed += 1
161
+
162
+ def update(self, box: Box, age: int) -> None:
163
+ self.direction = _direction(self.reference_observation(age), box)
164
+ if self._frozen is None:
165
+ self._correct(_box_to_z(box))
166
+ else:
167
+ self.x, self.P = self._frozen
168
+ gap = self._missed + 1
169
+ self._frozen, self._missed = None, 0
170
+ start, end = self.last_observation, box
171
+ w0, h0 = start[2] - start[0], start[3] - start[1]
172
+ w1, h1 = end[2] - end[0], end[3] - end[1]
173
+ (c0, c1) = _centers(np.array([start, end], dtype=np.float64))
174
+ for step in range(1, gap + 1):
175
+ f = step / gap
176
+ cx, cy = c0 + f * (c1 - c0)
177
+ w = max(w0 + f * (w1 - w0), 1e-3)
178
+ h = max(h0 + f * (h1 - h0), 1e-3)
179
+ self._correct(np.array([cx, cy, w * h, w / h]))
180
+ if step < gap:
181
+ self._predict()
182
+ self.last_observation = box
183
+ self.observations[age] = box
184
+ oldest = age + 1 - self.delta_t
185
+ self.observations = {a: b for a, b in self.observations.items() if a >= oldest}
186
+
187
+
188
+ class OcSortTracker(_SortStyleTracker):
189
+ """OC-SORT: SORT made robust to occlusion by trusting observations over predictions.
190
+
191
+ Each frame:
192
+
193
+ 1. high-score detections <-> confirmed tracks' predicted boxes, by IoU plus observation-centric
194
+ momentum (OCM): a bonus, weighted by ``inertia`` and the detection score, when the
195
+ direction from the track's observation ``delta_t`` frames back to the detection agrees
196
+ with the track's recent direction of motion;
197
+ 2. observation-centric recovery (OCR): remaining high-score detections <-> remaining
198
+ tracks' *last observed* boxes by IoU, which recovers tracks the filter has drifted off;
199
+ 3. with ``use_byte``, low-score detections <-> remaining confirmed tracks seen on the
200
+ previous frame, by IoU;
201
+ 4. remaining high-score detections <-> tentative (not yet confirmed) tracks, by IoU;
202
+ 5. unmatched detections at or above ``new_track_thresh`` spawn tracks, unless mostly
203
+ covered by a box matched this frame. A tentative track that misses a frame is dropped.
204
+
205
+ A track that matches again after missing frames is re-updated along a virtual trajectory
206
+ (ORU). Confirmed tracks report the matched detection's box.
207
+ """
208
+
209
+ name: str = "ocsort"
210
+
211
+ def __init__(
212
+ self,
213
+ *,
214
+ det_thresh: float = 0.5,
215
+ low_thresh: float = 0.1,
216
+ iou_threshold: float = 0.3,
217
+ max_age: int = 30,
218
+ min_hits: int = 3,
219
+ delta_t: int = 3,
220
+ inertia: float = 0.2,
221
+ use_byte: bool = True,
222
+ iou_buffer: float = 0.0,
223
+ use_cmc: bool = True,
224
+ new_track_thresh: float | None = None,
225
+ ) -> None:
226
+ self.det_thresh = float(det_thresh)
227
+ self.new_track_thresh = (
228
+ float(new_track_thresh)
229
+ if new_track_thresh is not None
230
+ else max(self.det_thresh, min(0.95, self.det_thresh + 0.05))
231
+ )
232
+ self.low_thresh = float(low_thresh)
233
+ self.iou_threshold = float(iou_threshold)
234
+ self.delta_t = int(delta_t)
235
+ self.inertia = float(inertia)
236
+ self.use_byte = bool(use_byte)
237
+ self.use_cmc = bool(use_cmc)
238
+ # Buffered IoU for the first association (see iou_buffer_for_interval).
239
+ self.iou_buffer = float(iou_buffer)
240
+ self._native: Any = None
241
+ super().__init__(max_age=max_age, min_hits=min_hits)
242
+ if type(self) is OcSortTracker:
243
+ native = native_module()
244
+ if native is not None:
245
+ self._native = native.NativeOcSortTracker(
246
+ self.det_thresh,
247
+ self.new_track_thresh,
248
+ self.low_thresh,
249
+ self.iou_threshold,
250
+ self.track_buffer,
251
+ self.min_hits,
252
+ self.delta_t,
253
+ self.inertia,
254
+ self.use_byte,
255
+ )
256
+
257
+ def reset(self) -> None:
258
+ super().reset()
259
+ self._cmc = SparseOpticalFlowCMC() if self.use_cmc else None
260
+ self.last_cmc_warp: np.ndarray | None = None
261
+ if self._native is not None:
262
+ self._native.reset()
263
+
264
+ def coasting_tracks(self, max_frames: int = 3) -> list[Track]:
265
+ if self._native is not None:
266
+ return self._native.coasting_tracks(max_frames)
267
+ return super().coasting_tracks(max_frames)
268
+
269
+ def _compensate(self, frame: np.ndarray, detections: list[Detection]) -> None:
270
+ assert self._cmc is not None
271
+ warp = self._cmc.estimate(frame, _boxes(detections))
272
+ self.last_cmc_warp = warp
273
+ if warp is None:
274
+ return
275
+ linear = warp[:, :2]
276
+ area_scale = float(np.sum(linear[0] ** 2))
277
+ if area_scale <= 1e-6:
278
+ return
279
+ jacobian = np.eye(7)
280
+ jacobian[:2, :2] = jacobian[4:6, 4:6] = linear
281
+ jacobian[2, 2] = jacobian[6, 6] = area_scale
282
+ scale = float(np.sqrt(area_scale))
283
+ for track in self._tracks:
284
+ track.motion.compensate(warp, jacobian, scale)
285
+
286
+ def _gate(self, iou: np.ndarray, tracks: list[_SortTrack], dets: list[Detection]) -> np.ndarray:
287
+ same_class = np.equal.outer([t.class_id for t in tracks], [d.class_id for d in dets])
288
+ return (iou >= self.iou_threshold) & same_class
289
+
290
+ def _momentum(self, tracks: list[_SortTrack], dets: list[Detection]) -> np.ndarray:
291
+ """OCM bonus for each (track, detection) pair, in ``[-inertia/2, inertia/2] * score``."""
292
+ refs = np.array([t.motion.reference_observation(t.age) for t in tracks], dtype=np.float64)
293
+ delta = _centers(_boxes(dets))[None, :, :] - _centers(refs)[:, None, :]
294
+ norm = np.hypot(delta[..., 0], delta[..., 1]) + 1e-6
295
+ dx, dy = delta[..., 0] / norm, delta[..., 1] / norm
296
+ velocity = np.array([t.motion.direction for t in tracks]) # (dy, dx) per track
297
+ cos = np.clip(velocity[:, 0:1] * dy + velocity[:, 1:2] * dx, -1.0, 1.0)
298
+ agreement = (np.pi / 2 - np.abs(np.arccos(cos))) / np.pi
299
+ scores = np.array([d.confidence for d in dets])
300
+ return agreement * self.inertia * scores[None, :]
301
+
302
+ def _match(self, tr: _SortTrack, det: Detection) -> None:
303
+ tr.motion.update(det.bbox, tr.age)
304
+ self._observe(tr, det, det.bbox)
305
+
306
+ def update(
307
+ self,
308
+ detections: list[Detection],
309
+ frame_bgr: np.ndarray | None = None,
310
+ ) -> list[Track]:
311
+ """Advance the tracker by one frame and return the tracks reported on it."""
312
+ if self._native is not None:
313
+ self.last_cmc_warp = None
314
+ warp: np.ndarray | None = None
315
+ if self._cmc is not None:
316
+ if frame_bgr is None:
317
+ self._cmc = SparseOpticalFlowCMC()
318
+ else:
319
+ warp = self._cmc.estimate(frame_bgr, _boxes(detections))
320
+ self.last_cmc_warp = warp
321
+ outputs, events = self._native.update(detections, self.iou_buffer, warp)
322
+ self.last_events = events
323
+ return outputs
324
+ self._frame_id += 1
325
+ events: list[dict[str, Any]] = []
326
+ self.last_cmc_warp = None
327
+ if self._cmc is not None:
328
+ if frame_bgr is None:
329
+ self._cmc = SparseOpticalFlowCMC()
330
+ else:
331
+ self._compensate(frame_bgr, detections)
332
+ self._predict()
333
+ # Confirmed tracks associate first; tentative tracks only get the leftover detections.
334
+ tracks = [t for t in self._tracks if t.track_id]
335
+ tentative = [t for t in self._tracks if not t.track_id]
336
+
337
+ high = [d for d in detections if d.confidence >= self.det_thresh]
338
+ u_det = list(range(len(high)))
339
+ u_trk = list(range(len(tracks)))
340
+
341
+ # 1. High-score detections <-> predicted boxes, IoU plus direction consistency.
342
+ if tracks and high:
343
+ iou, cost = _hm_soft_iou(
344
+ _expand_boxes(np.array([t.motion.box for t in tracks]), self.iou_buffer),
345
+ _expand_boxes(_boxes(high), self.iou_buffer),
346
+ )
347
+ matches, u_trk, u_det = _assign(
348
+ cost + self._momentum(tracks, high), self._gate(iou, tracks, high)
349
+ )
350
+ for ti, di in matches:
351
+ self._match(tracks[ti], high[di])
352
+
353
+ # 2. OCR: remaining high-score detections <-> last observed boxes.
354
+ if u_det and u_trk:
355
+ rest = [tracks[i] for i in u_trk]
356
+ dets = [high[i] for i in u_det]
357
+ iou, cost = _hm_soft_iou(
358
+ np.array([t.motion.last_observation for t in rest], dtype=np.float64),
359
+ _boxes(dets),
360
+ )
361
+ matches, left_t, left_d = _assign(cost, self._gate(iou, rest, dets))
362
+ for ti, di in matches:
363
+ self._match(rest[ti], dets[di])
364
+ u_trk = [u_trk[i] for i in left_t]
365
+ u_det = [u_det[i] for i in left_d]
366
+
367
+ # 3. Low scores can sustain an active track after both high-score passes.
368
+ if self.use_byte and u_trk:
369
+ active = [i for i in u_trk if tracks[i].track_id and tracks[i].time_since_update == 1]
370
+ low = [d for d in detections if self.low_thresh <= d.confidence < self.det_thresh]
371
+ if active and low:
372
+ rest = [tracks[i] for i in active]
373
+ iou = compute_iou_matrix(np.array([t.motion.box for t in rest]), _boxes(low))
374
+ matches, _, _ = _assign(iou, self._gate(iou, rest, low) & (iou >= 0.5))
375
+ for ti, di in matches:
376
+ self._match(rest[ti], low[di])
377
+
378
+ # 4. Tentative tracks <-> remaining high-score detections.
379
+ if tentative and u_det:
380
+ dets = [high[i] for i in u_det]
381
+ iou, cost = _hm_soft_iou(np.array([t.motion.box for t in tentative]), _boxes(dets))
382
+ matches, _, left_d = _assign(cost, self._gate(iou, tentative, dets))
383
+ for ti, di in matches:
384
+ self._match(tentative[ti], dets[di])
385
+ u_det = [u_det[i] for i in left_d]
386
+
387
+ for i in u_trk:
388
+ if tracks[i].time_since_update:
389
+ tracks[i].motion.miss()
390
+ # A tentative track that misses a frame is dropped so it can't take later detections.
391
+ self._tracks = [t for t in self._tracks if t.track_id or not t.time_since_update]
392
+ # Spawn from confident leftovers that aren't mostly covered by a box matched this frame.
393
+ taken: dict[int, list[Box]] = {}
394
+ for t in self._tracks:
395
+ if not t.time_since_update:
396
+ taken.setdefault(t.class_id, []).append(t.box)
397
+ for i in sorted(u_det, key=lambda i: -high[i].confidence):
398
+ det = high[i]
399
+ if det.confidence < self.new_track_thresh:
400
+ continue
401
+ same = taken.get(det.class_id)
402
+ if same and float(compute_ioa_matrix(_boxes([det]), np.array(same)).max()) >= 0.8:
403
+ continue
404
+ self._spawn(det, _OcSortMotion(det.bbox, self.delta_t))
405
+ taken.setdefault(det.class_id, []).append(det.bbox)
406
+ return self._finish_frame(events)