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4 |
+
ByteTrack (Zhang et al., 2022) key insight: use ALL detection boxes
|
| 5 |
+
(high + low confidence) for association, not just high-confidence ones.
|
| 6 |
+
Low-confidence detections are valuable for tracking occluded/blurred faces.
|
| 7 |
+
|
| 8 |
+
Flow:
|
| 9 |
+
1. High-confidence detections → match to existing tracks (IoU + Kalman)
|
| 10 |
+
2. Unmatched tracks + low-confidence detections → second matching round
|
| 11 |
+
3. Remaining unmatched high-confidence → initialize new tracks
|
| 12 |
+
4. Unmatched tracks → mark lost → delete after max_lost frames
|
| 13 |
+
|
| 14 |
+
Kalman state: [x_center, y_center, aspect_ratio, height, vx, vy, va, vh]
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
from typing import List, Tuple, Optional, Dict
|
| 19 |
+
from dataclasses import dataclass, field
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class KalmanBoxTracker:
|
| 23 |
+
"""
|
| 24 |
+
Kalman filter for bounding box tracking.
|
| 25 |
+
|
| 26 |
+
State vector: [cx, cy, s, r, vcx, vcy, vs, vr]
|
| 27 |
+
where s = area, r = aspect ratio (w/h)
|
| 28 |
+
|
| 29 |
+
Measurement: [cx, cy, s, r]
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
_count = 0
|
| 33 |
+
|
| 34 |
+
def __init__(self, bbox: np.ndarray):
|
| 35 |
+
"""Initialize tracker with bounding box [x1, y1, x2, y2]."""
|
| 36 |
+
# State: [cx, cy, s, r, vcx, vcy, vs, vr]
|
| 37 |
+
self.dim_x = 8
|
| 38 |
+
self.dim_z = 4
|
| 39 |
+
|
| 40 |
+
# State vector
|
| 41 |
+
self.x = np.zeros(self.dim_x)
|
| 42 |
+
cx = (bbox[0] + bbox[2]) / 2
|
| 43 |
+
cy = (bbox[1] + bbox[3]) / 2
|
| 44 |
+
w = bbox[2] - bbox[0]
|
| 45 |
+
h = bbox[3] - bbox[1]
|
| 46 |
+
self.x[0] = cx
|
| 47 |
+
self.x[1] = cy
|
| 48 |
+
self.x[2] = w * h # area
|
| 49 |
+
self.x[3] = w / max(h, 1e-6) # aspect ratio
|
| 50 |
+
|
| 51 |
+
# State covariance
|
| 52 |
+
self.P = np.eye(self.dim_x)
|
| 53 |
+
self.P[4:, 4:] *= 10 # High uncertainty on velocities
|
| 54 |
+
self.P *= 10
|
| 55 |
+
|
| 56 |
+
# Transition matrix (constant velocity)
|
| 57 |
+
self.F = np.eye(self.dim_x)
|
| 58 |
+
self.F[0, 4] = 1 # cx += vcx
|
| 59 |
+
self.F[1, 5] = 1 # cy += vcy
|
| 60 |
+
self.F[2, 6] = 1 # s += vs
|
| 61 |
+
self.F[3, 7] = 1 # r += vr
|
| 62 |
+
|
| 63 |
+
# Measurement matrix
|
| 64 |
+
self.H = np.zeros((self.dim_z, self.dim_x))
|
| 65 |
+
self.H[:4, :4] = np.eye(4)
|
| 66 |
+
|
| 67 |
+
# Process noise
|
| 68 |
+
self.Q = np.eye(self.dim_x) * 0.01
|
| 69 |
+
self.Q[4:, 4:] *= 0.01
|
| 70 |
+
|
| 71 |
+
# Measurement noise
|
| 72 |
+
self.R = np.eye(self.dim_z) * 1.0
|
| 73 |
+
|
| 74 |
+
KalmanBoxTracker._count += 1
|
| 75 |
+
self.id = KalmanBoxTracker._count
|
| 76 |
+
self.age = 0
|
| 77 |
+
self.hits = 0
|
| 78 |
+
self.time_since_update = 0
|
| 79 |
+
|
| 80 |
+
def predict(self) -> np.ndarray:
|
| 81 |
+
"""Predict next state. Returns predicted bbox [x1, y1, x2, y2]."""
|
| 82 |
+
# Prevent negative area
|
| 83 |
+
if self.x[2] + self.x[6] <= 0:
|
| 84 |
+
self.x[6] = 0
|
| 85 |
+
|
| 86 |
+
# Kalman predict
|
| 87 |
+
self.x = self.F @ self.x
|
| 88 |
+
self.P = self.F @ self.P @ self.F.T + self.Q
|
| 89 |
+
self.age += 1
|
| 90 |
+
self.time_since_update += 1
|
| 91 |
+
|
| 92 |
+
return self._state_to_bbox()
|
| 93 |
+
|
| 94 |
+
def update(self, bbox: np.ndarray):
|
| 95 |
+
"""Update state with measurement [x1, y1, x2, y2]."""
|
| 96 |
+
cx = (bbox[0] + bbox[2]) / 2
|
| 97 |
+
cy = (bbox[1] + bbox[3]) / 2
|
| 98 |
+
w = bbox[2] - bbox[0]
|
| 99 |
+
h = bbox[3] - bbox[1]
|
| 100 |
+
z = np.array([cx, cy, w * h, w / max(h, 1e-6)])
|
| 101 |
+
|
| 102 |
+
# Kalman update
|
| 103 |
+
y = z - self.H @ self.x
|
| 104 |
+
S = self.H @ self.P @ self.H.T + self.R
|
| 105 |
+
K = self.P @ self.H.T @ np.linalg.inv(S)
|
| 106 |
+
self.x = self.x + K @ y
|
| 107 |
+
self.P = (np.eye(self.dim_x) - K @ self.H) @ self.P
|
| 108 |
+
|
| 109 |
+
self.hits += 1
|
| 110 |
+
self.time_since_update = 0
|
| 111 |
+
|
| 112 |
+
def _state_to_bbox(self) -> np.ndarray:
|
| 113 |
+
"""Convert state [cx, cy, s, r] to bbox [x1, y1, x2, y2]."""
|
| 114 |
+
cx, cy, s, r = self.x[:4]
|
| 115 |
+
s = max(s, 1)
|
| 116 |
+
w = np.sqrt(s * r)
|
| 117 |
+
h = s / max(w, 1e-6)
|
| 118 |
+
return np.array([cx - w/2, cy - h/2, cx + w/2, cy + h/2])
|
| 119 |
+
|
| 120 |
+
def get_state(self) -> np.ndarray:
|
| 121 |
+
"""Get current bbox estimate."""
|
| 122 |
+
return self._state_to_bbox()
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
@dataclass
|
| 126 |
+
class Track:
|
| 127 |
+
"""Single face track."""
|
| 128 |
+
track_id: int
|
| 129 |
+
bbox: np.ndarray # Current bounding box [x1, y1, x2, y2]
|
| 130 |
+
score: float # Detection confidence
|
| 131 |
+
age: int = 0 # Frames since track creation
|
| 132 |
+
hits: int = 0 # Total detection associations
|
| 133 |
+
time_since_update: int = 0
|
| 134 |
+
is_confirmed: bool = False
|
| 135 |
+
landmarks: Optional[np.ndarray] = None
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
class ByteTracker:
|
| 139 |
+
"""
|
| 140 |
+
ByteTrack face tracker for video temporal stability.
|
| 141 |
+
|
| 142 |
+
Features:
|
| 143 |
+
- Two-stage association (high + low confidence)
|
| 144 |
+
- Kalman filter prediction for smooth trajectories
|
| 145 |
+
- Track lifecycle management (init, confirm, lose, delete)
|
| 146 |
+
- IoU-based association (no appearance features needed for faces)
|
| 147 |
+
|
| 148 |
+
Args:
|
| 149 |
+
high_thresh: High detection confidence threshold (default: 0.5)
|
| 150 |
+
low_thresh: Low detection confidence threshold (default: 0.1)
|
| 151 |
+
match_thresh: IoU threshold for association (default: 0.3)
|
| 152 |
+
max_lost: Frames before deleting lost tracks (default: 30)
|
| 153 |
+
min_hits: Detections needed to confirm a track (default: 3)
|
| 154 |
+
"""
|
| 155 |
+
|
| 156 |
+
def __init__(self,
|
| 157 |
+
high_thresh: float = 0.5,
|
| 158 |
+
low_thresh: float = 0.1,
|
| 159 |
+
match_thresh: float = 0.3,
|
| 160 |
+
max_lost: int = 30,
|
| 161 |
+
min_hits: int = 3):
|
| 162 |
+
self.high_thresh = high_thresh
|
| 163 |
+
self.low_thresh = low_thresh
|
| 164 |
+
self.match_thresh = match_thresh
|
| 165 |
+
self.max_lost = max_lost
|
| 166 |
+
self.min_hits = min_hits
|
| 167 |
+
|
| 168 |
+
self.tracks: List[KalmanBoxTracker] = []
|
| 169 |
+
self.track_scores: Dict[int, float] = {}
|
| 170 |
+
self.frame_count = 0
|
| 171 |
+
|
| 172 |
+
def update(self, detections: np.ndarray, scores: np.ndarray,
|
| 173 |
+
landmarks: Optional[np.ndarray] = None) -> List[Track]:
|
| 174 |
+
"""
|
| 175 |
+
Update tracker with new detections.
|
| 176 |
+
|
| 177 |
+
Args:
|
| 178 |
+
detections: [N, 4] bounding boxes (x1, y1, x2, y2)
|
| 179 |
+
scores: [N] confidence scores
|
| 180 |
+
landmarks: [N, 10] optional landmarks
|
| 181 |
+
|
| 182 |
+
Returns:
|
| 183 |
+
List of active Track objects with stable IDs
|
| 184 |
+
"""
|
| 185 |
+
self.frame_count += 1
|
| 186 |
+
|
| 187 |
+
# Split into high and low confidence
|
| 188 |
+
high_mask = scores >= self.high_thresh
|
| 189 |
+
low_mask = (scores >= self.low_thresh) & (~high_mask)
|
| 190 |
+
|
| 191 |
+
high_dets = detections[high_mask]
|
| 192 |
+
high_scores = scores[high_mask]
|
| 193 |
+
low_dets = detections[low_mask]
|
| 194 |
+
low_scores = scores[low_mask]
|
| 195 |
+
|
| 196 |
+
high_lmk = landmarks[high_mask] if landmarks is not None else None
|
| 197 |
+
low_lmk = landmarks[low_mask] if landmarks is not None else None
|
| 198 |
+
|
| 199 |
+
# Predict existing tracks
|
| 200 |
+
predicted_boxes = []
|
| 201 |
+
for t in self.tracks:
|
| 202 |
+
pred = t.predict()
|
| 203 |
+
predicted_boxes.append(pred)
|
| 204 |
+
predicted_boxes = np.array(predicted_boxes) if predicted_boxes else np.empty((0, 4))
|
| 205 |
+
|
| 206 |
+
# === First association: high-confidence detections ===
|
| 207 |
+
if len(self.tracks) > 0 and len(high_dets) > 0:
|
| 208 |
+
iou_matrix = self._iou_batch(predicted_boxes, high_dets)
|
| 209 |
+
matches_h, unmatched_tracks_h, unmatched_dets_h = \
|
| 210 |
+
self._hungarian_match(iou_matrix, self.match_thresh)
|
| 211 |
+
else:
|
| 212 |
+
matches_h = np.empty((0, 2), dtype=int)
|
| 213 |
+
unmatched_tracks_h = list(range(len(self.tracks)))
|
| 214 |
+
unmatched_dets_h = list(range(len(high_dets)))
|
| 215 |
+
|
| 216 |
+
# Update matched tracks
|
| 217 |
+
for t_idx, d_idx in matches_h:
|
| 218 |
+
self.tracks[t_idx].update(high_dets[d_idx])
|
| 219 |
+
self.track_scores[self.tracks[t_idx].id] = high_scores[d_idx]
|
| 220 |
+
|
| 221 |
+
# === Second association: low-confidence detections with remaining tracks ===
|
| 222 |
+
remaining_tracks = [self.tracks[i] for i in unmatched_tracks_h]
|
| 223 |
+
if len(remaining_tracks) > 0 and len(low_dets) > 0:
|
| 224 |
+
remaining_preds = np.array([t.get_state() for t in remaining_tracks])
|
| 225 |
+
iou_matrix_l = self._iou_batch(remaining_preds, low_dets)
|
| 226 |
+
matches_l, unmatched_tracks_l, _ = \
|
| 227 |
+
self._hungarian_match(iou_matrix_l, self.match_thresh)
|
| 228 |
+
|
| 229 |
+
for t_local, d_idx in matches_l:
|
| 230 |
+
remaining_tracks[t_local].update(low_dets[d_idx])
|
| 231 |
+
self.track_scores[remaining_tracks[t_local].id] = low_scores[d_idx]
|
| 232 |
+
else:
|
| 233 |
+
unmatched_tracks_l = list(range(len(remaining_tracks)))
|
| 234 |
+
|
| 235 |
+
# === Initialize new tracks from unmatched high-confidence detections ===
|
| 236 |
+
for d_idx in unmatched_dets_h:
|
| 237 |
+
new_tracker = KalmanBoxTracker(high_dets[d_idx])
|
| 238 |
+
self.tracks.append(new_tracker)
|
| 239 |
+
self.track_scores[new_tracker.id] = high_scores[d_idx]
|
| 240 |
+
|
| 241 |
+
# === Remove lost tracks ===
|
| 242 |
+
active_tracks = []
|
| 243 |
+
for t in self.tracks:
|
| 244 |
+
if t.time_since_update <= self.max_lost:
|
| 245 |
+
active_tracks.append(t)
|
| 246 |
+
self.tracks = active_tracks
|
| 247 |
+
|
| 248 |
+
# === Build output ===
|
| 249 |
+
results = []
|
| 250 |
+
for t in self.tracks:
|
| 251 |
+
if t.hits >= self.min_hits or self.frame_count <= self.min_hits:
|
| 252 |
+
bbox = t.get_state()
|
| 253 |
+
score = self.track_scores.get(t.id, 0.5)
|
| 254 |
+
track = Track(
|
| 255 |
+
track_id=t.id,
|
| 256 |
+
bbox=bbox,
|
| 257 |
+
score=score,
|
| 258 |
+
age=t.age,
|
| 259 |
+
hits=t.hits,
|
| 260 |
+
time_since_update=t.time_since_update,
|
| 261 |
+
is_confirmed=(t.hits >= self.min_hits),
|
| 262 |
+
)
|
| 263 |
+
results.append(track)
|
| 264 |
+
|
| 265 |
+
return results
|
| 266 |
+
|
| 267 |
+
@staticmethod
|
| 268 |
+
def _iou_batch(boxes1: np.ndarray, boxes2: np.ndarray) -> np.ndarray:
|
| 269 |
+
"""Compute IoU matrix between two sets of boxes."""
|
| 270 |
+
x1 = np.maximum(boxes1[:, 0:1], boxes2[:, 0:1].T)
|
| 271 |
+
y1 = np.maximum(boxes1[:, 1:2], boxes2[:, 1:2].T)
|
| 272 |
+
x2 = np.minimum(boxes1[:, 2:3], boxes2[:, 2:3].T)
|
| 273 |
+
y2 = np.minimum(boxes1[:, 3:4], boxes2[:, 3:4].T)
|
| 274 |
+
|
| 275 |
+
inter = np.maximum(0, x2 - x1) * np.maximum(0, y2 - y1)
|
| 276 |
+
|
| 277 |
+
area1 = (boxes1[:, 2] - boxes1[:, 0]) * (boxes1[:, 3] - boxes1[:, 1])
|
| 278 |
+
area2 = (boxes2[:, 2] - boxes2[:, 0]) * (boxes2[:, 3] - boxes2[:, 1])
|
| 279 |
+
|
| 280 |
+
union = area1[:, None] + area2[None, :] - inter
|
| 281 |
+
return inter / (union + 1e-6)
|
| 282 |
+
|
| 283 |
+
@staticmethod
|
| 284 |
+
def _hungarian_match(iou_matrix: np.ndarray, threshold: float):
|
| 285 |
+
"""Greedy matching by IoU (fast approximation of Hungarian algorithm)."""
|
| 286 |
+
matches = []
|
| 287 |
+
unmatched_rows = list(range(iou_matrix.shape[0]))
|
| 288 |
+
unmatched_cols = list(range(iou_matrix.shape[1]))
|
| 289 |
+
|
| 290 |
+
if iou_matrix.size == 0:
|
| 291 |
+
return np.empty((0, 2), dtype=int), unmatched_rows, unmatched_cols
|
| 292 |
+
|
| 293 |
+
# Greedy: take highest IoU pairs iteratively
|
| 294 |
+
while True:
|
| 295 |
+
if iou_matrix.size == 0:
|
| 296 |
+
break
|
| 297 |
+
max_idx = np.unravel_index(iou_matrix.argmax(), iou_matrix.shape)
|
| 298 |
+
if iou_matrix[max_idx] < threshold:
|
| 299 |
+
break
|
| 300 |
+
|
| 301 |
+
row, col = max_idx
|
| 302 |
+
matches.append([unmatched_rows[row], unmatched_cols[col]])
|
| 303 |
+
|
| 304 |
+
# Remove matched row and col
|
| 305 |
+
iou_matrix = np.delete(iou_matrix, row, axis=0)
|
| 306 |
+
iou_matrix = np.delete(iou_matrix, col, axis=1)
|
| 307 |
+
unmatched_rows.pop(row)
|
| 308 |
+
unmatched_cols.pop(col)
|
| 309 |
+
|
| 310 |
+
return (np.array(matches) if matches else np.empty((0, 2), dtype=int),
|
| 311 |
+
unmatched_rows, unmatched_cols)
|
| 312 |
+
|
| 313 |
+
def reset(self):
|
| 314 |
+
"""Reset tracker state."""
|
| 315 |
+
self.tracks.clear()
|
| 316 |
+
self.track_scores.clear()
|
| 317 |
+
self.frame_count = 0
|
| 318 |
+
KalmanBoxTracker._count = 0
|