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