trackflow-python-tensorrt 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.
- Cargo.lock +132 -0
- LICENSE +202 -0
- README.md +364 -0
- trackflow/__init__.py +93 -0
- trackflow/_accel.py +36 -0
- trackflow/_native.pyd +0 -0
- trackflow/benchmark.py +266 -0
- trackflow/boosttrack.py +476 -0
- trackflow/cli.py +705 -0
- trackflow/detector.py +912 -0
- trackflow/homography.py +240 -0
- trackflow/inspector.py +479 -0
- trackflow/inspector_ui.html +538 -0
- trackflow/lines.py +125 -0
- trackflow/mask_fallback.py +1025 -0
- trackflow/models.py +491 -0
- trackflow/nltrack.py +1107 -0
- trackflow/ocsort.py +406 -0
- trackflow/pipeline.py +1473 -0
- trackflow/postprocess.py +2068 -0
- trackflow/privacy.py +266 -0
- trackflow/py.typed +1 -0
- trackflow/reid.py +985 -0
- trackflow/sam2_adapter.py +222 -0
- trackflow/sinks.py +440 -0
- trackflow/tracker.py +1331 -0
- trackflow/types.py +241 -0
- trackflow_python_tensorrt-0.7.0.dist-info/METADATA +421 -0
- trackflow_python_tensorrt-0.7.0.dist-info/RECORD +33 -0
- trackflow_python_tensorrt-0.7.0.dist-info/WHEEL +4 -0
- trackflow_python_tensorrt-0.7.0.dist-info/entry_points.txt +3 -0
- trackflow_python_tensorrt-0.7.0.dist-info/licenses/LICENSE +202 -0
- trackflow_python_tensorrt-0.7.0.dist-info/sboms/trackflow-native.cyclonedx.json +536 -0
trackflow/postprocess.py
ADDED
|
@@ -0,0 +1,2068 @@
|
|
|
1
|
+
"""Offline post-processing for multi-object tracking outputs.
|
|
2
|
+
|
|
3
|
+
Implements suspect-transition track splitting (internal gaps, crossing overlaps, and
|
|
4
|
+
birth/death overlap junctions) followed by two-stage global CMC-kinematic and
|
|
5
|
+
sequence-calibrated appearance re-stitching via exact bipartite assignment, then
|
|
6
|
+
support- and motion-gated CMC-compensated short-gap interpolation, and finally gated
|
|
7
|
+
image-space smoothing of box jitter.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import time
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
import numpy as np
|
|
17
|
+
from scipy.ndimage import gaussian_filter1d
|
|
18
|
+
from scipy.optimize import linear_sum_assignment
|
|
19
|
+
|
|
20
|
+
from trackflow._accel import native_module
|
|
21
|
+
|
|
22
|
+
# Stage 3 gap interpolation gates.
|
|
23
|
+
_INTERP_MAX_GAP_S = 20.0 / 30.0 # longest filled gap without strong Re-ID verification, seconds
|
|
24
|
+
_INTERP_REID_MAX_GAP_S = 36.0 / 30.0 # extended gap when sequence-calibrated Re-ID confirms identity
|
|
25
|
+
_INTERP_ENDPOINT_CONF = 0.25
|
|
26
|
+
_INTERP_SUPPORT_CONF = 0.40 # mean confidence of the support observations on each side
|
|
27
|
+
_INTERP_SUPPORT_WINDOW = 5
|
|
28
|
+
_INTERP_MIN_SUPPORT = 3
|
|
29
|
+
_INTERP_TRAVEL_BASE = 0.5 # camera-compensated centre travel, box heights
|
|
30
|
+
_INTERP_TRAVEL_PER_FRAME = 0.08
|
|
31
|
+
_INTERP_MAX_BIDIR = 0.80 # forward/backward extrapolation disagreement at midpoint, box heights
|
|
32
|
+
_INTERP_REID_EXT_BIDIR = 0.65 # tighter kinematic consistency required for extended Re-ID gaps
|
|
33
|
+
_INTERP_MAX_HEIGHT_RATIO = 1.6
|
|
34
|
+
_INTERP_MIN_COS = 0.5
|
|
35
|
+
_INTERP_CONF_DECAY = 0.9
|
|
36
|
+
# Stage 1 within-track appearance bisection: min clean observations per side, local window,
|
|
37
|
+
# recursion depth, and required calibrated appearance distance (global and local contrast).
|
|
38
|
+
_BIS_MIN = 15
|
|
39
|
+
_BIS_WIN = 15
|
|
40
|
+
_BIS_DEPTH = 2
|
|
41
|
+
_BIS_GLOBAL = 0.85
|
|
42
|
+
_BIS_LOCAL = 0.85
|
|
43
|
+
# A trusted-Re-ID link must be within this cosine of the best candidate of its source and target.
|
|
44
|
+
_MUTUAL_COS_TOL = 0.04
|
|
45
|
+
# Stage 4 image-space smoothing: adaptive two-scale Gaussian (seconds), max accepted shift (box heights).
|
|
46
|
+
_SMOOTH_SIGMA_LO_S = 1.0 / 30.0
|
|
47
|
+
_SMOOTH_SIGMA_HI_S = 4.2 / 30.0
|
|
48
|
+
_SMOOTH_MIN_FPS = 6.0
|
|
49
|
+
_SMOOTH_V_SCALE = 0.65 # max box-edge speed (box-heights/s) for strong smoothing
|
|
50
|
+
_SMOOTH_D_SCALE = 0.0150 # 4-edge multi-scale discrepancy (box heights) for strong smoothing
|
|
51
|
+
_SMOOTH_GATE = 0.15
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass
|
|
55
|
+
class _Tracklet:
|
|
56
|
+
"""Internal representation of a single contiguous tracklet segment."""
|
|
57
|
+
|
|
58
|
+
idx: int
|
|
59
|
+
raw_id: int
|
|
60
|
+
part_id: int
|
|
61
|
+
class_id: int
|
|
62
|
+
row_indices: np.ndarray # indices into input `rows` (sorted by frame_idx)
|
|
63
|
+
frames: np.ndarray # int64 (L,)
|
|
64
|
+
boxes: np.ndarray # float64 (L, 4) xyxy
|
|
65
|
+
confs: np.ndarray # float64 (L,)
|
|
66
|
+
ioa: np.ndarray # float64 (L,) max IoA with other tracks in same frame
|
|
67
|
+
iou: np.ndarray # float64 (L,) max IoU with other tracks in same frame
|
|
68
|
+
start_frame: int
|
|
69
|
+
end_frame: int
|
|
70
|
+
# Precomputed boundary states in their own boundary frame coordinates (start_frame / end_frame)
|
|
71
|
+
p_start: np.ndarray # float64 (2,)
|
|
72
|
+
v_start: np.ndarray # float64 (2,) px/frame in start_frame coords
|
|
73
|
+
h_start: float
|
|
74
|
+
n_start: int
|
|
75
|
+
p_end: np.ndarray # float64 (2,)
|
|
76
|
+
v_end: np.ndarray # float64 (2,) px/frame in end_frame coords
|
|
77
|
+
h_end: float
|
|
78
|
+
n_end: int
|
|
79
|
+
emb_full: np.ndarray | None = None
|
|
80
|
+
n_emb: int = 0
|
|
81
|
+
# Continuity prior with the immediately following split sibling (if any)
|
|
82
|
+
next_sibling_idx: int = -1
|
|
83
|
+
next_sibling_bonus: float = 0.0
|
|
84
|
+
next_sibling_soft: bool = False
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _l2_norm_vec(v: np.ndarray) -> np.ndarray | None:
|
|
88
|
+
n = float(np.linalg.norm(v))
|
|
89
|
+
if not np.isfinite(n) or n <= 1e-8:
|
|
90
|
+
return None
|
|
91
|
+
return (v / n).astype(np.float32, copy=False)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _compute_cumulative_cmc(
|
|
95
|
+
num_frames: int,
|
|
96
|
+
cmc_warps: np.ndarray | None,
|
|
97
|
+
cmc_valid: np.ndarray | None,
|
|
98
|
+
frame_width: int | None,
|
|
99
|
+
frame_height: int | None,
|
|
100
|
+
) -> tuple[np.ndarray, np.ndarray, bool]:
|
|
101
|
+
"""Build cumulative 3x3 homogeneous transforms W[f] mapping frame 0 -> frame f."""
|
|
102
|
+
if cmc_warps is None or len(cmc_warps) == 0:
|
|
103
|
+
empty = np.zeros((0, 3, 3), dtype=np.float64)
|
|
104
|
+
return empty, empty, False
|
|
105
|
+
|
|
106
|
+
T = max(num_frames, 1)
|
|
107
|
+
W = np.broadcast_to(np.eye(3, dtype=np.float64), (T, 3, 3)).copy()
|
|
108
|
+
|
|
109
|
+
max_shift = float(max(frame_width or 1920, frame_height or 1080)) * 0.45
|
|
110
|
+
n_w = min(T, len(cmc_warps))
|
|
111
|
+
has_valid = cmc_valid is not None
|
|
112
|
+
any_applied = False
|
|
113
|
+
for f in range(1, T):
|
|
114
|
+
if f < n_w and (not has_valid or bool(cmc_valid[f])):
|
|
115
|
+
w = cmc_warps[f]
|
|
116
|
+
if w.shape == (2, 3) and np.isfinite(w).all():
|
|
117
|
+
det = float(w[0, 0] * w[1, 1] - w[0, 1] * w[1, 0])
|
|
118
|
+
shift = float(np.hypot(w[0, 2], w[1, 2]))
|
|
119
|
+
if 0.85 <= det <= 1.15 and shift <= max_shift:
|
|
120
|
+
A = np.eye(3, dtype=np.float64)
|
|
121
|
+
A[:2, :] = w
|
|
122
|
+
W[f] = A @ W[f - 1]
|
|
123
|
+
any_applied = True
|
|
124
|
+
continue
|
|
125
|
+
W[f] = W[f - 1]
|
|
126
|
+
|
|
127
|
+
if not any_applied:
|
|
128
|
+
empty = np.zeros((0, 3, 3), dtype=np.float64)
|
|
129
|
+
return empty, empty, False
|
|
130
|
+
|
|
131
|
+
W_inv = np.broadcast_to(np.eye(3, dtype=np.float64), (T, 3, 3)).copy()
|
|
132
|
+
a = W[:, 0, 0]
|
|
133
|
+
b = W[:, 0, 1]
|
|
134
|
+
c = W[:, 1, 0]
|
|
135
|
+
d = W[:, 1, 1]
|
|
136
|
+
tx = W[:, 0, 2]
|
|
137
|
+
ty = W[:, 1, 2]
|
|
138
|
+
det = a * d - b * c
|
|
139
|
+
safe = np.abs(det) > 1e-9
|
|
140
|
+
inv_det = np.where(safe, 1.0 / np.where(safe, det, 1.0), 0.0)
|
|
141
|
+
ia = d * inv_det
|
|
142
|
+
ib = -b * inv_det
|
|
143
|
+
ic = -c * inv_det
|
|
144
|
+
id_ = a * inv_det
|
|
145
|
+
W_inv[safe, 0, 0] = ia[safe]
|
|
146
|
+
W_inv[safe, 0, 1] = ib[safe]
|
|
147
|
+
W_inv[safe, 1, 0] = ic[safe]
|
|
148
|
+
W_inv[safe, 1, 1] = id_[safe]
|
|
149
|
+
W_inv[safe, 0, 2] = -(ia[safe] * tx[safe] + ib[safe] * ty[safe])
|
|
150
|
+
W_inv[safe, 1, 2] = -(ic[safe] * tx[safe] + id_[safe] * ty[safe])
|
|
151
|
+
return W, W_inv, True
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _warp_points(
|
|
155
|
+
cx: np.ndarray,
|
|
156
|
+
cy: np.ndarray,
|
|
157
|
+
frames: np.ndarray,
|
|
158
|
+
f_ref: int,
|
|
159
|
+
W: np.ndarray,
|
|
160
|
+
W_inv: np.ndarray,
|
|
161
|
+
use_cmc: bool,
|
|
162
|
+
) -> np.ndarray:
|
|
163
|
+
"""Warp 2D points observed at `frames` into the coordinate frame `f_ref`."""
|
|
164
|
+
n = len(frames)
|
|
165
|
+
if not use_cmc or n == 0:
|
|
166
|
+
return np.column_stack((cx, cy))
|
|
167
|
+
Mref = W[f_ref]
|
|
168
|
+
Ms = Mref[None, :, :] @ W_inv[frames]
|
|
169
|
+
px = Ms[:, 0, 0] * cx + Ms[:, 0, 1] * cy + Ms[:, 0, 2]
|
|
170
|
+
py = Ms[:, 1, 0] * cx + Ms[:, 1, 1] * cy + Ms[:, 1, 2]
|
|
171
|
+
return np.column_stack((px, py))
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _compute_frame_overlaps(
|
|
175
|
+
frames: np.ndarray,
|
|
176
|
+
tids: np.ndarray,
|
|
177
|
+
boxes: np.ndarray,
|
|
178
|
+
) -> tuple[np.ndarray, np.ndarray, dict[tuple[int, int], list[tuple[int, float]]]]:
|
|
179
|
+
"""Compute per-observation max IoA, max IoU, and pairwise overlap frames (IoU >= 0.20)."""
|
|
180
|
+
native = native_module()
|
|
181
|
+
if native is not None:
|
|
182
|
+
return native.compute_frame_overlaps(frames, tids, boxes)
|
|
183
|
+
n = len(frames)
|
|
184
|
+
max_ioa = np.zeros(n, dtype=np.float64)
|
|
185
|
+
max_iou = np.zeros(n, dtype=np.float64)
|
|
186
|
+
pair_overlaps: dict[tuple[int, int], list[tuple[int, float]]] = {}
|
|
187
|
+
|
|
188
|
+
order = np.argsort(frames, kind="mergesort")
|
|
189
|
+
f_sorted = frames[order]
|
|
190
|
+
u_frames, starts, counts = np.unique(f_sorted, return_index=True, return_counts=True)
|
|
191
|
+
|
|
192
|
+
for fr, s, c in zip(u_frames, starts, counts, strict=True):
|
|
193
|
+
if c < 2:
|
|
194
|
+
continue
|
|
195
|
+
idxs = order[s : s + c]
|
|
196
|
+
b = boxes[idxs]
|
|
197
|
+
x1 = np.maximum(b[:, None, 0], b[None, :, 0])
|
|
198
|
+
y1 = np.maximum(b[:, None, 1], b[None, :, 1])
|
|
199
|
+
x2 = np.minimum(b[:, None, 2], b[None, :, 2])
|
|
200
|
+
y2 = np.minimum(b[:, None, 3], b[None, :, 3])
|
|
201
|
+
inter = np.maximum(0.0, x2 - x1) * np.maximum(0.0, y2 - y1)
|
|
202
|
+
areas = np.maximum(1e-9, (b[:, 2] - b[:, 0]) * (b[:, 3] - b[:, 1]))
|
|
203
|
+
ioa_m = inter / areas[:, None]
|
|
204
|
+
iou_m = inter / np.maximum(areas[:, None] + areas[None, :] - inter, 1e-9)
|
|
205
|
+
np.fill_diagonal(ioa_m, 0.0)
|
|
206
|
+
np.fill_diagonal(iou_m, 0.0)
|
|
207
|
+
max_ioa[idxs] = ioa_m.max(axis=1)
|
|
208
|
+
max_iou[idxs] = iou_m.max(axis=1)
|
|
209
|
+
|
|
210
|
+
ii, jj = np.where(np.triu(iou_m, k=1) >= 0.20)
|
|
211
|
+
fr_i = int(fr)
|
|
212
|
+
for a, b_i in zip(ii.tolist(), jj.tolist(), strict=True):
|
|
213
|
+
ta = int(tids[idxs[a]])
|
|
214
|
+
tb = int(tids[idxs[b_i]])
|
|
215
|
+
if ta == tb:
|
|
216
|
+
continue
|
|
217
|
+
key = (ta, tb) if ta < tb else (tb, ta)
|
|
218
|
+
pair_overlaps.setdefault(key, []).append((fr_i, float(iou_m[a, b_i])))
|
|
219
|
+
|
|
220
|
+
return max_ioa, max_iou, pair_overlaps
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _clean_prototype(
|
|
224
|
+
row_indices: np.ndarray,
|
|
225
|
+
confs: np.ndarray,
|
|
226
|
+
ioa: np.ndarray,
|
|
227
|
+
embeddings: np.ndarray | None,
|
|
228
|
+
emb_valid: np.ndarray | None,
|
|
229
|
+
) -> tuple[np.ndarray | None, int]:
|
|
230
|
+
"""Compute occlusion-downweighted, confidence-weighted L2-normalized mean embedding."""
|
|
231
|
+
if embeddings is None or emb_valid is None or len(row_indices) == 0:
|
|
232
|
+
return None, 0
|
|
233
|
+
valid_mask = emb_valid[row_indices]
|
|
234
|
+
n_valid = int(valid_mask.sum())
|
|
235
|
+
if n_valid == 0:
|
|
236
|
+
return None, 0
|
|
237
|
+
sel_rows = row_indices[valid_mask]
|
|
238
|
+
sel_ioa = ioa[valid_mask]
|
|
239
|
+
sel_conf = confs[valid_mask]
|
|
240
|
+
embs = embeddings[sel_rows].astype(np.float32, copy=False)
|
|
241
|
+
|
|
242
|
+
unocc = sel_ioa < 0.15
|
|
243
|
+
if int(unocc.sum()) >= 2:
|
|
244
|
+
w = np.where(unocc, np.clip(sel_conf, 0.2, 1.0), 0.05 * np.clip(sel_conf, 0.2, 1.0))
|
|
245
|
+
else:
|
|
246
|
+
w = np.clip(sel_conf, 0.2, 1.0) * np.square(1.0 - np.clip(sel_ioa, 0.0, 0.90))
|
|
247
|
+
mean_v = np.sum(embs * w[:, None].astype(np.float32), axis=0)
|
|
248
|
+
return _l2_norm_vec(mean_v), n_valid
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _calibrate_reid(
|
|
252
|
+
raw_tracks: dict[int, np.ndarray],
|
|
253
|
+
frames: np.ndarray,
|
|
254
|
+
confs: np.ndarray,
|
|
255
|
+
max_ioa: np.ndarray,
|
|
256
|
+
embeddings: np.ndarray | None,
|
|
257
|
+
emb_valid: np.ndarray | None,
|
|
258
|
+
) -> tuple[float, float, float, float]:
|
|
259
|
+
"""Estimate (reid_trust, mu_same, p50_diff, p70_diff) from concurrent vs within-track cosines."""
|
|
260
|
+
if embeddings is None or emb_valid is None or not emb_valid.any():
|
|
261
|
+
return 0.0, 0.88, 0.88, 0.88
|
|
262
|
+
|
|
263
|
+
spans: list[tuple[int, int]] = []
|
|
264
|
+
protos: list[np.ndarray] = []
|
|
265
|
+
same_cos: list[float] = []
|
|
266
|
+
|
|
267
|
+
for idxs in raw_tracks.values():
|
|
268
|
+
v_mask = emb_valid[idxs]
|
|
269
|
+
if int(v_mask.sum()) < 3:
|
|
270
|
+
continue
|
|
271
|
+
proto, n_emb = _clean_prototype(idxs, confs[idxs], max_ioa[idxs], embeddings, emb_valid)
|
|
272
|
+
if proto is None:
|
|
273
|
+
continue
|
|
274
|
+
spans.append((int(frames[idxs[0]]), int(frames[idxs[-1]])))
|
|
275
|
+
protos.append(proto)
|
|
276
|
+
|
|
277
|
+
if n_emb >= 10:
|
|
278
|
+
v_idxs = idxs[v_mask]
|
|
279
|
+
clean_v = v_idxs[max_ioa[v_idxs] < 0.20]
|
|
280
|
+
if len(clean_v) < 8:
|
|
281
|
+
clean_v = v_idxs
|
|
282
|
+
q = max(2, len(clean_v) // 3)
|
|
283
|
+
e1 = _l2_norm_vec(embeddings[clean_v[:q]].astype(np.float32).mean(axis=0))
|
|
284
|
+
e2 = _l2_norm_vec(embeddings[clean_v[-q:]].astype(np.float32).mean(axis=0))
|
|
285
|
+
if e1 is not None and e2 is not None:
|
|
286
|
+
same_cos.append(float(np.dot(e1, e2)))
|
|
287
|
+
|
|
288
|
+
if len(protos) < 2:
|
|
289
|
+
return 0.0, 0.88, 0.88, 0.88
|
|
290
|
+
|
|
291
|
+
P = np.stack(protos, axis=0)
|
|
292
|
+
sim = P @ P.T
|
|
293
|
+
diff_cos: list[float] = []
|
|
294
|
+
n_t = len(protos)
|
|
295
|
+
for i in range(n_t):
|
|
296
|
+
s0, e0 = spans[i]
|
|
297
|
+
for j in range(i + 1, n_t):
|
|
298
|
+
s1, e1 = spans[j]
|
|
299
|
+
if min(e0, e1) - max(s0, s1) + 1 >= 5:
|
|
300
|
+
diff_cos.append(float(sim[i, j]))
|
|
301
|
+
|
|
302
|
+
if len(diff_cos) < 3:
|
|
303
|
+
tri = sim[np.triu_indices(n_t, k=1)]
|
|
304
|
+
if len(tri) == 0:
|
|
305
|
+
return 0.0, 0.88, 0.88, 0.88
|
|
306
|
+
diff_arr = tri
|
|
307
|
+
else:
|
|
308
|
+
diff_arr = np.asarray(diff_cos, dtype=np.float64)
|
|
309
|
+
|
|
310
|
+
p50_diff = float(np.percentile(diff_arr, 50))
|
|
311
|
+
p70_diff = float(np.percentile(diff_arr, 70))
|
|
312
|
+
mu_same = float(np.median(same_cos)) if len(same_cos) >= 3 else 0.88
|
|
313
|
+
mu_same = max(mu_same, 0.78)
|
|
314
|
+
|
|
315
|
+
# Calibrate against the look-alike upper tail (p70_diff) and median (p50_diff):
|
|
316
|
+
# uniform-costume scenes drop cleanly to trust=0; multi-appearance & sports scenes -> 0.7..1.0.
|
|
317
|
+
sep_tail = mu_same - p70_diff
|
|
318
|
+
sep_med = mu_same - p50_diff
|
|
319
|
+
trust_tail = float(np.clip((sep_tail - 0.03) / 0.11, 0.0, 1.0))
|
|
320
|
+
trust_med = float(np.clip((sep_med - 0.09) / 0.14, 0.0, 1.0))
|
|
321
|
+
reid_trust = min(trust_tail, trust_med)
|
|
322
|
+
return reid_trust, mu_same, p50_diff, p70_diff
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def _fit_edge_state(
|
|
326
|
+
frames: np.ndarray,
|
|
327
|
+
boxes: np.ndarray,
|
|
328
|
+
ioa: np.ndarray,
|
|
329
|
+
W: np.ndarray,
|
|
330
|
+
W_inv: np.ndarray,
|
|
331
|
+
use_cmc: bool,
|
|
332
|
+
f_ref: int,
|
|
333
|
+
*,
|
|
334
|
+
from_end: bool,
|
|
335
|
+
win: int = 12,
|
|
336
|
+
) -> tuple[np.ndarray, np.ndarray, float, int]:
|
|
337
|
+
"""Fit weighted linear position & velocity at tracklet boundary in frame `f_ref`."""
|
|
338
|
+
L = len(frames)
|
|
339
|
+
if from_end:
|
|
340
|
+
sel = slice(max(0, L - win), L)
|
|
341
|
+
f_edge = int(frames[-1])
|
|
342
|
+
else:
|
|
343
|
+
sel = slice(0, min(L, win))
|
|
344
|
+
f_edge = int(frames[0])
|
|
345
|
+
|
|
346
|
+
fs = frames[sel]
|
|
347
|
+
bs = boxes[sel]
|
|
348
|
+
ios = ioa[sel]
|
|
349
|
+
cx = 0.5 * (bs[:, 0] + bs[:, 2])
|
|
350
|
+
cy = 0.5 * (bs[:, 1] + bs[:, 3])
|
|
351
|
+
hs = bs[:, 3] - bs[:, 1]
|
|
352
|
+
h = max(float(np.median(hs)) if len(hs) > 0 else 1.0, 8.0)
|
|
353
|
+
|
|
354
|
+
pts = _warp_points(cx, cy, fs, f_ref, W, W_inv, use_cmc)
|
|
355
|
+
edge_pt = pts[-1] if from_end else pts[0]
|
|
356
|
+
if len(fs) < 2 or int(fs[-1]) == int(fs[0]):
|
|
357
|
+
return edge_pt, np.zeros(2, dtype=np.float64), h, 1
|
|
358
|
+
|
|
359
|
+
t = (fs - f_edge).astype(np.float64)
|
|
360
|
+
w_time = np.exp(-np.abs(t) / 6.0)
|
|
361
|
+
w_occ = np.where(ios < 0.25, 1.0, 0.20)
|
|
362
|
+
w = w_time * w_occ
|
|
363
|
+
sw = float(np.sum(w))
|
|
364
|
+
if sw <= 1e-8:
|
|
365
|
+
return edge_pt, np.zeros(2, dtype=np.float64), h, len(fs)
|
|
366
|
+
|
|
367
|
+
mt = float(np.sum(w * t)) / sw
|
|
368
|
+
dt = t - mt
|
|
369
|
+
var_t = float(np.sum(w * dt * dt))
|
|
370
|
+
if var_t < 0.25:
|
|
371
|
+
return edge_pt, np.zeros(2, dtype=np.float64), h, len(fs)
|
|
372
|
+
|
|
373
|
+
mp = np.sum(w[:, None] * pts, axis=0) / sw
|
|
374
|
+
vel = np.sum((w * dt)[:, None] * (pts - mp), axis=0) / var_t
|
|
375
|
+
|
|
376
|
+
damp = min(1.0, (len(fs) - 1) / 4.0)
|
|
377
|
+
vel = vel * damp
|
|
378
|
+
speed = float(np.hypot(vel[0], vel[1]))
|
|
379
|
+
max_speed = 0.65 * h
|
|
380
|
+
if speed > max_speed:
|
|
381
|
+
vel = vel * (max_speed / speed)
|
|
382
|
+
|
|
383
|
+
pos_fit = mp - vel * mt
|
|
384
|
+
edge_ioa = float(ios[-1] if from_end else ios[0])
|
|
385
|
+
if edge_ioa >= 0.25 and len(fs) >= 4:
|
|
386
|
+
pos = 0.7 * pos_fit + 0.3 * edge_pt
|
|
387
|
+
else:
|
|
388
|
+
pos = 0.35 * pos_fit + 0.65 * edge_pt
|
|
389
|
+
return pos, vel, h, len(fs)
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def _make_tracklet(
|
|
393
|
+
idx: int,
|
|
394
|
+
raw_id: int,
|
|
395
|
+
part_id: int,
|
|
396
|
+
class_id: int,
|
|
397
|
+
seg_idxs: np.ndarray,
|
|
398
|
+
frames: np.ndarray,
|
|
399
|
+
boxes: np.ndarray,
|
|
400
|
+
confs: np.ndarray,
|
|
401
|
+
max_ioa: np.ndarray,
|
|
402
|
+
max_iou: np.ndarray,
|
|
403
|
+
W: np.ndarray,
|
|
404
|
+
W_inv: np.ndarray,
|
|
405
|
+
use_cmc: bool,
|
|
406
|
+
embeddings: np.ndarray | None,
|
|
407
|
+
emb_valid: np.ndarray | None,
|
|
408
|
+
) -> _Tracklet:
|
|
409
|
+
"""Construct a _Tracklet with precomputed head/tail CMC edge states and clean prototype."""
|
|
410
|
+
seg_f = frames[seg_idxs]
|
|
411
|
+
seg_b = boxes[seg_idxs]
|
|
412
|
+
seg_c = confs[seg_idxs]
|
|
413
|
+
seg_ioa = max_ioa[seg_idxs]
|
|
414
|
+
seg_iou = max_iou[seg_idxs]
|
|
415
|
+
f_start = int(seg_f[0])
|
|
416
|
+
f_end = int(seg_f[-1])
|
|
417
|
+
p_s, v_s, h_s, n_s = _fit_edge_state(
|
|
418
|
+
seg_f, seg_b, seg_ioa, W, W_inv, use_cmc, f_start, from_end=False, win=12
|
|
419
|
+
)
|
|
420
|
+
p_e, v_e, h_e, n_e = _fit_edge_state(
|
|
421
|
+
seg_f, seg_b, seg_ioa, W, W_inv, use_cmc, f_end, from_end=True, win=12
|
|
422
|
+
)
|
|
423
|
+
emb, n_emb = _clean_prototype(seg_idxs, seg_c, seg_ioa, embeddings, emb_valid)
|
|
424
|
+
return _Tracklet(
|
|
425
|
+
idx=idx,
|
|
426
|
+
raw_id=raw_id,
|
|
427
|
+
part_id=part_id,
|
|
428
|
+
class_id=class_id,
|
|
429
|
+
row_indices=seg_idxs,
|
|
430
|
+
frames=seg_f,
|
|
431
|
+
boxes=seg_b,
|
|
432
|
+
confs=seg_c,
|
|
433
|
+
ioa=seg_ioa,
|
|
434
|
+
iou=seg_iou,
|
|
435
|
+
start_frame=f_start,
|
|
436
|
+
end_frame=f_end,
|
|
437
|
+
p_start=p_s,
|
|
438
|
+
v_start=v_s,
|
|
439
|
+
h_start=h_s,
|
|
440
|
+
n_start=n_s,
|
|
441
|
+
p_end=p_e,
|
|
442
|
+
v_end=v_e,
|
|
443
|
+
h_end=h_e,
|
|
444
|
+
n_end=n_e,
|
|
445
|
+
emb_full=emb,
|
|
446
|
+
n_emb=n_emb,
|
|
447
|
+
)
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
def _appearance_bisect(
|
|
451
|
+
idxs: np.ndarray,
|
|
452
|
+
max_ioa: np.ndarray,
|
|
453
|
+
max_iou: np.ndarray,
|
|
454
|
+
embeddings: np.ndarray,
|
|
455
|
+
emb_valid: np.ndarray,
|
|
456
|
+
mu_same: float,
|
|
457
|
+
sep_tail: float,
|
|
458
|
+
) -> list[int]:
|
|
459
|
+
"""Split points (observation positions in `idxs`) where clean appearance changes abruptly.
|
|
460
|
+
|
|
461
|
+
The clean (unoccluded) embeddings of a track are cut at the point that minimises the cosine
|
|
462
|
+
between the pre- and post-cut mean embeddings. A cut is kept when that global contrast and a
|
|
463
|
+
local window contrast around it are both far below the sequence's same-identity similarity;
|
|
464
|
+
each accepted side is bisected again up to `_BIS_DEPTH` levels.
|
|
465
|
+
"""
|
|
466
|
+
clean = np.nonzero(emb_valid[idxs] & (max_ioa[idxs] < 0.20))[0]
|
|
467
|
+
m = _BIS_MIN
|
|
468
|
+
if len(clean) < 2 * m:
|
|
469
|
+
return []
|
|
470
|
+
E = embeddings[idxs[clean]].astype(np.float32)
|
|
471
|
+
E /= np.maximum(np.linalg.norm(E, axis=1, keepdims=True), 1e-12)
|
|
472
|
+
cuts: list[int] = []
|
|
473
|
+
|
|
474
|
+
def _rec(lo: int, hi: int, depth: int) -> None:
|
|
475
|
+
n = hi - lo
|
|
476
|
+
if depth >= _BIS_DEPTH or n < 2 * m:
|
|
477
|
+
return
|
|
478
|
+
c = np.arange(m - 1, n - m)
|
|
479
|
+
pre = np.cumsum(E[lo:hi], axis=0)[c].astype(np.float64)
|
|
480
|
+
total = E[lo:hi].sum(axis=0, dtype=np.float64)
|
|
481
|
+
pre_sq = np.einsum("ij,ij->i", pre, pre)
|
|
482
|
+
pre_tot = pre @ total
|
|
483
|
+
post_sq = np.maximum(float(total @ total) - 2.0 * pre_tot + pre_sq, 1e-12)
|
|
484
|
+
cos = (pre_tot - pre_sq) / np.sqrt(np.maximum(pre_sq, 1e-12) * post_sq)
|
|
485
|
+
b = int(np.argmin(cos))
|
|
486
|
+
if (mu_same - float(cos[b])) / sep_tail < _BIS_GLOBAL:
|
|
487
|
+
return
|
|
488
|
+
cut = lo + int(c[b]) + 1 # first clean position of the post side
|
|
489
|
+
w = _BIS_WIN
|
|
490
|
+
e_pre = E[max(lo, cut - w) : cut].mean(axis=0)
|
|
491
|
+
e_post = E[cut : min(hi, cut + w)].mean(axis=0)
|
|
492
|
+
cos_loc = float(e_pre @ e_post) / max(
|
|
493
|
+
float(np.linalg.norm(e_pre) * np.linalg.norm(e_post)), 1e-12
|
|
494
|
+
)
|
|
495
|
+
if (mu_same - cos_loc) / sep_tail < _BIS_LOCAL:
|
|
496
|
+
return
|
|
497
|
+
# Place the cut at the most overlapped observation between the two clean samples.
|
|
498
|
+
a = int(clean[cut - 1])
|
|
499
|
+
k = int(clean[cut])
|
|
500
|
+
if k > a + 1:
|
|
501
|
+
k = a + 2 + int(np.argmax(max_iou[idxs[a + 1 : k]]))
|
|
502
|
+
cuts.append(k)
|
|
503
|
+
_rec(lo, cut, depth + 1)
|
|
504
|
+
_rec(cut, hi, depth + 1)
|
|
505
|
+
|
|
506
|
+
_rec(0, len(clean), 0)
|
|
507
|
+
return cuts
|
|
508
|
+
|
|
509
|
+
|
|
510
|
+
def _detect_split_points(
|
|
511
|
+
raw_tracks: dict[int, np.ndarray],
|
|
512
|
+
frames: np.ndarray,
|
|
513
|
+
boxes: np.ndarray,
|
|
514
|
+
confs: np.ndarray,
|
|
515
|
+
max_ioa: np.ndarray,
|
|
516
|
+
max_iou: np.ndarray,
|
|
517
|
+
pair_overlaps: dict[tuple[int, int], list[tuple[int, float]]],
|
|
518
|
+
W: np.ndarray,
|
|
519
|
+
W_inv: np.ndarray,
|
|
520
|
+
use_cmc: bool,
|
|
521
|
+
embeddings: np.ndarray | None,
|
|
522
|
+
emb_valid: np.ndarray | None,
|
|
523
|
+
reid_trust: float,
|
|
524
|
+
mu_same: float,
|
|
525
|
+
p70_diff: float,
|
|
526
|
+
crossing_swaps: list[tuple[float, int, int]],
|
|
527
|
+
*,
|
|
528
|
+
class_ids: np.ndarray | None = None,
|
|
529
|
+
frame_stride: int,
|
|
530
|
+
fps: float,
|
|
531
|
+
) -> dict[int, list[tuple[int, float, bool]]]:
|
|
532
|
+
"""Return per-raw-track list of (split_k, continuity_bonus, is_soft_split)."""
|
|
533
|
+
splits: dict[int, dict[int, tuple[float, bool]]] = {}
|
|
534
|
+
sep_tail = max(mu_same - p70_diff, 0.08)
|
|
535
|
+
stride = max(1, int(frame_stride))
|
|
536
|
+
# Stronger continuity prior when appearance cannot verify junction/crossing re-wirings
|
|
537
|
+
b_junc = 0.20 * (1.0 - reid_trust) + 0.12 * reid_trust
|
|
538
|
+
b_cross = b_junc + 0.02
|
|
539
|
+
|
|
540
|
+
def _add_split(
|
|
541
|
+
tid: int, k: int, bonus: float, is_soft: bool, length: int, min_side: int = 3
|
|
542
|
+
) -> None:
|
|
543
|
+
if k < min_side or length - k < min_side:
|
|
544
|
+
return
|
|
545
|
+
d = splits.setdefault(tid, {})
|
|
546
|
+
prev = d.get(k)
|
|
547
|
+
if prev is None:
|
|
548
|
+
d[k] = (bonus, is_soft)
|
|
549
|
+
else:
|
|
550
|
+
prev_b, prev_soft = prev
|
|
551
|
+
if (not is_soft and prev_soft) or (is_soft == prev_soft and bonus < prev_b):
|
|
552
|
+
d[k] = (bonus, is_soft)
|
|
553
|
+
|
|
554
|
+
spans: dict[int, tuple[int, int, int]] = {
|
|
555
|
+
tid: (int(frames[idxs[0]]), int(frames[idxs[-1]]), len(idxs))
|
|
556
|
+
for tid, idxs in raw_tracks.items()
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
# --- Trigger A: Suspect internal gaps ---
|
|
560
|
+
for tid, idxs in raw_tracks.items():
|
|
561
|
+
L = len(idxs)
|
|
562
|
+
if L < 4:
|
|
563
|
+
continue
|
|
564
|
+
fs = frames[idxs]
|
|
565
|
+
bs = boxes[idxs]
|
|
566
|
+
ioas = max_ioa[idxs]
|
|
567
|
+
ious = max_iou[idxs]
|
|
568
|
+
cs = confs[idxs]
|
|
569
|
+
|
|
570
|
+
diffs = np.diff(fs)
|
|
571
|
+
gap_ks = np.where(diffs >= 2 * stride)[0] + 1
|
|
572
|
+
for k_val in gap_ks.tolist():
|
|
573
|
+
if k_val < 2 or L - k_val < 2:
|
|
574
|
+
continue
|
|
575
|
+
df = int(fs[k_val] - fs[k_val - 1])
|
|
576
|
+
f0 = int(fs[k_val - 1])
|
|
577
|
+
f1 = int(fs[k_val])
|
|
578
|
+
f_mid = (f0 + f1) // 2
|
|
579
|
+
|
|
580
|
+
p0, v0, h0, _ = _fit_edge_state(
|
|
581
|
+
fs[:k_val], bs[:k_val], ioas[:k_val], W, W_inv, use_cmc, f_mid, from_end=True, win=10
|
|
582
|
+
)
|
|
583
|
+
p1, v1, h1, _ = _fit_edge_state(
|
|
584
|
+
fs[k_val:], bs[k_val:], ioas[k_val:], W, W_inv, use_cmc, f_mid, from_end=False, win=10
|
|
585
|
+
)
|
|
586
|
+
h = max(12.0, 0.5 * (h0 + h1))
|
|
587
|
+
d_ep = float(np.hypot(p1[0] - p0[0], p1[1] - p0[1])) / h
|
|
588
|
+
tau = (0.5 * float(df)) / (1.0 + (float(df) / max(2.2 * fps, 25.0)) ** 2)
|
|
589
|
+
d_bidir = float(
|
|
590
|
+
np.hypot(
|
|
591
|
+
(p1[0] - v1[0] * tau) - (p0[0] + v0[0] * tau),
|
|
592
|
+
(p1[1] - v1[1] * tau) - (p0[1] + v0[1] * tau),
|
|
593
|
+
)
|
|
594
|
+
) / h
|
|
595
|
+
ov_gap = max(float(ious[k_val - 1]), float(ious[k_val]))
|
|
596
|
+
|
|
597
|
+
app_drop = False
|
|
598
|
+
if reid_trust >= 0.45 and embeddings is not None and emb_valid is not None:
|
|
599
|
+
pre_sl = slice(max(0, k_val - 14), k_val)
|
|
600
|
+
post_sl = slice(k_val, min(L, k_val + 14))
|
|
601
|
+
e_pre, n_pre = _clean_prototype(
|
|
602
|
+
idxs[pre_sl], cs[pre_sl], ioas[pre_sl], embeddings, emb_valid
|
|
603
|
+
)
|
|
604
|
+
e_post, n_post = _clean_prototype(
|
|
605
|
+
idxs[post_sl], cs[post_sl], ioas[post_sl], embeddings, emb_valid
|
|
606
|
+
)
|
|
607
|
+
if e_pre is not None and e_post is not None and n_pre >= 2 and n_post >= 2:
|
|
608
|
+
cos_g = float(np.dot(e_pre, e_post))
|
|
609
|
+
app_dist = (mu_same - cos_g) / sep_tail
|
|
610
|
+
if app_dist >= 0.85 and cos_g < mu_same - 0.08:
|
|
611
|
+
app_drop = True
|
|
612
|
+
|
|
613
|
+
# Clear kinematic breaks across a gap are switches; short gaps need a larger break.
|
|
614
|
+
d_break = min(d_bidir, d_ep)
|
|
615
|
+
extreme_teleport = d_break >= 0.85 or (d_break >= 0.5 and df >= 0.25 * fps)
|
|
616
|
+
if app_drop or extreme_teleport:
|
|
617
|
+
_add_split(tid, k_val, 0.0, False, L, min_side=2)
|
|
618
|
+
elif (d_bidir >= 0.30) or (d_ep >= 0.35 + 0.03 * df):
|
|
619
|
+
_add_split(tid, k_val, 0.04, True, L, min_side=2)
|
|
620
|
+
elif ov_gap >= 0.20 or df >= 3:
|
|
621
|
+
_add_split(tid, k_val, 0.09, True, L, min_side=2)
|
|
622
|
+
|
|
623
|
+
# --- Trigger B & C: Overlap junctions (T/Y birth/death junctions & surviving crossings) ---
|
|
624
|
+
for (ta, tb), evs in pair_overlaps.items():
|
|
625
|
+
if ta not in raw_tracks or tb not in raw_tracks:
|
|
626
|
+
continue
|
|
627
|
+
ia = raw_tracks[ta]
|
|
628
|
+
ib = raw_tracks[tb]
|
|
629
|
+
if class_ids is not None and int(class_ids[ia[0]]) != int(class_ids[ib[0]]):
|
|
630
|
+
continue
|
|
631
|
+
sa0, sa1, la = spans[ta]
|
|
632
|
+
sb0, sb1, lb = spans[tb]
|
|
633
|
+
if la < 4 or lb < 4:
|
|
634
|
+
continue
|
|
635
|
+
|
|
636
|
+
evs.sort(key=lambda x: x[0])
|
|
637
|
+
episodes: list[list[tuple[int, float]]] = [[evs[0]]]
|
|
638
|
+
for item in evs[1:]:
|
|
639
|
+
if item[0] - episodes[-1][-1][0] <= 6 * stride:
|
|
640
|
+
episodes[-1].append(item)
|
|
641
|
+
else:
|
|
642
|
+
episodes.append([item])
|
|
643
|
+
|
|
644
|
+
fa = frames[ia]
|
|
645
|
+
fb = frames[ib]
|
|
646
|
+
|
|
647
|
+
for ep in episodes:
|
|
648
|
+
ts = ep[0][0]
|
|
649
|
+
te = ep[-1][0]
|
|
650
|
+
peak_fr, peak_iou = max(ep, key=lambda x: x[1])
|
|
651
|
+
ep_len = (te - ts) // stride + 1
|
|
652
|
+
|
|
653
|
+
# Trigger B: Track died or started right at this overlap -> soft junction split
|
|
654
|
+
# Only split T/Y junctions when calibrated Re-ID can reliably disambiguate branches.
|
|
655
|
+
if reid_trust >= 0.45:
|
|
656
|
+
if ts - 3 * stride <= sb1 <= te + 4 * stride and sa0 < sb1 < sa1:
|
|
657
|
+
ka = int(np.searchsorted(fa, sb1, side="right"))
|
|
658
|
+
_add_split(ta, ka, b_junc, True, la, min_side=3)
|
|
659
|
+
if ts - 4 * stride <= sb0 <= te + 3 * stride and sa0 < sb0 < sa1:
|
|
660
|
+
ka = int(np.searchsorted(fa, sb0, side="left"))
|
|
661
|
+
_add_split(ta, ka, b_junc, True, la, min_side=3)
|
|
662
|
+
if ts - 3 * stride <= sa1 <= te + 4 * stride and sb0 < sa1 < sb1:
|
|
663
|
+
kb = int(np.searchsorted(fb, sa1, side="right"))
|
|
664
|
+
_add_split(tb, kb, b_junc, True, lb, min_side=3)
|
|
665
|
+
if ts - 4 * stride <= sa0 <= te + 3 * stride and sb0 < sa0 < sb1:
|
|
666
|
+
kb = int(np.searchsorted(fb, sa0, side="left"))
|
|
667
|
+
_add_split(tb, kb, b_junc, True, lb, min_side=3)
|
|
668
|
+
|
|
669
|
+
# Trigger C: Surviving 2-track crossing -> soft split on both at peak IoU
|
|
670
|
+
if (
|
|
671
|
+
ep_len <= 30
|
|
672
|
+
and peak_iou >= 0.30
|
|
673
|
+
and sa0 < ts - 2 * stride
|
|
674
|
+
and sa1 > te + 2 * stride
|
|
675
|
+
and sb0 < ts - 2 * stride
|
|
676
|
+
and sb1 > te + 2 * stride
|
|
677
|
+
):
|
|
678
|
+
# Compare the two possible continuations using motion on either
|
|
679
|
+
# side of the overlap. Both fits use the peak's camera coordinates.
|
|
680
|
+
sides = []
|
|
681
|
+
for ids, fs in ((ia, fa), (ib, fb)):
|
|
682
|
+
pre = ids[np.searchsorted(fs, ts - 12 * stride):np.searchsorted(fs, ts)]
|
|
683
|
+
post = ids[np.searchsorted(fs, te + 1):np.searchsorted(fs, te + 1 + 12 * stride)]
|
|
684
|
+
sides.append((pre[max_iou[pre] < 0.2], post[max_iou[post] < 0.2]))
|
|
685
|
+
if min(len(ids) for pair in sides for ids in pair) < 4:
|
|
686
|
+
continue
|
|
687
|
+
states = []
|
|
688
|
+
for pair in sides:
|
|
689
|
+
track_states = []
|
|
690
|
+
for end, ids in zip((True, False), pair, strict=True):
|
|
691
|
+
pos, vel, h, _ = _fit_edge_state(
|
|
692
|
+
frames[ids], boxes[ids], max_ioa[ids], W, W_inv, use_cmc,
|
|
693
|
+
peak_fr, from_end=end,
|
|
694
|
+
)
|
|
695
|
+
edge = frames[ids[-1 if end else 0]]
|
|
696
|
+
emb, _ = _clean_prototype(ids, confs[ids], max_ioa[ids], embeddings, emb_valid)
|
|
697
|
+
track_states.append((pos, vel, h, edge, emb))
|
|
698
|
+
states.append(track_states)
|
|
699
|
+
|
|
700
|
+
costs = np.empty((2, 2))
|
|
701
|
+
for a in range(2):
|
|
702
|
+
p0, v0, h0, f0, e0 = states[a][0]
|
|
703
|
+
for b in range(2):
|
|
704
|
+
p1, v1, h1, f1, e1 = states[b][1]
|
|
705
|
+
gap = f1 - f0
|
|
706
|
+
delta = p1 - p0
|
|
707
|
+
h = 0.5 * (h0 + h1)
|
|
708
|
+
costs[a, b] = (
|
|
709
|
+
np.linalg.norm(delta - gap * v0) + np.linalg.norm(delta - gap * v1)
|
|
710
|
+
) / (2 * h)
|
|
711
|
+
if e0 is not None and e1 is not None:
|
|
712
|
+
costs[a, b] += reid_trust * (1 - e0 @ e1) / sep_tail
|
|
713
|
+
gain = min(costs[0, 0] - costs[0, 1], costs[1, 1] - costs[1, 0])
|
|
714
|
+
if gain <= 0.08 or max(costs[0, 1], costs[1, 0]) > 1.2:
|
|
715
|
+
continue
|
|
716
|
+
ka = int(np.searchsorted(fa, peak_fr, side="right"))
|
|
717
|
+
kb = int(np.searchsorted(fb, peak_fr, side="right"))
|
|
718
|
+
_add_split(ta, ka, b_cross, True, la, min_side=4)
|
|
719
|
+
_add_split(tb, kb, b_cross, True, lb, min_side=4)
|
|
720
|
+
crossing_swaps.append((gain, int(ia[ka - 1]), int(ib[kb - 1])))
|
|
721
|
+
|
|
722
|
+
# --- Trigger D: Strong calibrated appearance shift across an overlap region ---
|
|
723
|
+
if reid_trust >= 0.50 and embeddings is not None and emb_valid is not None:
|
|
724
|
+
for tid, idxs in raw_tracks.items():
|
|
725
|
+
L = len(idxs)
|
|
726
|
+
if L < 14:
|
|
727
|
+
continue
|
|
728
|
+
ious = max_iou[idxs]
|
|
729
|
+
ov_pos = np.where(ious >= 0.25)[0]
|
|
730
|
+
if len(ov_pos) == 0:
|
|
731
|
+
continue
|
|
732
|
+
runs: list[tuple[int, int]] = []
|
|
733
|
+
r_s = int(ov_pos[0])
|
|
734
|
+
r_e = r_s
|
|
735
|
+
for p in ov_pos[1:].tolist():
|
|
736
|
+
if p <= r_e + 4:
|
|
737
|
+
r_e = p
|
|
738
|
+
else:
|
|
739
|
+
runs.append((r_s, r_e))
|
|
740
|
+
r_s = p
|
|
741
|
+
r_e = p
|
|
742
|
+
runs.append((r_s, r_e))
|
|
743
|
+
|
|
744
|
+
ioas = max_ioa[idxs]
|
|
745
|
+
cs = confs[idxs]
|
|
746
|
+
for r_s, r_e in runs:
|
|
747
|
+
if r_e - r_s > 30 or r_s < 5 or L - 1 - r_e < 5:
|
|
748
|
+
continue
|
|
749
|
+
pre_sl = slice(max(0, r_s - 15), r_s)
|
|
750
|
+
post_sl = slice(r_e + 1, min(L, r_e + 16))
|
|
751
|
+
e_pre, n_pre = _clean_prototype(
|
|
752
|
+
idxs[pre_sl], cs[pre_sl], ioas[pre_sl], embeddings, emb_valid
|
|
753
|
+
)
|
|
754
|
+
e_post, n_post = _clean_prototype(
|
|
755
|
+
idxs[post_sl], cs[post_sl], ioas[post_sl], embeddings, emb_valid
|
|
756
|
+
)
|
|
757
|
+
if e_pre is not None and e_post is not None and n_pre >= 3 and n_post >= 3:
|
|
758
|
+
cos_ov = float(np.dot(e_pre, e_post))
|
|
759
|
+
app_dist = (mu_same - cos_ov) / sep_tail
|
|
760
|
+
if app_dist >= 0.95 and cos_ov < mu_same - 0.09:
|
|
761
|
+
peak_k = r_s + int(np.argmax(ious[r_s : r_e + 1])) + 1
|
|
762
|
+
_add_split(tid, peak_k, 0.0, False, L, min_side=4)
|
|
763
|
+
|
|
764
|
+
# --- Trigger E: Within-track appearance bisection (undetected mid-track switches) ---
|
|
765
|
+
if reid_trust >= 0.50 and embeddings is not None and emb_valid is not None:
|
|
766
|
+
for tid, idxs in raw_tracks.items():
|
|
767
|
+
for k in _appearance_bisect(
|
|
768
|
+
idxs, max_ioa, max_iou, embeddings, emb_valid, mu_same, sep_tail
|
|
769
|
+
):
|
|
770
|
+
_add_split(tid, k, 0.0, False, len(idxs), min_side=4)
|
|
771
|
+
|
|
772
|
+
# Coalesce split points closer than 4 observations on the same track
|
|
773
|
+
out: dict[int, list[tuple[int, float, bool]]] = {}
|
|
774
|
+
for tid, kmap in splits.items():
|
|
775
|
+
items = sorted(kmap.items(), key=lambda x: x[0])
|
|
776
|
+
merged: list[tuple[int, float, bool]] = []
|
|
777
|
+
for k, (b, is_soft) in items:
|
|
778
|
+
if merged and k - merged[-1][0] < 4:
|
|
779
|
+
prev_k, prev_b, prev_soft = merged[-1]
|
|
780
|
+
if (not is_soft and prev_soft) or (is_soft == prev_soft and b < prev_b):
|
|
781
|
+
merged[-1] = (k, b, is_soft)
|
|
782
|
+
else:
|
|
783
|
+
merged.append((k, b, is_soft))
|
|
784
|
+
if merged:
|
|
785
|
+
out[tid] = merged
|
|
786
|
+
return out
|
|
787
|
+
|
|
788
|
+
|
|
789
|
+
def _build_tracklets(
|
|
790
|
+
raw_tracks: dict[int, np.ndarray],
|
|
791
|
+
split_points: dict[int, list[tuple[int, float, bool]]],
|
|
792
|
+
frames: np.ndarray,
|
|
793
|
+
boxes: np.ndarray,
|
|
794
|
+
confs: np.ndarray,
|
|
795
|
+
max_ioa: np.ndarray,
|
|
796
|
+
max_iou: np.ndarray,
|
|
797
|
+
class_ids: np.ndarray | None,
|
|
798
|
+
W: np.ndarray,
|
|
799
|
+
W_inv: np.ndarray,
|
|
800
|
+
use_cmc: bool,
|
|
801
|
+
embeddings: np.ndarray | None,
|
|
802
|
+
emb_valid: np.ndarray | None,
|
|
803
|
+
) -> list[_Tracklet]:
|
|
804
|
+
"""Slice raw tracks at split_points into initial tracklets with precomputed edge states."""
|
|
805
|
+
tracklets: list[_Tracklet] = []
|
|
806
|
+
for tid in sorted(raw_tracks):
|
|
807
|
+
idxs = raw_tracks[tid]
|
|
808
|
+
L = len(idxs)
|
|
809
|
+
cls_id = int(class_ids[idxs[0]]) if class_ids is not None else 0
|
|
810
|
+
spts = split_points.get(tid, [])
|
|
811
|
+
bounds = [0] + [k for k, _, _ in spts] + [L]
|
|
812
|
+
meta_s = [(b, soft) for _, b, soft in spts]
|
|
813
|
+
|
|
814
|
+
first_tidx = len(tracklets)
|
|
815
|
+
for p_i in range(len(bounds) - 1):
|
|
816
|
+
lo, hi = bounds[p_i], bounds[p_i + 1]
|
|
817
|
+
if hi <= lo:
|
|
818
|
+
continue
|
|
819
|
+
tracklets.append(
|
|
820
|
+
_make_tracklet(
|
|
821
|
+
len(tracklets),
|
|
822
|
+
tid,
|
|
823
|
+
p_i,
|
|
824
|
+
cls_id,
|
|
825
|
+
idxs[lo:hi],
|
|
826
|
+
frames,
|
|
827
|
+
boxes,
|
|
828
|
+
confs,
|
|
829
|
+
max_ioa,
|
|
830
|
+
max_iou,
|
|
831
|
+
W,
|
|
832
|
+
W_inv,
|
|
833
|
+
use_cmc,
|
|
834
|
+
embeddings,
|
|
835
|
+
emb_valid,
|
|
836
|
+
)
|
|
837
|
+
)
|
|
838
|
+
n_parts = len(tracklets) - first_tidx
|
|
839
|
+
for p_i in range(n_parts - 1):
|
|
840
|
+
t_cur = tracklets[first_tidx + p_i]
|
|
841
|
+
t_nxt = tracklets[first_tidx + p_i + 1]
|
|
842
|
+
t_cur.next_sibling_idx = t_nxt.idx
|
|
843
|
+
t_cur.next_sibling_bonus = meta_s[p_i][0]
|
|
844
|
+
t_cur.next_sibling_soft = meta_s[p_i][1]
|
|
845
|
+
return tracklets
|
|
846
|
+
|
|
847
|
+
|
|
848
|
+
def _merge_chains(
|
|
849
|
+
tracklets: list[_Tracklet],
|
|
850
|
+
links: dict[int, int],
|
|
851
|
+
frames: np.ndarray,
|
|
852
|
+
boxes: np.ndarray,
|
|
853
|
+
confs: np.ndarray,
|
|
854
|
+
max_ioa: np.ndarray,
|
|
855
|
+
max_iou: np.ndarray,
|
|
856
|
+
W: np.ndarray,
|
|
857
|
+
W_inv: np.ndarray,
|
|
858
|
+
use_cmc: bool,
|
|
859
|
+
embeddings: np.ndarray | None,
|
|
860
|
+
emb_valid: np.ndarray | None,
|
|
861
|
+
) -> list[_Tracklet]:
|
|
862
|
+
"""Merge linked tracklets along directed time-ordered paths into new tracklets."""
|
|
863
|
+
if not links:
|
|
864
|
+
return tracklets
|
|
865
|
+
|
|
866
|
+
has_pred = set(links.values())
|
|
867
|
+
new_tracklets: list[_Tracklet] = []
|
|
868
|
+
visited: set[int] = set()
|
|
869
|
+
|
|
870
|
+
for t in tracklets:
|
|
871
|
+
if t.idx in has_pred or t.idx in visited:
|
|
872
|
+
continue
|
|
873
|
+
chain: list[_Tracklet] = []
|
|
874
|
+
cur: int | None = t.idx
|
|
875
|
+
while cur is not None and cur not in visited:
|
|
876
|
+
visited.add(cur)
|
|
877
|
+
chain.append(tracklets[cur])
|
|
878
|
+
cur = links.get(cur)
|
|
879
|
+
|
|
880
|
+
if len(chain) == 1:
|
|
881
|
+
nt = chain[0]
|
|
882
|
+
nt.idx = len(new_tracklets)
|
|
883
|
+
nt.next_sibling_idx = -1
|
|
884
|
+
nt.next_sibling_bonus = 0.0
|
|
885
|
+
nt.next_sibling_soft = False
|
|
886
|
+
new_tracklets.append(nt)
|
|
887
|
+
continue
|
|
888
|
+
|
|
889
|
+
row_idxs = np.concatenate([c.row_indices for c in chain])
|
|
890
|
+
new_tracklets.append(
|
|
891
|
+
_make_tracklet(
|
|
892
|
+
len(new_tracklets),
|
|
893
|
+
chain[0].raw_id,
|
|
894
|
+
chain[0].part_id,
|
|
895
|
+
chain[0].class_id,
|
|
896
|
+
row_idxs,
|
|
897
|
+
frames,
|
|
898
|
+
boxes,
|
|
899
|
+
confs,
|
|
900
|
+
max_ioa,
|
|
901
|
+
max_iou,
|
|
902
|
+
W,
|
|
903
|
+
W_inv,
|
|
904
|
+
use_cmc,
|
|
905
|
+
embeddings,
|
|
906
|
+
emb_valid,
|
|
907
|
+
)
|
|
908
|
+
)
|
|
909
|
+
|
|
910
|
+
for t in tracklets:
|
|
911
|
+
if t.idx not in visited:
|
|
912
|
+
t.idx = len(new_tracklets)
|
|
913
|
+
t.next_sibling_idx = -1
|
|
914
|
+
t.next_sibling_bonus = 0.0
|
|
915
|
+
t.next_sibling_soft = False
|
|
916
|
+
new_tracklets.append(t)
|
|
917
|
+
|
|
918
|
+
return new_tracklets
|
|
919
|
+
|
|
920
|
+
|
|
921
|
+
def _stitch_pass(
|
|
922
|
+
tracklets: list[_Tracklet],
|
|
923
|
+
W: np.ndarray,
|
|
924
|
+
W_inv: np.ndarray,
|
|
925
|
+
use_cmc: bool,
|
|
926
|
+
fps: float,
|
|
927
|
+
reid_trust: float,
|
|
928
|
+
mu_same: float,
|
|
929
|
+
p70_diff: float,
|
|
930
|
+
*,
|
|
931
|
+
max_gap_frames: int,
|
|
932
|
+
max_cost: float,
|
|
933
|
+
use_sibling_bonus: bool,
|
|
934
|
+
margin_gate: float,
|
|
935
|
+
margin_apply_above: float,
|
|
936
|
+
) -> dict[int, int]:
|
|
937
|
+
"""Solve global 1-to-1 forward-in-time tracklet linking using vectorized scoring + Hungarian."""
|
|
938
|
+
n = len(tracklets)
|
|
939
|
+
if n < 2:
|
|
940
|
+
return {}
|
|
941
|
+
|
|
942
|
+
sep_tail = max(mu_same - p70_diff, 0.08)
|
|
943
|
+
cos_floor = max(0.68, p70_diff - 0.01)
|
|
944
|
+
fps_safe = max(fps, 1.0)
|
|
945
|
+
tau_mid_scale = max(2.2 * fps_safe, 25.0)
|
|
946
|
+
tau_slow_cap = 0.30 * fps_safe
|
|
947
|
+
|
|
948
|
+
start_f = np.array([t.start_frame for t in tracklets], dtype=np.int64)
|
|
949
|
+
end_f = np.array([t.end_frame for t in tracklets], dtype=np.int64)
|
|
950
|
+
cls_arr = np.array([t.class_id for t in tracklets], dtype=np.int64)
|
|
951
|
+
p_starts = np.stack([t.p_start for t in tracklets], axis=0)
|
|
952
|
+
v_starts = np.stack([t.v_start for t in tracklets], axis=0)
|
|
953
|
+
h_starts = np.array([t.h_start for t in tracklets], dtype=np.float64)
|
|
954
|
+
n_starts = np.array([t.n_start for t in tracklets], dtype=np.int64)
|
|
955
|
+
p_ends = np.stack([t.p_end for t in tracklets], axis=0)
|
|
956
|
+
v_ends = np.stack([t.v_end for t in tracklets], axis=0)
|
|
957
|
+
h_ends = np.array([t.h_end for t in tracklets], dtype=np.float64)
|
|
958
|
+
n_ends = np.array([t.n_end for t in tracklets], dtype=np.int64)
|
|
959
|
+
|
|
960
|
+
has_emb = np.array([t.emb_full is not None for t in tracklets], dtype=bool)
|
|
961
|
+
emb_dim = next((t.emb_full.shape[0] for t in tracklets if t.emb_full is not None), 0)
|
|
962
|
+
emb_mat = np.zeros((n, emb_dim), dtype=np.float32) if emb_dim > 0 else None
|
|
963
|
+
if emb_mat is not None:
|
|
964
|
+
for i, t in enumerate(tracklets):
|
|
965
|
+
if t.emb_full is not None:
|
|
966
|
+
emb_mat[i] = t.emb_full
|
|
967
|
+
|
|
968
|
+
order_by_start = np.argsort(start_f, kind="mergesort")
|
|
969
|
+
sorted_starts = start_f[order_by_start]
|
|
970
|
+
|
|
971
|
+
edges: dict[tuple[int, int], float] = {}
|
|
972
|
+
edge_cos: dict[tuple[int, int], float] = {}
|
|
973
|
+
best_src_cos = np.full(n, -np.inf)
|
|
974
|
+
best_dst_cos = np.full(n, -np.inf)
|
|
975
|
+
active_src: set[int] = set()
|
|
976
|
+
active_dst: set[int] = set()
|
|
977
|
+
|
|
978
|
+
for i in range(n):
|
|
979
|
+
t_a = tracklets[i]
|
|
980
|
+
f0 = int(end_f[i])
|
|
981
|
+
lo = int(np.searchsorted(sorted_starts, f0 + 1, side="left"))
|
|
982
|
+
hi = int(np.searchsorted(sorted_starts, f0 + max_gap_frames, side="right"))
|
|
983
|
+
if lo >= hi:
|
|
984
|
+
continue
|
|
985
|
+
|
|
986
|
+
cand_j = order_by_start[lo:hi]
|
|
987
|
+
if cls_arr[i] != 0 or np.any(cls_arr[cand_j] != cls_arr[i]):
|
|
988
|
+
cand_j = cand_j[cls_arr[cand_j] == cls_arr[i]]
|
|
989
|
+
if len(cand_j) == 0:
|
|
990
|
+
continue
|
|
991
|
+
|
|
992
|
+
f1s = start_f[cand_j]
|
|
993
|
+
dts = (f1s - f0).astype(np.float64)
|
|
994
|
+
dt_s = dts / fps_safe
|
|
995
|
+
f_mids = (f0 + f1s) // 2
|
|
996
|
+
|
|
997
|
+
h0 = h_ends[i]
|
|
998
|
+
h1s = h_starts[cand_j]
|
|
999
|
+
h_ratio = np.maximum(h0 / h1s, h1s / h0)
|
|
1000
|
+
hs = np.maximum(12.0, 0.5 * (h0 + h1s))
|
|
1001
|
+
|
|
1002
|
+
if use_cmc:
|
|
1003
|
+
W_mids = W[f_mids]
|
|
1004
|
+
M0 = W_mids @ W_inv[f0]
|
|
1005
|
+
p0 = np.empty((len(cand_j), 2), dtype=np.float64)
|
|
1006
|
+
p0[:, 0] = M0[:, 0, 0] * p_ends[i, 0] + M0[:, 0, 1] * p_ends[i, 1] + M0[:, 0, 2]
|
|
1007
|
+
p0[:, 1] = M0[:, 1, 0] * p_ends[i, 0] + M0[:, 1, 1] * p_ends[i, 1] + M0[:, 1, 2]
|
|
1008
|
+
v0 = np.empty((len(cand_j), 2), dtype=np.float64)
|
|
1009
|
+
v0[:, 0] = M0[:, 0, 0] * v_ends[i, 0] + M0[:, 0, 1] * v_ends[i, 1]
|
|
1010
|
+
v0[:, 1] = M0[:, 1, 0] * v_ends[i, 0] + M0[:, 1, 1] * v_ends[i, 1]
|
|
1011
|
+
|
|
1012
|
+
M1 = W_mids @ W_inv[f1s]
|
|
1013
|
+
ps1 = p_starts[cand_j]
|
|
1014
|
+
vs1 = v_starts[cand_j]
|
|
1015
|
+
p1 = np.empty((len(cand_j), 2), dtype=np.float64)
|
|
1016
|
+
p1[:, 0] = M1[:, 0, 0] * ps1[:, 0] + M1[:, 0, 1] * ps1[:, 1] + M1[:, 0, 2]
|
|
1017
|
+
p1[:, 1] = M1[:, 1, 0] * ps1[:, 0] + M1[:, 1, 1] * ps1[:, 1] + M1[:, 1, 2]
|
|
1018
|
+
v1 = np.empty((len(cand_j), 2), dtype=np.float64)
|
|
1019
|
+
v1[:, 0] = M1[:, 0, 0] * vs1[:, 0] + M1[:, 0, 1] * vs1[:, 1]
|
|
1020
|
+
v1[:, 1] = M1[:, 1, 0] * vs1[:, 0] + M1[:, 1, 1] * vs1[:, 1]
|
|
1021
|
+
else:
|
|
1022
|
+
p0 = np.broadcast_to(p_ends[i], (len(cand_j), 2))
|
|
1023
|
+
v0 = np.broadcast_to(v_ends[i], (len(cand_j), 2))
|
|
1024
|
+
p1 = p_starts[cand_j]
|
|
1025
|
+
v1 = v_starts[cand_j]
|
|
1026
|
+
|
|
1027
|
+
dp = p1 - p0
|
|
1028
|
+
d_ep = np.hypot(dp[:, 0], dp[:, 1]) / hs
|
|
1029
|
+
|
|
1030
|
+
tau_mid = (0.5 * dts) / (1.0 + np.square(dts / tau_mid_scale))
|
|
1031
|
+
pred0 = p0 + v0 * tau_mid[:, None]
|
|
1032
|
+
pred1 = p1 - v1 * tau_mid[:, None]
|
|
1033
|
+
d_bidir = np.hypot(pred1[:, 0] - pred0[:, 0], pred1[:, 1] - pred0[:, 1]) / hs
|
|
1034
|
+
|
|
1035
|
+
tau_slow = np.minimum(0.5 * dts, tau_slow_cap)
|
|
1036
|
+
ps0 = p0 + v0 * tau_slow[:, None]
|
|
1037
|
+
ps1_b = p1 - v1 * tau_slow[:, None]
|
|
1038
|
+
d_slow = np.hypot(ps1_b[:, 0] - ps0[:, 0], ps1_b[:, 1] - ps0[:, 1]) / hs
|
|
1039
|
+
d_geom = np.minimum(d_bidir, d_slow + 0.15)
|
|
1040
|
+
|
|
1041
|
+
d_vel = np.zeros(len(cand_j), dtype=np.float64)
|
|
1042
|
+
n0 = int(n_ends[i])
|
|
1043
|
+
n1s = n_starts[cand_j]
|
|
1044
|
+
if n0 >= 3:
|
|
1045
|
+
m_ge2 = (n1s >= 3) & (dts >= 2.0)
|
|
1046
|
+
if np.any(m_ge2):
|
|
1047
|
+
v_avg = dp[m_ge2] / dts[m_ge2, None]
|
|
1048
|
+
sc = np.minimum(dts[m_ge2], 8.0) / hs[m_ge2]
|
|
1049
|
+
dv0 = np.hypot(v0[m_ge2, 0] - v_avg[:, 0], v0[m_ge2, 1] - v_avg[:, 1]) * sc
|
|
1050
|
+
dv1 = np.hypot(v1[m_ge2, 0] - v_avg[:, 0], v1[m_ge2, 1] - v_avg[:, 1]) * sc
|
|
1051
|
+
d_vel[m_ge2] = 0.5 * (dv0 + dv1)
|
|
1052
|
+
if n0 >= 4:
|
|
1053
|
+
m_eq1 = (n1s >= 4) & (dts == 1.0)
|
|
1054
|
+
if np.any(m_eq1):
|
|
1055
|
+
d_vel[m_eq1] = (
|
|
1056
|
+
np.hypot(v1[m_eq1, 0] - v0[m_eq1, 0], v1[m_eq1, 1] - v0[m_eq1, 1])
|
|
1057
|
+
* 3.5
|
|
1058
|
+
/ hs[m_eq1]
|
|
1059
|
+
)
|
|
1060
|
+
|
|
1061
|
+
# Balanced kinematic cost: midpoint extrapolation + bounded endpoint anchor + velocity agreement
|
|
1062
|
+
kin_scale = 1.0 + (0.30 + 0.20 * reid_trust) * np.sqrt(dt_s)
|
|
1063
|
+
c_kin = (
|
|
1064
|
+
(0.82 * d_geom + 0.18 * np.minimum(d_ep, d_geom + 1.2)) / kin_scale
|
|
1065
|
+
+ 0.22 * d_vel
|
|
1066
|
+
+ 0.06 * np.abs(np.log(h0 / h1s))
|
|
1067
|
+
+ 0.06 * np.log1p(dt_s)
|
|
1068
|
+
)
|
|
1069
|
+
|
|
1070
|
+
max_ep = 1.50 + (3.6 + 1.4 * reid_trust) * dt_s
|
|
1071
|
+
max_geom = 1.05 + (1.25 + 1.0 * reid_trust) * dt_s
|
|
1072
|
+
valid = (h_ratio <= 2.3) & (d_ep <= max_ep) & (d_geom <= max_geom)
|
|
1073
|
+
|
|
1074
|
+
costs = c_kin.copy()
|
|
1075
|
+
cos_all = np.full(len(cand_j), np.nan)
|
|
1076
|
+
if reid_trust >= 0.08 and emb_mat is not None and has_emb[i]:
|
|
1077
|
+
both_emb = has_emb[cand_j]
|
|
1078
|
+
if np.any(both_emb):
|
|
1079
|
+
cos = (emb_mat[cand_j[both_emb]] @ emb_mat[i]).astype(np.float64)
|
|
1080
|
+
app_dist = (mu_same - cos) / sep_tail
|
|
1081
|
+
w_kin = 1.0 - 0.52 * reid_trust
|
|
1082
|
+
w_app = 0.55 * reid_trust
|
|
1083
|
+
app_term = np.maximum(-0.18, app_dist)
|
|
1084
|
+
costs[both_emb] = w_kin * c_kin[both_emb] + w_app * app_term
|
|
1085
|
+
cos_all[both_emb] = cos
|
|
1086
|
+
if reid_trust >= 0.45:
|
|
1087
|
+
veto = (app_dist > 1.00) | (cos < cos_floor)
|
|
1088
|
+
idx_b = np.where(both_emb)[0]
|
|
1089
|
+
valid[idx_b[veto]] = False
|
|
1090
|
+
|
|
1091
|
+
# Continuity prior for split siblings (soft splits are never orphaned)
|
|
1092
|
+
sib_j = t_a.next_sibling_idx if use_sibling_bonus else -1
|
|
1093
|
+
if sib_j >= 0:
|
|
1094
|
+
sib_pos = np.where(cand_j == sib_j)[0]
|
|
1095
|
+
if len(sib_pos) == 1:
|
|
1096
|
+
sp = int(sib_pos[0])
|
|
1097
|
+
costs[sp] -= t_a.next_sibling_bonus
|
|
1098
|
+
if t_a.next_sibling_soft:
|
|
1099
|
+
valid[sp] = True
|
|
1100
|
+
if costs[sp] > max_cost - 0.02:
|
|
1101
|
+
costs[sp] = max_cost - 0.02
|
|
1102
|
+
|
|
1103
|
+
keep = np.where(valid & (costs < max_cost))[0]
|
|
1104
|
+
if len(keep) == 0:
|
|
1105
|
+
continue
|
|
1106
|
+
active_src.add(i)
|
|
1107
|
+
for k_pos in keep.tolist():
|
|
1108
|
+
j = int(cand_j[k_pos])
|
|
1109
|
+
edges[(i, j)] = float(costs[k_pos])
|
|
1110
|
+
active_dst.add(j)
|
|
1111
|
+
c_ij = float(cos_all[k_pos])
|
|
1112
|
+
if np.isfinite(c_ij):
|
|
1113
|
+
edge_cos[(i, j)] = c_ij
|
|
1114
|
+
best_src_cos[i] = max(best_src_cos[i], c_ij)
|
|
1115
|
+
best_dst_cos[j] = max(best_dst_cos[j], c_ij)
|
|
1116
|
+
|
|
1117
|
+
if not edges:
|
|
1118
|
+
return {}
|
|
1119
|
+
|
|
1120
|
+
src_list = sorted(active_src)
|
|
1121
|
+
dst_list = sorted(active_dst)
|
|
1122
|
+
src_pos = {u: idx for idx, u in enumerate(src_list)}
|
|
1123
|
+
dst_pos = {v: idx for idx, v in enumerate(dst_list)}
|
|
1124
|
+
nr = len(src_list)
|
|
1125
|
+
nc = len(dst_list)
|
|
1126
|
+
|
|
1127
|
+
big = max_cost + 100.0
|
|
1128
|
+
mat = np.full((nr, nc + nr), big, dtype=np.float64)
|
|
1129
|
+
for (u, v), c in edges.items():
|
|
1130
|
+
mat[src_pos[u], dst_pos[v]] = c
|
|
1131
|
+
mat[np.arange(nr), nc + np.arange(nr)] = max_cost
|
|
1132
|
+
|
|
1133
|
+
row_ind, col_ind = linear_sum_assignment(mat)
|
|
1134
|
+
links: dict[int, int] = {}
|
|
1135
|
+
|
|
1136
|
+
for r_i, c_i in zip(row_ind.tolist(), col_ind.tolist(), strict=True):
|
|
1137
|
+
if c_i >= nc:
|
|
1138
|
+
continue
|
|
1139
|
+
cost = float(mat[r_i, c_i])
|
|
1140
|
+
if cost >= max_cost:
|
|
1141
|
+
continue
|
|
1142
|
+
u = src_list[r_i]
|
|
1143
|
+
v = dst_list[c_i]
|
|
1144
|
+
|
|
1145
|
+
is_sib = use_sibling_bonus and tracklets[u].next_sibling_idx == v
|
|
1146
|
+
if margin_gate > 0.0 and not is_sib and cost > margin_apply_above:
|
|
1147
|
+
row_vals = mat[r_i, :nc]
|
|
1148
|
+
col_vals = mat[:, c_i]
|
|
1149
|
+
alt_row = float(np.min(np.delete(row_vals, c_i))) if nc > 1 else big
|
|
1150
|
+
alt_col = float(np.min(np.delete(col_vals, r_i))) if nr > 1 else big
|
|
1151
|
+
if min(alt_row, alt_col) - cost < margin_gate:
|
|
1152
|
+
continue
|
|
1153
|
+
|
|
1154
|
+
# Mutual-best appearance: reject a link when either end has a clearly better-looking
|
|
1155
|
+
# valid candidate that the assignment gave elsewhere.
|
|
1156
|
+
c_uv = edge_cos.get((u, v))
|
|
1157
|
+
if (
|
|
1158
|
+
reid_trust >= 0.50
|
|
1159
|
+
and c_uv is not None
|
|
1160
|
+
and c_uv < max(best_src_cos[u], best_dst_cos[v]) - _MUTUAL_COS_TOL
|
|
1161
|
+
):
|
|
1162
|
+
continue
|
|
1163
|
+
links[u] = v
|
|
1164
|
+
|
|
1165
|
+
if use_sibling_bonus:
|
|
1166
|
+
used_dst = set(links.values())
|
|
1167
|
+
for t in tracklets:
|
|
1168
|
+
if t.next_sibling_soft and t.next_sibling_idx >= 0:
|
|
1169
|
+
u = t.idx
|
|
1170
|
+
v = t.next_sibling_idx
|
|
1171
|
+
if u not in links and v not in used_dst:
|
|
1172
|
+
links[u] = v
|
|
1173
|
+
used_dst.add(v)
|
|
1174
|
+
|
|
1175
|
+
return links
|
|
1176
|
+
|
|
1177
|
+
|
|
1178
|
+
def _side_velocity(frames: np.ndarray, pts: np.ndarray) -> np.ndarray:
|
|
1179
|
+
"""Least-squares velocity (px/frame) of a short run of points, zero if degenerate."""
|
|
1180
|
+
if len(frames) < 2:
|
|
1181
|
+
return np.zeros(2, dtype=np.float64)
|
|
1182
|
+
t = frames - frames.mean()
|
|
1183
|
+
denom = float(np.dot(t, t))
|
|
1184
|
+
if denom <= 0.0:
|
|
1185
|
+
return np.zeros(2, dtype=np.float64)
|
|
1186
|
+
return (t[:, None] * (pts - pts.mean(axis=0))).sum(axis=0) / denom
|
|
1187
|
+
|
|
1188
|
+
|
|
1189
|
+
def _gated_cmc_interpolate(
|
|
1190
|
+
tracklets: list[_Tracklet],
|
|
1191
|
+
W: np.ndarray,
|
|
1192
|
+
W_inv: np.ndarray,
|
|
1193
|
+
use_cmc: bool,
|
|
1194
|
+
fps: float,
|
|
1195
|
+
frame_stride: int,
|
|
1196
|
+
frame_width: int | None,
|
|
1197
|
+
frame_height: int | None,
|
|
1198
|
+
embeddings: np.ndarray | None,
|
|
1199
|
+
emb_valid: np.ndarray | None,
|
|
1200
|
+
reid_trust: float = 0.0,
|
|
1201
|
+
mu_same: float = 0.88,
|
|
1202
|
+
p70_diff: float = 0.88,
|
|
1203
|
+
) -> np.ndarray:
|
|
1204
|
+
"""Fill short gaps whose both sides are well supported and kinematically consistent.
|
|
1205
|
+
|
|
1206
|
+
A gap is filled when each side has at least `_INTERP_MIN_SUPPORT` nearby observations with
|
|
1207
|
+
mean confidence `>= _INTERP_SUPPORT_CONF`, both endpoints have confidence
|
|
1208
|
+
`>= _INTERP_ENDPOINT_CONF`, the camera-compensated travel and bidirectional velocity
|
|
1209
|
+
extrapolations agree, and (when embeddings exist) both sides look alike. When calibrated
|
|
1210
|
+
Re-ID is trustworthy and strongly confirms identity across both sides of a gap, gaps up to
|
|
1211
|
+
`_INTERP_REID_MAX_GAP_S` are eligible under tighter kinematic checks. Centres are
|
|
1212
|
+
interpolated in the coordinates of the gap's last frame and mapped back to each filled frame.
|
|
1213
|
+
"""
|
|
1214
|
+
stride = max(1, int(frame_stride))
|
|
1215
|
+
max_gap_base = max(2 * stride, int(round(_INTERP_MAX_GAP_S * fps)))
|
|
1216
|
+
can_extend = reid_trust >= 0.45 and embeddings is not None
|
|
1217
|
+
max_gap = (
|
|
1218
|
+
max(max_gap_base, int(round(_INTERP_REID_MAX_GAP_S * fps)))
|
|
1219
|
+
if can_extend
|
|
1220
|
+
else max_gap_base
|
|
1221
|
+
)
|
|
1222
|
+
reid_confirm_cos = max(p70_diff + 0.08, mu_same - 0.10)
|
|
1223
|
+
reid_veto_cos = max(_INTERP_MIN_COS, p70_diff - 0.04) if reid_trust >= 0.50 else _INTERP_MIN_COS
|
|
1224
|
+
win = _INTERP_SUPPORT_WINDOW
|
|
1225
|
+
out: list[np.ndarray] = []
|
|
1226
|
+
|
|
1227
|
+
for assigned_id, t in enumerate(tracklets, start=1):
|
|
1228
|
+
L = len(t.frames)
|
|
1229
|
+
if L < 2 * _INTERP_MIN_SUPPORT:
|
|
1230
|
+
continue
|
|
1231
|
+
fr = t.frames
|
|
1232
|
+
diffs = np.diff(fr)
|
|
1233
|
+
gap_idxs = np.nonzero((diffs > stride) & (diffs - 1 <= max_gap))[0]
|
|
1234
|
+
for g in gap_idxs.tolist():
|
|
1235
|
+
f0 = int(fr[g])
|
|
1236
|
+
f1 = int(fr[g + 1])
|
|
1237
|
+
span = f1 - f0
|
|
1238
|
+
is_extended = (span - 1) > max_gap_base
|
|
1239
|
+
c0 = float(t.confs[g])
|
|
1240
|
+
c1 = float(t.confs[g + 1])
|
|
1241
|
+
if min(c0, c1) < (_INTERP_ENDPOINT_CONF + 0.05 if is_extended else _INTERP_ENDPOINT_CONF):
|
|
1242
|
+
continue
|
|
1243
|
+
before = np.arange(max(0, g + 1 - win), g + 1)
|
|
1244
|
+
after = np.arange(g + 1, min(L, g + 1 + win))
|
|
1245
|
+
before = before[fr[before] >= f0 - 2 * stride * win]
|
|
1246
|
+
after = after[fr[after] <= f1 + 2 * stride * win]
|
|
1247
|
+
if len(before) < _INTERP_MIN_SUPPORT or len(after) < _INTERP_MIN_SUPPORT:
|
|
1248
|
+
continue
|
|
1249
|
+
min_sup_conf = _INTERP_SUPPORT_CONF + 0.05 if is_extended else _INTERP_SUPPORT_CONF
|
|
1250
|
+
if (
|
|
1251
|
+
float(t.confs[before].mean()) < min_sup_conf
|
|
1252
|
+
or float(t.confs[after].mean()) < min_sup_conf
|
|
1253
|
+
):
|
|
1254
|
+
continue
|
|
1255
|
+
b0 = t.boxes[g]
|
|
1256
|
+
b1 = t.boxes[g + 1]
|
|
1257
|
+
h0 = float(b0[3] - b0[1])
|
|
1258
|
+
h1 = float(b1[3] - b1[1])
|
|
1259
|
+
if h0 <= 1.0 or h1 <= 1.0 or max(h0, h1) / min(h0, h1) > _INTERP_MAX_HEIGHT_RATIO:
|
|
1260
|
+
continue
|
|
1261
|
+
hm = 0.5 * (h0 + h1)
|
|
1262
|
+
|
|
1263
|
+
side = np.concatenate((before, after))
|
|
1264
|
+
sb = t.boxes[side]
|
|
1265
|
+
pts = _warp_points(
|
|
1266
|
+
0.5 * (sb[:, 0] + sb[:, 2]),
|
|
1267
|
+
0.5 * (sb[:, 1] + sb[:, 3]),
|
|
1268
|
+
fr[side],
|
|
1269
|
+
f1,
|
|
1270
|
+
W,
|
|
1271
|
+
W_inv,
|
|
1272
|
+
use_cmc,
|
|
1273
|
+
)
|
|
1274
|
+
pb = pts[: len(before)]
|
|
1275
|
+
pa = pts[len(before) :]
|
|
1276
|
+
p0 = pb[-1]
|
|
1277
|
+
p1 = pa[0]
|
|
1278
|
+
travel = float(np.hypot(*(p1 - p0))) / hm
|
|
1279
|
+
travel_rate = 0.065 if is_extended else _INTERP_TRAVEL_PER_FRAME
|
|
1280
|
+
if travel > _INTERP_TRAVEL_BASE + travel_rate * span:
|
|
1281
|
+
continue
|
|
1282
|
+
v0 = _side_velocity(fr[before].astype(np.float64), pb)
|
|
1283
|
+
v1 = _side_velocity(fr[after].astype(np.float64), pa)
|
|
1284
|
+
half = 0.5 * span
|
|
1285
|
+
bidir = float(np.hypot(*((p0 + v0 * half) - (p1 - v1 * half)))) / hm
|
|
1286
|
+
max_bidir = _INTERP_REID_EXT_BIDIR if is_extended else _INTERP_MAX_BIDIR
|
|
1287
|
+
if bidir > max_bidir:
|
|
1288
|
+
continue
|
|
1289
|
+
|
|
1290
|
+
# Use a slightly wider occlusion-filtered window for Re-ID verification across gaps
|
|
1291
|
+
emb_b = np.arange(max(0, g + 1 - 10), g + 1)
|
|
1292
|
+
emb_a = np.arange(g + 1, min(L, g + 1 + 10))
|
|
1293
|
+
e0, _ = _clean_prototype(
|
|
1294
|
+
t.row_indices[emb_b], t.confs[emb_b], t.ioa[emb_b], embeddings, emb_valid
|
|
1295
|
+
)
|
|
1296
|
+
e1, _ = _clean_prototype(
|
|
1297
|
+
t.row_indices[emb_a], t.confs[emb_a], t.ioa[emb_a], embeddings, emb_valid
|
|
1298
|
+
)
|
|
1299
|
+
if is_extended:
|
|
1300
|
+
if e0 is None or e1 is None or float(e0 @ e1) < reid_confirm_cos:
|
|
1301
|
+
continue
|
|
1302
|
+
elif e0 is not None and e1 is not None and float(e0 @ e1) < reid_veto_cos:
|
|
1303
|
+
continue
|
|
1304
|
+
|
|
1305
|
+
fill = np.arange(f0 + stride, f1, stride, dtype=np.int64)
|
|
1306
|
+
if len(fill) == 0:
|
|
1307
|
+
continue
|
|
1308
|
+
s = ((fill - f0) / float(span))[:, None]
|
|
1309
|
+
centers = p0[None] + s * (p1 - p0)[None]
|
|
1310
|
+
if use_cmc:
|
|
1311
|
+
M = W[fill] @ W_inv[f1][None, :, :]
|
|
1312
|
+
centers = np.einsum("nij,nj->ni", M[:, :2, :2], centers) + M[:, :2, 2]
|
|
1313
|
+
wh0 = b0[2:4] - b0[0:2]
|
|
1314
|
+
wh1 = b1[2:4] - b1[0:2]
|
|
1315
|
+
wh = wh0[None] + s * (wh1 - wh0)[None]
|
|
1316
|
+
bx = np.concatenate((centers - 0.5 * wh, centers + 0.5 * wh), axis=1)
|
|
1317
|
+
if frame_width is not None:
|
|
1318
|
+
bx[:, [0, 2]] = np.clip(bx[:, [0, 2]], 0.0, float(frame_width))
|
|
1319
|
+
if frame_height is not None:
|
|
1320
|
+
bx[:, [1, 3]] = np.clip(bx[:, [1, 3]], 0.0, float(frame_height))
|
|
1321
|
+
keep = ((bx[:, 2] - bx[:, 0]) >= 1.0) & ((bx[:, 3] - bx[:, 1]) >= 1.0)
|
|
1322
|
+
keep &= np.isfinite(bx).all(axis=1)
|
|
1323
|
+
if not keep.any():
|
|
1324
|
+
continue
|
|
1325
|
+
rows = np.empty((int(keep.sum()), 7), dtype=np.float64)
|
|
1326
|
+
rows[:, 0] = fill[keep]
|
|
1327
|
+
rows[:, 1] = float(assigned_id)
|
|
1328
|
+
rows[:, 2:6] = bx[keep]
|
|
1329
|
+
rows[:, 6] = min(c0, c1) * _INTERP_CONF_DECAY
|
|
1330
|
+
out.append(rows)
|
|
1331
|
+
|
|
1332
|
+
if not out:
|
|
1333
|
+
return np.zeros((0, 7), dtype=np.float64)
|
|
1334
|
+
return np.concatenate(out, axis=0)
|
|
1335
|
+
|
|
1336
|
+
|
|
1337
|
+
def _smooth_tracks(
|
|
1338
|
+
out: np.ndarray,
|
|
1339
|
+
fps: float,
|
|
1340
|
+
frame_stride: int,
|
|
1341
|
+
is_interp: np.ndarray | None = None,
|
|
1342
|
+
) -> np.ndarray:
|
|
1343
|
+
"""Motion- and curvature-adaptive two-scale Gaussian smoothing in image coordinates.
|
|
1344
|
+
|
|
1345
|
+
Every contiguous run starts from light Gaussian smoothing (`_SMOOTH_SIGMA_LO_S`, with a
|
|
1346
|
+
low-fps frame-space floor) and smoothly blends toward stronger smoothing
|
|
1347
|
+
(`_SMOOTH_SIGMA_HI_S`) on low-speed, low-curvature frames measured across all four box
|
|
1348
|
+
edges (`x1, y1, x2, y2`), so steady targets lose jitter while fast articulated motion stays
|
|
1349
|
+
sharp. A smoothed value is only accepted if it stays within `_SMOOTH_GATE` box heights.
|
|
1350
|
+
"""
|
|
1351
|
+
stride = max(1, int(frame_stride))
|
|
1352
|
+
fps_eff = float(fps) / stride
|
|
1353
|
+
if fps_eff < _SMOOTH_MIN_FPS or len(out) == 0:
|
|
1354
|
+
return out
|
|
1355
|
+
sigma_lo = max(0.55, _SMOOTH_SIGMA_LO_S * fps_eff)
|
|
1356
|
+
sigma_hi = max(1.80, _SMOOTH_SIGMA_HI_S * fps_eff)
|
|
1357
|
+
|
|
1358
|
+
order = np.lexsort((out[:, 0], out[:, 1]))
|
|
1359
|
+
srt = out[order]
|
|
1360
|
+
interp_srt = is_interp[order] if is_interp is not None else np.zeros(len(srt), dtype=bool)
|
|
1361
|
+
tid = srt[:, 1]
|
|
1362
|
+
fr = np.rint(srt[:, 0]).astype(np.int64)
|
|
1363
|
+
brk = np.nonzero((np.diff(tid) != 0) | (np.diff(fr) != stride))[0] + 1
|
|
1364
|
+
starts = np.concatenate(([0], brk))
|
|
1365
|
+
ends = np.concatenate((brk, [len(srt)]))
|
|
1366
|
+
|
|
1367
|
+
b = srt[:, 2:6]
|
|
1368
|
+
sm = b.copy()
|
|
1369
|
+
|
|
1370
|
+
for s, e in zip(starts.tolist(), ends.tolist(), strict=True):
|
|
1371
|
+
L = e - s
|
|
1372
|
+
if L < 5:
|
|
1373
|
+
continue
|
|
1374
|
+
seg = b[s:e]
|
|
1375
|
+
s_lo = gaussian_filter1d(seg, sigma_lo, axis=0, mode="nearest")
|
|
1376
|
+
s_hi = gaussian_filter1d(seg, sigma_hi, axis=0, mode="nearest")
|
|
1377
|
+
|
|
1378
|
+
h_ref = np.maximum(s_lo[:, 3] - s_lo[:, 1], 1.0)
|
|
1379
|
+
edge_v = (np.abs(np.gradient(s_lo, axis=0)).max(axis=1) / h_ref) * fps_eff
|
|
1380
|
+
d_hl = np.abs(s_hi - s_lo).max(axis=1) / h_ref
|
|
1381
|
+
# Local neighborhood smoothing prevents turning on strong smoothing at inflection points
|
|
1382
|
+
edge_v_loc = gaussian_filter1d(edge_v, sigma_lo, mode="nearest")
|
|
1383
|
+
d_hl_loc = gaussian_filter1d(d_hl, sigma_lo, mode="nearest")
|
|
1384
|
+
|
|
1385
|
+
w_v = 1.0 / (1.0 + np.power(edge_v_loc / _SMOOTH_V_SCALE, 4))
|
|
1386
|
+
w_d = 1.0 / (1.0 + np.power(d_hl_loc / _SMOOTH_D_SCALE, 4))
|
|
1387
|
+
w_hi = w_v * w_d
|
|
1388
|
+
|
|
1389
|
+
seg_interp = interp_srt[s:e]
|
|
1390
|
+
if seg_interp.any():
|
|
1391
|
+
seam = seg_interp.copy()
|
|
1392
|
+
seam[:-1] |= seg_interp[1:]
|
|
1393
|
+
seam[1:] |= seg_interp[:-1]
|
|
1394
|
+
w_seam = (
|
|
1395
|
+
0.50
|
|
1396
|
+
/ (1.0 + np.power(edge_v_loc / (1.3 * _SMOOTH_V_SCALE), 4))
|
|
1397
|
+
/ (1.0 + np.power(d_hl_loc / (1.5 * _SMOOTH_D_SCALE), 4))
|
|
1398
|
+
)
|
|
1399
|
+
w_hi = np.where(seam, np.maximum(w_hi, w_seam), w_hi)
|
|
1400
|
+
|
|
1401
|
+
sm[s:e] = (1.0 - w_hi[:, None]) * s_lo + w_hi[:, None] * s_hi
|
|
1402
|
+
|
|
1403
|
+
h = np.maximum(b[:, 3] - b[:, 1], 1.0)
|
|
1404
|
+
# Match baseline gate on [cx, cy, w, h]
|
|
1405
|
+
st_raw = np.column_stack(
|
|
1406
|
+
(0.5 * (b[:, 0] + b[:, 2]), 0.5 * (b[:, 1] + b[:, 3]), b[:, 2] - b[:, 0], b[:, 3] - b[:, 1])
|
|
1407
|
+
)
|
|
1408
|
+
st_sm = np.column_stack(
|
|
1409
|
+
(0.5 * (sm[:, 0] + sm[:, 2]), 0.5 * (sm[:, 1] + sm[:, 3]), sm[:, 2] - sm[:, 0], sm[:, 3] - sm[:, 1])
|
|
1410
|
+
)
|
|
1411
|
+
dev = np.abs(st_sm - st_raw).max(axis=1) / h
|
|
1412
|
+
use = dev <= _SMOOTH_GATE
|
|
1413
|
+
nb = np.where(use[:, None], sm, b)
|
|
1414
|
+
ok = np.isfinite(nb).all(axis=1) & (nb[:, 2] - nb[:, 0] >= 1.0) & (nb[:, 3] - nb[:, 1] >= 1.0)
|
|
1415
|
+
srt[ok, 2:6] = nb[ok]
|
|
1416
|
+
res = out.copy()
|
|
1417
|
+
res[order] = srt
|
|
1418
|
+
return res
|
|
1419
|
+
|
|
1420
|
+
|
|
1421
|
+
@dataclass(slots=True)
|
|
1422
|
+
class PostprocessResult:
|
|
1423
|
+
"""Output and diagnostics of :func:`postprocess_records`."""
|
|
1424
|
+
|
|
1425
|
+
records: list[dict[str, Any]]
|
|
1426
|
+
source_row_indices: np.ndarray # int64 (M,): index into input records, or -1 if interpolated
|
|
1427
|
+
unique_tracks_before: int
|
|
1428
|
+
unique_tracks_after: int
|
|
1429
|
+
interpolated_rows: int
|
|
1430
|
+
merges: int
|
|
1431
|
+
reid_merges: int
|
|
1432
|
+
splits: int
|
|
1433
|
+
elapsed_ms: float
|
|
1434
|
+
reid_merge_events: list[dict[str, Any]]
|
|
1435
|
+
|
|
1436
|
+
|
|
1437
|
+
def _cross_exit_reid_merge(
|
|
1438
|
+
tracklets: list[_Tracklet],
|
|
1439
|
+
frames: np.ndarray,
|
|
1440
|
+
boxes: np.ndarray,
|
|
1441
|
+
confs: np.ndarray,
|
|
1442
|
+
max_ioa: np.ndarray,
|
|
1443
|
+
max_iou: np.ndarray,
|
|
1444
|
+
W: np.ndarray,
|
|
1445
|
+
W_inv: np.ndarray,
|
|
1446
|
+
use_cmc: bool,
|
|
1447
|
+
embeddings: np.ndarray | None,
|
|
1448
|
+
emb_valid: np.ndarray | None,
|
|
1449
|
+
*,
|
|
1450
|
+
min_exit_gap_frames: int = 8,
|
|
1451
|
+
min_samples: int = 3,
|
|
1452
|
+
threshold: float = 0.80,
|
|
1453
|
+
margin: float = 0.05,
|
|
1454
|
+
) -> tuple[list[_Tracklet], list[tuple[int, int, int, float]]]:
|
|
1455
|
+
"""Opt-in global cross-exit appearance merge (unifies ``--reid-merge`` with ``--postprocess``).
|
|
1456
|
+
|
|
1457
|
+
Links non-overlapping same-class tracklets separated by at least ``min_exit_gap_frames``
|
|
1458
|
+
when both have at least ``min_samples`` embeddings, cosine similarity clears ``threshold``,
|
|
1459
|
+
and the match beats every temporally competing (overlapping) alternative on both ends by
|
|
1460
|
+
``margin``. Non-overlapping third appearances of the same person do not block A->B->C chains.
|
|
1461
|
+
"""
|
|
1462
|
+
if embeddings is None or emb_valid is None or len(tracklets) < 2:
|
|
1463
|
+
return tracklets, []
|
|
1464
|
+
|
|
1465
|
+
eligible = [
|
|
1466
|
+
i for i, t in enumerate(tracklets) if t.emb_full is not None and t.n_emb >= min_samples
|
|
1467
|
+
]
|
|
1468
|
+
if len(eligible) < 2:
|
|
1469
|
+
return tracklets, []
|
|
1470
|
+
|
|
1471
|
+
def _overlaps(a: _Tracklet, b: _Tracklet) -> bool:
|
|
1472
|
+
return a.start_frame <= b.end_frame and b.start_frame <= a.end_frame
|
|
1473
|
+
|
|
1474
|
+
# Score all temporally valid (end_u + gap <= start_v) same-class pairs.
|
|
1475
|
+
pair_sims: list[tuple[float, int, int]] = []
|
|
1476
|
+
out_sims: dict[int, list[tuple[float, int]]] = {}
|
|
1477
|
+
in_sims: dict[int, list[tuple[float, int]]] = {}
|
|
1478
|
+
for a_pos, i in enumerate(eligible):
|
|
1479
|
+
ti = tracklets[i]
|
|
1480
|
+
assert ti.emb_full is not None
|
|
1481
|
+
for j in eligible[a_pos + 1 :]:
|
|
1482
|
+
tj = tracklets[j]
|
|
1483
|
+
assert tj.emb_full is not None
|
|
1484
|
+
if ti.class_id != tj.class_id:
|
|
1485
|
+
continue
|
|
1486
|
+
if ti.end_frame + min_exit_gap_frames <= tj.start_frame:
|
|
1487
|
+
u, v = i, j
|
|
1488
|
+
elif tj.end_frame + min_exit_gap_frames <= ti.start_frame:
|
|
1489
|
+
u, v = j, i
|
|
1490
|
+
else:
|
|
1491
|
+
continue
|
|
1492
|
+
sim = float(np.dot(ti.emb_full, tj.emb_full))
|
|
1493
|
+
out_sims.setdefault(u, []).append((sim, v))
|
|
1494
|
+
in_sims.setdefault(v, []).append((sim, u))
|
|
1495
|
+
if sim >= threshold:
|
|
1496
|
+
pair_sims.append((sim, u, v))
|
|
1497
|
+
|
|
1498
|
+
if not pair_sims:
|
|
1499
|
+
return tracklets, []
|
|
1500
|
+
|
|
1501
|
+
# Merge clusters via union-find (highest similarity first) so a stronger (A, C) link
|
|
1502
|
+
# cannot orphan an intermediate re-entry B in A -> B -> C chains.
|
|
1503
|
+
parent = list(range(len(tracklets)))
|
|
1504
|
+
members: list[list[int]] = [[i] for i in range(len(tracklets))]
|
|
1505
|
+
|
|
1506
|
+
def _find(x: int) -> int:
|
|
1507
|
+
while parent[x] != x:
|
|
1508
|
+
parent[x] = parent[parent[x]]
|
|
1509
|
+
x = parent[x]
|
|
1510
|
+
return x
|
|
1511
|
+
|
|
1512
|
+
def _compatible(a: _Tracklet, b: _Tracklet) -> bool:
|
|
1513
|
+
assert a.emb_full is not None and b.emb_full is not None
|
|
1514
|
+
return (
|
|
1515
|
+
a.end_frame + min_exit_gap_frames <= b.start_frame
|
|
1516
|
+
or b.end_frame + min_exit_gap_frames <= a.start_frame
|
|
1517
|
+
) and float(np.dot(a.emb_full, b.emb_full)) >= threshold
|
|
1518
|
+
|
|
1519
|
+
pair_sims.sort(key=lambda x: (-x[0], tracklets[x[2]].start_frame - tracklets[x[1]].end_frame))
|
|
1520
|
+
for sim, u, v in pair_sims:
|
|
1521
|
+
ru, rv = _find(u), _find(v)
|
|
1522
|
+
if ru == rv:
|
|
1523
|
+
continue
|
|
1524
|
+
tu, tv = tracklets[u], tracklets[v]
|
|
1525
|
+
# Only candidates that overlap in time with v (or u) are mutually exclusive look-alikes;
|
|
1526
|
+
# a later non-overlapping return C of the same person must not block A -> B.
|
|
1527
|
+
o_comp = [s for s, cand in out_sims[u] if cand != v and _overlaps(tracklets[cand], tv)]
|
|
1528
|
+
i_comp = [s for s, cand in in_sims[v] if cand != u and _overlaps(tracklets[cand], tu)]
|
|
1529
|
+
o_runner = max(o_comp, default=-1.0)
|
|
1530
|
+
i_runner = max(i_comp, default=-1.0)
|
|
1531
|
+
if sim - o_runner < margin or sim - i_runner < margin:
|
|
1532
|
+
continue
|
|
1533
|
+
if not all(
|
|
1534
|
+
_compatible(tracklets[a], tracklets[b]) for a in members[ru] for b in members[rv]
|
|
1535
|
+
):
|
|
1536
|
+
continue
|
|
1537
|
+
if len(members[ru]) < len(members[rv]):
|
|
1538
|
+
ru, rv = rv, ru
|
|
1539
|
+
parent[rv] = ru
|
|
1540
|
+
members[ru].extend(members[rv])
|
|
1541
|
+
members[rv].clear()
|
|
1542
|
+
|
|
1543
|
+
links: dict[int, int] = {}
|
|
1544
|
+
link_meta: list[tuple[int, int, int, float]] = []
|
|
1545
|
+
for grp in members:
|
|
1546
|
+
if len(grp) < 2:
|
|
1547
|
+
continue
|
|
1548
|
+
grp.sort(key=lambda idx: (tracklets[idx].start_frame, tracklets[idx].end_frame))
|
|
1549
|
+
for u, v in zip(grp, grp[1:], strict=False):
|
|
1550
|
+
tu, tv = tracklets[u], tracklets[v]
|
|
1551
|
+
assert tu.emb_full is not None and tv.emb_full is not None
|
|
1552
|
+
links[u] = v
|
|
1553
|
+
link_meta.append(
|
|
1554
|
+
(
|
|
1555
|
+
tv.start_frame,
|
|
1556
|
+
int(tu.row_indices[0]),
|
|
1557
|
+
int(tv.row_indices[0]),
|
|
1558
|
+
float(np.dot(tu.emb_full, tv.emb_full)),
|
|
1559
|
+
)
|
|
1560
|
+
)
|
|
1561
|
+
|
|
1562
|
+
if not links:
|
|
1563
|
+
return tracklets, []
|
|
1564
|
+
|
|
1565
|
+
merged = _merge_chains(
|
|
1566
|
+
tracklets,
|
|
1567
|
+
links,
|
|
1568
|
+
frames,
|
|
1569
|
+
boxes,
|
|
1570
|
+
confs,
|
|
1571
|
+
max_ioa,
|
|
1572
|
+
max_iou,
|
|
1573
|
+
W,
|
|
1574
|
+
W_inv,
|
|
1575
|
+
use_cmc,
|
|
1576
|
+
embeddings,
|
|
1577
|
+
emb_valid,
|
|
1578
|
+
)
|
|
1579
|
+
return merged, link_meta
|
|
1580
|
+
|
|
1581
|
+
|
|
1582
|
+
def _postprocess_tracks_core(
|
|
1583
|
+
rows: np.ndarray,
|
|
1584
|
+
*,
|
|
1585
|
+
fps: float = 30.0,
|
|
1586
|
+
frame_width: int | None = None,
|
|
1587
|
+
frame_height: int | None = None,
|
|
1588
|
+
embeddings: np.ndarray | None = None,
|
|
1589
|
+
emb_valid: np.ndarray | None = None,
|
|
1590
|
+
cmc_warps: np.ndarray | None = None,
|
|
1591
|
+
cmc_valid: np.ndarray | None = None,
|
|
1592
|
+
class_ids: np.ndarray | None = None,
|
|
1593
|
+
frame_stride: int = 1,
|
|
1594
|
+
allow_long_reid_merge: bool = False,
|
|
1595
|
+
min_exit_gap_frames: int = 8,
|
|
1596
|
+
) -> tuple[np.ndarray, np.ndarray, dict[str, Any]]:
|
|
1597
|
+
"""Core post-processing engine returning ``(out_rows, source_row_indices, stats)``."""
|
|
1598
|
+
arr = np.asarray(rows, dtype=np.float64).reshape(-1, 7)
|
|
1599
|
+
if len(arr) == 0:
|
|
1600
|
+
return (
|
|
1601
|
+
arr.copy(),
|
|
1602
|
+
np.zeros((0,), dtype=np.int64),
|
|
1603
|
+
{
|
|
1604
|
+
"unique_tracks_before": 0,
|
|
1605
|
+
"unique_tracks_after": 0,
|
|
1606
|
+
"interpolated_rows": 0,
|
|
1607
|
+
"merges": 0,
|
|
1608
|
+
"reid_merges": 0,
|
|
1609
|
+
"splits": 0,
|
|
1610
|
+
"reid_merge_events": [],
|
|
1611
|
+
},
|
|
1612
|
+
)
|
|
1613
|
+
|
|
1614
|
+
frames = np.rint(arr[:, 0]).astype(np.int64)
|
|
1615
|
+
if int(frames.min()) < 0:
|
|
1616
|
+
raise ValueError(f"frame_idx must be nonnegative, got min {int(frames.min())}.")
|
|
1617
|
+
if embeddings is not None:
|
|
1618
|
+
if len(embeddings) != len(arr):
|
|
1619
|
+
raise ValueError(
|
|
1620
|
+
f"embeddings length ({len(embeddings)}) must match rows length ({len(arr)})."
|
|
1621
|
+
)
|
|
1622
|
+
if emb_valid is None:
|
|
1623
|
+
emb_valid = np.ones((len(arr),), dtype=bool)
|
|
1624
|
+
else:
|
|
1625
|
+
emb_valid = np.asarray(emb_valid, dtype=bool)
|
|
1626
|
+
if emb_valid.shape != (len(arr),):
|
|
1627
|
+
raise ValueError(
|
|
1628
|
+
f"emb_valid length ({len(emb_valid)}) must match rows length ({len(arr)})."
|
|
1629
|
+
)
|
|
1630
|
+
if class_ids is not None:
|
|
1631
|
+
class_ids = np.asarray(class_ids, dtype=np.int64)
|
|
1632
|
+
if class_ids.shape != (len(arr),):
|
|
1633
|
+
raise ValueError(
|
|
1634
|
+
f"class_ids length ({len(class_ids)}) must match rows length ({len(arr)})."
|
|
1635
|
+
)
|
|
1636
|
+
if cmc_warps is not None and cmc_valid is not None:
|
|
1637
|
+
cmc_valid = np.asarray(cmc_valid, dtype=bool)
|
|
1638
|
+
if len(cmc_valid) != len(cmc_warps):
|
|
1639
|
+
raise ValueError(
|
|
1640
|
+
f"cmc_valid length ({len(cmc_valid)}) must match cmc_warps length ({len(cmc_warps)})."
|
|
1641
|
+
)
|
|
1642
|
+
|
|
1643
|
+
tids = np.rint(arr[:, 1]).astype(np.int64)
|
|
1644
|
+
boxes = arr[:, 2:6]
|
|
1645
|
+
confs = arr[:, 6]
|
|
1646
|
+
stride = max(1, int(frame_stride))
|
|
1647
|
+
|
|
1648
|
+
num_frames = int(frames.max()) + 1
|
|
1649
|
+
if cmc_warps is not None:
|
|
1650
|
+
num_frames = max(num_frames, len(cmc_warps))
|
|
1651
|
+
|
|
1652
|
+
# Stage 0: Cumulative CMC, per-frame overlaps, and sequence-level Re-ID calibration
|
|
1653
|
+
W, W_inv, use_cmc = _compute_cumulative_cmc(
|
|
1654
|
+
num_frames, cmc_warps, cmc_valid, frame_width, frame_height
|
|
1655
|
+
)
|
|
1656
|
+
max_ioa, max_iou, pair_overlaps = _compute_frame_overlaps(frames, tids, boxes)
|
|
1657
|
+
|
|
1658
|
+
order = np.lexsort((frames, tids))
|
|
1659
|
+
t_sorted = tids[order]
|
|
1660
|
+
u_tids, t_starts, t_counts = np.unique(t_sorted, return_index=True, return_counts=True)
|
|
1661
|
+
raw_tracks: dict[int, np.ndarray] = {
|
|
1662
|
+
int(tid): order[s : s + c]
|
|
1663
|
+
for tid, s, c in zip(u_tids, t_starts, t_counts, strict=True)
|
|
1664
|
+
}
|
|
1665
|
+
unique_before = len(raw_tracks)
|
|
1666
|
+
|
|
1667
|
+
reid_trust, mu_same, _p50_diff, p70_diff = _calibrate_reid(
|
|
1668
|
+
raw_tracks, frames, confs, max_ioa, embeddings, emb_valid
|
|
1669
|
+
)
|
|
1670
|
+
|
|
1671
|
+
# Stage 1: Suspect-transition track splitting
|
|
1672
|
+
crossing_swaps: list[tuple[float, int, int]] = []
|
|
1673
|
+
split_points = _detect_split_points(
|
|
1674
|
+
raw_tracks,
|
|
1675
|
+
frames,
|
|
1676
|
+
boxes,
|
|
1677
|
+
confs,
|
|
1678
|
+
max_ioa,
|
|
1679
|
+
max_iou,
|
|
1680
|
+
pair_overlaps,
|
|
1681
|
+
W,
|
|
1682
|
+
W_inv,
|
|
1683
|
+
use_cmc,
|
|
1684
|
+
embeddings,
|
|
1685
|
+
emb_valid,
|
|
1686
|
+
reid_trust,
|
|
1687
|
+
mu_same,
|
|
1688
|
+
p70_diff,
|
|
1689
|
+
crossing_swaps,
|
|
1690
|
+
class_ids=class_ids,
|
|
1691
|
+
frame_stride=stride,
|
|
1692
|
+
fps=fps,
|
|
1693
|
+
)
|
|
1694
|
+
tracklets = _build_tracklets(
|
|
1695
|
+
raw_tracks,
|
|
1696
|
+
split_points,
|
|
1697
|
+
frames,
|
|
1698
|
+
boxes,
|
|
1699
|
+
confs,
|
|
1700
|
+
max_ioa,
|
|
1701
|
+
max_iou,
|
|
1702
|
+
class_ids,
|
|
1703
|
+
W,
|
|
1704
|
+
W_inv,
|
|
1705
|
+
use_cmc,
|
|
1706
|
+
embeddings,
|
|
1707
|
+
emb_valid,
|
|
1708
|
+
)
|
|
1709
|
+
n_splits = sum(len(v) for v in split_points.values())
|
|
1710
|
+
|
|
1711
|
+
# A cut may have coalesced with another split. Rewire only intact
|
|
1712
|
+
# crossing pairs, resolving simultaneous proposals by their cost margin.
|
|
1713
|
+
tails = {int(t.row_indices[-1]): t for t in tracklets}
|
|
1714
|
+
paired = set()
|
|
1715
|
+
for _, ra, rb in sorted(crossing_swaps, reverse=True):
|
|
1716
|
+
if ra not in tails or rb not in tails or ra in paired or rb in paired:
|
|
1717
|
+
continue
|
|
1718
|
+
a, b = tails[ra], tails[rb]
|
|
1719
|
+
if a.class_id != b.class_id or min(a.next_sibling_idx, b.next_sibling_idx) < 0:
|
|
1720
|
+
continue
|
|
1721
|
+
a.next_sibling_idx, b.next_sibling_idx = b.next_sibling_idx, a.next_sibling_idx
|
|
1722
|
+
a.next_sibling_bonus = b.next_sibling_bonus = 1.0
|
|
1723
|
+
a.next_sibling_soft = b.next_sibling_soft = True
|
|
1724
|
+
paired.update((ra, rb))
|
|
1725
|
+
|
|
1726
|
+
# Stage 2, Pass 1 (Local Repair): resolve crossing swaps, Y/T-junction hijacks & restore soft splits
|
|
1727
|
+
p1_gap = max(2 * stride, int(round(0.9 * fps)))
|
|
1728
|
+
p1_max_cost = 0.54 + 0.18 * reid_trust
|
|
1729
|
+
links_p1 = _stitch_pass(
|
|
1730
|
+
tracklets,
|
|
1731
|
+
W,
|
|
1732
|
+
W_inv,
|
|
1733
|
+
use_cmc,
|
|
1734
|
+
fps,
|
|
1735
|
+
reid_trust,
|
|
1736
|
+
mu_same,
|
|
1737
|
+
p70_diff,
|
|
1738
|
+
max_gap_frames=p1_gap,
|
|
1739
|
+
max_cost=p1_max_cost,
|
|
1740
|
+
use_sibling_bonus=True,
|
|
1741
|
+
margin_gate=0.06,
|
|
1742
|
+
margin_apply_above=0.22,
|
|
1743
|
+
)
|
|
1744
|
+
tracklets = _merge_chains(
|
|
1745
|
+
tracklets,
|
|
1746
|
+
links_p1,
|
|
1747
|
+
frames,
|
|
1748
|
+
boxes,
|
|
1749
|
+
confs,
|
|
1750
|
+
max_ioa,
|
|
1751
|
+
max_iou,
|
|
1752
|
+
W,
|
|
1753
|
+
W_inv,
|
|
1754
|
+
use_cmc,
|
|
1755
|
+
embeddings,
|
|
1756
|
+
emb_valid,
|
|
1757
|
+
)
|
|
1758
|
+
|
|
1759
|
+
# Stage 2, Pass 2 & 3 (Global Long-Range Stitching): operate on repaired full-length tracklets
|
|
1760
|
+
long_gap_s = 6.0 if reid_trust >= 0.50 else 3.2
|
|
1761
|
+
p2_max_cost = 0.54 + 0.28 * reid_trust
|
|
1762
|
+
# With trusted Re-ID, commit medium-range links before the long-range pass.
|
|
1763
|
+
horizons = [2.5, long_gap_s] if reid_trust >= 0.50 else [long_gap_s]
|
|
1764
|
+
for horizon_s in horizons:
|
|
1765
|
+
long_gap = max(4 * stride, int(round(horizon_s * fps)))
|
|
1766
|
+
links_p2 = _stitch_pass(
|
|
1767
|
+
tracklets,
|
|
1768
|
+
W,
|
|
1769
|
+
W_inv,
|
|
1770
|
+
use_cmc,
|
|
1771
|
+
fps,
|
|
1772
|
+
reid_trust,
|
|
1773
|
+
mu_same,
|
|
1774
|
+
p70_diff,
|
|
1775
|
+
max_gap_frames=long_gap,
|
|
1776
|
+
max_cost=p2_max_cost,
|
|
1777
|
+
use_sibling_bonus=False,
|
|
1778
|
+
margin_gate=0.09 if reid_trust < 0.35 else 0.07,
|
|
1779
|
+
margin_apply_above=0.22,
|
|
1780
|
+
)
|
|
1781
|
+
if not links_p2:
|
|
1782
|
+
continue
|
|
1783
|
+
tracklets = _merge_chains(
|
|
1784
|
+
tracklets,
|
|
1785
|
+
links_p2,
|
|
1786
|
+
frames,
|
|
1787
|
+
boxes,
|
|
1788
|
+
confs,
|
|
1789
|
+
max_ioa,
|
|
1790
|
+
max_iou,
|
|
1791
|
+
W,
|
|
1792
|
+
W_inv,
|
|
1793
|
+
use_cmc,
|
|
1794
|
+
embeddings,
|
|
1795
|
+
emb_valid,
|
|
1796
|
+
)
|
|
1797
|
+
|
|
1798
|
+
# Optional cross-exit Re-ID merge pass (when user passes both --postprocess and --reid-merge)
|
|
1799
|
+
reid_link_meta: list[tuple[int, int, int, float]] = []
|
|
1800
|
+
if allow_long_reid_merge:
|
|
1801
|
+
tracklets, reid_link_meta = _cross_exit_reid_merge(
|
|
1802
|
+
tracklets,
|
|
1803
|
+
frames,
|
|
1804
|
+
boxes,
|
|
1805
|
+
confs,
|
|
1806
|
+
max_ioa,
|
|
1807
|
+
max_iou,
|
|
1808
|
+
W,
|
|
1809
|
+
W_inv,
|
|
1810
|
+
use_cmc,
|
|
1811
|
+
embeddings,
|
|
1812
|
+
emb_valid,
|
|
1813
|
+
min_exit_gap_frames=min_exit_gap_frames,
|
|
1814
|
+
)
|
|
1815
|
+
|
|
1816
|
+
# Reconstruct output rows with clean contiguous 1-based track IDs
|
|
1817
|
+
tracklets.sort(key=lambda t: (t.start_frame, t.raw_id, t.part_id))
|
|
1818
|
+
out = arr.copy()
|
|
1819
|
+
new_tid = np.empty(len(arr), dtype=np.int64)
|
|
1820
|
+
for assigned_id, t in enumerate(tracklets, start=1):
|
|
1821
|
+
new_tid[t.row_indices] = assigned_id
|
|
1822
|
+
out[:, 1] = new_tid.astype(np.float64)
|
|
1823
|
+
src_idx = np.arange(len(arr), dtype=np.int64)
|
|
1824
|
+
|
|
1825
|
+
# Stage 3: Strictly gated short-gap CMC interpolation
|
|
1826
|
+
interp_rows = _gated_cmc_interpolate(
|
|
1827
|
+
tracklets,
|
|
1828
|
+
W,
|
|
1829
|
+
W_inv,
|
|
1830
|
+
use_cmc,
|
|
1831
|
+
fps,
|
|
1832
|
+
stride,
|
|
1833
|
+
frame_width,
|
|
1834
|
+
frame_height,
|
|
1835
|
+
embeddings,
|
|
1836
|
+
emb_valid,
|
|
1837
|
+
reid_trust=reid_trust,
|
|
1838
|
+
mu_same=mu_same,
|
|
1839
|
+
p70_diff=p70_diff,
|
|
1840
|
+
)
|
|
1841
|
+
n_interp = len(interp_rows)
|
|
1842
|
+
is_interp = np.zeros(len(out), dtype=bool)
|
|
1843
|
+
if n_interp > 0:
|
|
1844
|
+
out = np.vstack((out, interp_rows))
|
|
1845
|
+
is_interp = np.concatenate((is_interp, np.ones(n_interp, dtype=bool)))
|
|
1846
|
+
src_idx = np.concatenate((src_idx, np.full(n_interp, -1, dtype=np.int64)))
|
|
1847
|
+
|
|
1848
|
+
# Stage 4: Motion- and curvature-adaptive image-space smoothing
|
|
1849
|
+
out = _smooth_tracks(out, fps, stride, is_interp=is_interp)
|
|
1850
|
+
|
|
1851
|
+
out_order = np.lexsort((out[:, 1], out[:, 0]))
|
|
1852
|
+
# Realized raw-ID merges (distinct raw IDs folded into the same final track)
|
|
1853
|
+
raw_merges = sum(
|
|
1854
|
+
max(0, len({int(tids[i]) for i in t.row_indices.tolist()}) - 1) for t in tracklets
|
|
1855
|
+
)
|
|
1856
|
+
reid_merge_events = [
|
|
1857
|
+
{
|
|
1858
|
+
"frame_idx": int(f_re),
|
|
1859
|
+
"type": "reid_cross_exit_merge",
|
|
1860
|
+
"raw_track_id": int(tids[row_v]),
|
|
1861
|
+
"canonical_track_id": int(new_tid[row_u]),
|
|
1862
|
+
"similarity": round(float(sim), 3),
|
|
1863
|
+
}
|
|
1864
|
+
for f_re, row_u, row_v, sim in reid_link_meta
|
|
1865
|
+
]
|
|
1866
|
+
stats = {
|
|
1867
|
+
"unique_tracks_before": unique_before,
|
|
1868
|
+
"unique_tracks_after": len(tracklets),
|
|
1869
|
+
"interpolated_rows": n_interp,
|
|
1870
|
+
"merges": raw_merges,
|
|
1871
|
+
"reid_merges": len(reid_merge_events),
|
|
1872
|
+
"splits": n_splits,
|
|
1873
|
+
"reid_merge_events": reid_merge_events,
|
|
1874
|
+
}
|
|
1875
|
+
return out[out_order], src_idx[out_order], stats
|
|
1876
|
+
|
|
1877
|
+
|
|
1878
|
+
def postprocess_tracks_array(
|
|
1879
|
+
rows: np.ndarray,
|
|
1880
|
+
*,
|
|
1881
|
+
fps: float = 30.0,
|
|
1882
|
+
frame_width: int | None = None,
|
|
1883
|
+
frame_height: int | None = None,
|
|
1884
|
+
embeddings: np.ndarray | None = None,
|
|
1885
|
+
emb_valid: np.ndarray | None = None,
|
|
1886
|
+
cmc_warps: np.ndarray | None = None,
|
|
1887
|
+
cmc_valid: np.ndarray | None = None,
|
|
1888
|
+
class_ids: np.ndarray | None = None,
|
|
1889
|
+
frame_stride: int = 1,
|
|
1890
|
+
) -> np.ndarray:
|
|
1891
|
+
"""Offline post-processing: suspect-transition splitting + global CMC/Re-ID re-stitching.
|
|
1892
|
+
|
|
1893
|
+
`rows` has shape (N, 7) float64: [frame_idx (0-based), track_id, x1, y1, x2, y2, conf].
|
|
1894
|
+
Returns float64 array of shape (M, 7) with valid boxes and unique (frame_idx, track_id).
|
|
1895
|
+
"""
|
|
1896
|
+
out, _, _ = _postprocess_tracks_core(
|
|
1897
|
+
rows,
|
|
1898
|
+
fps=fps,
|
|
1899
|
+
frame_width=frame_width,
|
|
1900
|
+
frame_height=frame_height,
|
|
1901
|
+
embeddings=embeddings,
|
|
1902
|
+
emb_valid=emb_valid,
|
|
1903
|
+
cmc_warps=cmc_warps,
|
|
1904
|
+
cmc_valid=cmc_valid,
|
|
1905
|
+
class_ids=class_ids,
|
|
1906
|
+
frame_stride=frame_stride,
|
|
1907
|
+
)
|
|
1908
|
+
return out
|
|
1909
|
+
|
|
1910
|
+
|
|
1911
|
+
def postprocess_records(
|
|
1912
|
+
records: list[dict[str, Any]],
|
|
1913
|
+
*,
|
|
1914
|
+
fps: float = 30.0,
|
|
1915
|
+
frame_width: int | None = None,
|
|
1916
|
+
frame_height: int | None = None,
|
|
1917
|
+
embeddings: np.ndarray | None = None,
|
|
1918
|
+
emb_valid: np.ndarray | None = None,
|
|
1919
|
+
cmc_warps: np.ndarray | None = None,
|
|
1920
|
+
cmc_valid: np.ndarray | None = None,
|
|
1921
|
+
frame_stride: int = 1,
|
|
1922
|
+
allow_long_reid_merge: bool = False,
|
|
1923
|
+
min_exit_gap_frames: int = 8,
|
|
1924
|
+
) -> PostprocessResult:
|
|
1925
|
+
"""Post-process a list of Trackflow observation records (matching ``PARQUET_SCHEMA``).
|
|
1926
|
+
|
|
1927
|
+
Preserves multi-class isolation, ``frame_stride``, and exact source-row provenance while
|
|
1928
|
+
recomputing bounding box dimensions, track ages/hits, and timestamps for interpolated rows.
|
|
1929
|
+
"""
|
|
1930
|
+
t0 = time.perf_counter()
|
|
1931
|
+
if not records:
|
|
1932
|
+
return PostprocessResult(
|
|
1933
|
+
records=[],
|
|
1934
|
+
source_row_indices=np.zeros((0,), dtype=np.int64),
|
|
1935
|
+
unique_tracks_before=0,
|
|
1936
|
+
unique_tracks_after=0,
|
|
1937
|
+
interpolated_rows=0,
|
|
1938
|
+
merges=0,
|
|
1939
|
+
reid_merges=0,
|
|
1940
|
+
splits=0,
|
|
1941
|
+
elapsed_ms=0.0,
|
|
1942
|
+
reid_merge_events=[],
|
|
1943
|
+
)
|
|
1944
|
+
|
|
1945
|
+
rows = np.array(
|
|
1946
|
+
[
|
|
1947
|
+
(r["frame_idx"], r["track_id"], r["x1"], r["y1"], r["x2"], r["y2"], r["confidence"])
|
|
1948
|
+
for r in records
|
|
1949
|
+
],
|
|
1950
|
+
dtype=np.float64,
|
|
1951
|
+
)
|
|
1952
|
+
class_ids = np.array([r["class_id"] for r in records], dtype=np.int64)
|
|
1953
|
+
class_name_by_id: dict[int, str] = {}
|
|
1954
|
+
for r in records:
|
|
1955
|
+
cid = int(r["class_id"])
|
|
1956
|
+
if cid not in class_name_by_id:
|
|
1957
|
+
class_name_by_id[cid] = str(r["class_name"])
|
|
1958
|
+
|
|
1959
|
+
out_rows, src_idx, stats = _postprocess_tracks_core(
|
|
1960
|
+
rows,
|
|
1961
|
+
fps=fps,
|
|
1962
|
+
frame_width=frame_width,
|
|
1963
|
+
frame_height=frame_height,
|
|
1964
|
+
embeddings=embeddings,
|
|
1965
|
+
emb_valid=emb_valid,
|
|
1966
|
+
cmc_warps=cmc_warps,
|
|
1967
|
+
cmc_valid=cmc_valid,
|
|
1968
|
+
class_ids=class_ids,
|
|
1969
|
+
frame_stride=frame_stride,
|
|
1970
|
+
allow_long_reid_merge=allow_long_reid_merge,
|
|
1971
|
+
min_exit_gap_frames=min_exit_gap_frames,
|
|
1972
|
+
)
|
|
1973
|
+
|
|
1974
|
+
src_list = src_idx.tolist()
|
|
1975
|
+
f_list = np.rint(out_rows[:, 0]).astype(np.int64).tolist()
|
|
1976
|
+
tid_list = np.rint(out_rows[:, 1]).astype(np.int64).tolist()
|
|
1977
|
+
box_conf = out_rows[:, 2:7].tolist()
|
|
1978
|
+
|
|
1979
|
+
# Determine each finalized track's class from its observed source rows
|
|
1980
|
+
tid_class: dict[int, tuple[int, str]] = {}
|
|
1981
|
+
for tid, si in zip(tid_list, src_list, strict=True):
|
|
1982
|
+
if si >= 0 and tid not in tid_class:
|
|
1983
|
+
orig = records[si]
|
|
1984
|
+
tid_class[tid] = (int(orig["class_id"]), str(orig["class_name"]))
|
|
1985
|
+
|
|
1986
|
+
fps_safe = max(float(fps), 1e-6)
|
|
1987
|
+
stride = max(1, int(frame_stride))
|
|
1988
|
+
first_frame_by_tid: dict[int, int] = {}
|
|
1989
|
+
hits_by_tid: dict[int, int] = {}
|
|
1990
|
+
out_records: list[dict[str, Any]] = []
|
|
1991
|
+
append = out_records.append
|
|
1992
|
+
_round = round
|
|
1993
|
+
default_cls = (0, class_name_by_id.get(0, "object"))
|
|
1994
|
+
|
|
1995
|
+
for f_idx, tid, (x1, y1, x2, y2, conf), si in zip(
|
|
1996
|
+
f_list, tid_list, box_conf, src_list, strict=True
|
|
1997
|
+
):
|
|
1998
|
+
first_f = first_frame_by_tid.get(tid)
|
|
1999
|
+
if first_f is None:
|
|
2000
|
+
first_frame_by_tid[tid] = f_idx
|
|
2001
|
+
first_f = f_idx
|
|
2002
|
+
age = (f_idx - first_f) // stride + 1
|
|
2003
|
+
if age < 1:
|
|
2004
|
+
age = 1
|
|
2005
|
+
if si >= 0:
|
|
2006
|
+
hits = hits_by_tid.get(tid, 0) + 1
|
|
2007
|
+
hits_by_tid[tid] = hits
|
|
2008
|
+
orig = records[si]
|
|
2009
|
+
cid = int(orig["class_id"])
|
|
2010
|
+
cname = str(orig["class_name"])
|
|
2011
|
+
ts = _round(float(orig["timestamp_s"]), 4)
|
|
2012
|
+
recovered = bool(orig.get("recovered", False))
|
|
2013
|
+
q_score = orig.get("query_score")
|
|
2014
|
+
q_match = bool(orig.get("query_match", True))
|
|
2015
|
+
else:
|
|
2016
|
+
hits = hits_by_tid.get(tid)
|
|
2017
|
+
if hits is None:
|
|
2018
|
+
hits_by_tid[tid] = 1
|
|
2019
|
+
hits = 1
|
|
2020
|
+
cid, cname = tid_class.get(tid, default_cls)
|
|
2021
|
+
ts = _round(f_idx / fps_safe, 4)
|
|
2022
|
+
recovered = False
|
|
2023
|
+
q_score = None
|
|
2024
|
+
q_match = True
|
|
2025
|
+
|
|
2026
|
+
w = x2 - x1
|
|
2027
|
+
h = y2 - y1
|
|
2028
|
+
append(
|
|
2029
|
+
{
|
|
2030
|
+
"frame_idx": f_idx,
|
|
2031
|
+
"timestamp_s": ts,
|
|
2032
|
+
"track_id": tid,
|
|
2033
|
+
"class_id": cid,
|
|
2034
|
+
"class_name": cname,
|
|
2035
|
+
"confidence": _round(conf, 4),
|
|
2036
|
+
"x1": _round(x1, 2),
|
|
2037
|
+
"y1": _round(y1, 2),
|
|
2038
|
+
"x2": _round(x2, 2),
|
|
2039
|
+
"y2": _round(y2, 2),
|
|
2040
|
+
"width": _round(w if w > 0.0 else 0.0, 2),
|
|
2041
|
+
"height": _round(h if h > 0.0 else 0.0, 2),
|
|
2042
|
+
"age": age,
|
|
2043
|
+
"hits": hits,
|
|
2044
|
+
"recovered": recovered,
|
|
2045
|
+
"query_score": q_score,
|
|
2046
|
+
"query_match": q_match,
|
|
2047
|
+
"world_x": None,
|
|
2048
|
+
"world_y": None,
|
|
2049
|
+
"zone": None,
|
|
2050
|
+
}
|
|
2051
|
+
)
|
|
2052
|
+
|
|
2053
|
+
elapsed_ms = (time.perf_counter() - t0) * 1000.0
|
|
2054
|
+
return PostprocessResult(
|
|
2055
|
+
records=out_records,
|
|
2056
|
+
source_row_indices=src_idx,
|
|
2057
|
+
unique_tracks_before=stats["unique_tracks_before"],
|
|
2058
|
+
unique_tracks_after=stats["unique_tracks_after"],
|
|
2059
|
+
interpolated_rows=stats["interpolated_rows"],
|
|
2060
|
+
merges=stats["merges"],
|
|
2061
|
+
reid_merges=stats["reid_merges"],
|
|
2062
|
+
splits=stats["splits"],
|
|
2063
|
+
elapsed_ms=elapsed_ms,
|
|
2064
|
+
reid_merge_events=stats["reid_merge_events"],
|
|
2065
|
+
)
|
|
2066
|
+
|
|
2067
|
+
|
|
2068
|
+
__all__ = ["PostprocessResult", "postprocess_records", "postprocess_tracks_array"]
|