Sub topic 2
Matching detections to tracks with the Hungarian algorithm
This chapter assumes you know Python, NumPy, and basic linear algebra, and that you can read bounding boxes as [x1, y1, x2, y2]. It covers how a tracker links each new frame's detections to existing tracks, how a constant-velocity Kalman filter predicts where a track will be, how tracks are born and retired, and how these parts combine into SORT.
Matching detections to tracks with the Hungarian algorithm
Each frame, the tracker has a set of tracks and a set of detections. Matching pairs them so that the total overlap is as high as possible. Intersection over union (IoU) measures overlap: the shared area of two boxes divided by the area covered by either box.
The matcher turns IoU into a cost matrix (1 - IoU) and solves the assignment problem with the Hungarian algorithm, which scipy.optimize.linear_sum_assignment implements. A gating threshold then rejects weak pairs, so a track with no real match stays unmatched.
import numpy as np
from scipy.optimize import linear_sum_assignment
def iou_matrix(a, b):
a = np.asarray(a, float).reshape(-1, 1, 4)
b = np.asarray(b, float).reshape(1, -1, 4)
iw = np.clip(np.minimum(a[..., 2], b[..., 2]) - np.maximum(a[..., 0], b[..., 0]), 0, None)
ih = np.clip(np.minimum(a[..., 3], b[..., 3]) - np.maximum(a[..., 1], b[..., 1]), 0, None)
inter = iw * ih
area_a = (a[..., 2] - a[..., 0]) * (a[..., 3] - a[..., 1])
area_b = (b[..., 2] - b[..., 0]) * (b[..., 3] - b[..., 1])
return inter / np.maximum(area_a + area_b - inter, 1e-9)
def match(track_boxes, det_boxes, iou_thresh=0.3):
if len(track_boxes) == 0 or len(det_boxes) == 0:
return [], list(range(len(track_boxes))), list(range(len(det_boxes)))
iou = iou_matrix(track_boxes, det_boxes)
rows, cols = linear_sum_assignment(1.0 - iou) # minimises total cost
matches = [(r, c) for r, c in zip(rows, cols) if iou[r, c] >= iou_thresh]
matched_t = {r for r, _ in matches}
matched_d = {c for _, c in matches}
unmatched_t = [i for i in range(len(track_boxes)) if i not in matched_t]
unmatched_d = [j for j in range(len(det_boxes)) if j not in matched_d]
return matches, unmatched_t, unmatched_d
tracks = [[10, 10, 50, 50], [100, 100, 150, 160]]
dets = [[102, 104, 152, 162], [12, 11, 52, 52], [300, 300, 340, 340]]
print(match(tracks, dets))The gate matters. Without it, the solver still track with some detection, even a poor one.
Predicting motion with a Kalman filter
A constman filter keeps a state [cx, cy, vx, vy] (box center and its speed) and an P. Each frame it runs two steps:
- Predict:
x = F xandP = F P, which moves the center forward by its velocity. - Update: with a matched detection
z, it computes the innovationy = z - H xand the Kalman gainK, then corrects the state.
import numpy as np
class ConstantVelocityKalman:
def __init__(self, cx, cy, dt=1.0):
self.x = np.array([cx, cy, 0.0, 0.0])
self.P = np.diag([10.0, 10.0, 100.0, 100.0])
self.F = np.array([[1, 0, dt, 0], [0, 1, 0, dt],
[0, 0, 1, 0], [0, 0, 0, 1]], float)
self.H = np.array([[1, 0, 0, 0], [0, 1, 0, 0]], float)
self.Q = np.eye(4) * 0.01 # process noise
self.R = np.eye(2) * 1.0 # measurement noise
def predict(self):
self.x = self.F @ self.x
self.P = self.F @ self.P @ self.F.T + self.Q
return self.x[:2]
def update(self, z):
y = np.asarray(z, float) - self.H @ self.x
S = self.H @ self.P @ self.H.T + self.R
K = self.P @ self.H.T @ np.linalg.inv(S)
self.x = self.x + K @ y
self.P = (np.eye(4) - K @ self.H) @ self.P
kf = ConstantVelocityKalman(100.0, 50.0)
for z in [(103, 50), (106, 51), (109, 51)]:
kf.predict()
kf.update(z)
print(kf.x) # vx is positive
print(kf.predict())Q and R set how much the filter trusts its motion model versus the detector. A larger Q makes the track follow detections more closely. A larger R makes it smoother.
Creating, confirming, and deleting tracks
A new unmatched detection starts a tentative track. It becomes confirmed after min_hits matches, so one-frame false positives never receive an ID that reaches the output. A track that goes unmatched increments its misses counter. Once misses exceeds max_misses, the track is deleted. A matched track resets its counter to zero.
Putting it together: SORT
SORT (Simple Online and Realtime Tracking) runs the three parts above on every frame. It predicts each track forward, matches the predictions to detections by IoU, updates the matched tracks, and creates or retires tracks. It uses no appearance features, so it relies entirely on motion and overlap.
import numpy as np
from scipy.optimize import linear_sum_assignment
def iou_matrix(a, b):
a = np.asarray(a, float).reshape(-1, 1, 4)
b = np.asarray(b, float).reshape(1, -1, 4)
iw = np.clip(np.minimum(a[..., 2], b[..., 2]) - np.maximum(a[..., 0], b[..., 0]), 0, None)
ih = np.clip(np.minimum(a[..., 3], b[..., 3]) - np.maximum(a[..., 1], b[..., 1]), 0, None)
inter = iw * ih
area_a = (a[..., 2] - a[..., 0]) * (a[..., 3] - a[..., 1])
area_b = (b[..., 2] - b[..., 0]) * (b[..., 3] - b[..., 1])
return inter / np.maximum(area_a + area_b9)
def match(track_boxes, det_boxes, iou_thresh=0.3):
if len(track_boxes) == 0 or len(det_boxes) == 0range(len(track_boxes))), list(range(len(det_boxes)))
iou = iou_matrix(track_boxes, det_boxes)
rows, cols =ment(1.0 - iou)
matches = [(r, c) for r, c in zip(rows, cols) if iou[r, c] >= iou_thresh]
matched _ in matches}
matched_d = {c for _, c in matches}
unmatched_t = [i for i in range(len(track_boxes)) if i not in matched_td = [j for j in range(len(det_boxes)) if j not in matched_d]
return matches, unmatched_t, unmatched_d
class ConstantVelocityinit__(self, cx, cy, dt=1.0):
self.x = np.array([cx, cy, 0.0, 0.0])
self.P = np.diag([10 100.0, 100.0])
self.F = np.array([[1, 0, dt, 0], [0, 1, 0, dt],
[0, 0, 1,, 0, 1]], float)
self.H = np.array([[1, 0, 0, 0], [0, 1, 0, 0]], float)
self.Q = np..01
self.R = np.eye(2) * 1.0
def predict(self):
self.x = self.F @ self.x
self.P = self.F @ self.P self.Q
return self.x[:2]
def update(self, z):
y = np.asarray(z, float) - self.H @ self.x
S = self.H @ selfT + self.R
K = self.P @ self.H.T @ np.linalg.inv(S)
self.x = self.x + K @ y
self.P = (np.e self.H) @ self.P
class Track:
_next_id = 1
def __init__(self, box):
self.id = Track._next_id
Track._next_id += 1, y1, x2, y2 = box
self.w, self.h = x2 - x1, y2 - y1
self.kf = ConstantVelocityKalman((x2, (y1 + y2) / 2)
self.hits = 1
self.misses = 0
self.confirmed = False
def predict_box(self):
cx, cy = self.kf.predict()
return [cx - self.w / 2, cy - self.h / 2, cx + self.w / 2, cy + self.h / 2]
def update(self, box):
x1, y1, x2, y2 = box
self.w, self.h = x2 - x1, y2 - y1
self.kf.update(((x1 + x2) / 2, (y1 + y2) / 2))
self.hits += 1
self.misses = 0
def step(tracks, dets, iou_thresh=0.3, max_misses=2, min_hits=2):
preds = [t.predict_box() for t in tracks]
matches, unmatched_t, unmatched_d = match(preds, dets, iou_thresh)
for ti, di in matches:
tracks[ti].update(dets[di])
if tracks[ti].hits >= min_hits:
tracks[ti].confirmed = True
for ti in unmatched_t:
tracks[ti].misses += 1
for di in unmatched_d:
tracks.append(Track(dets[di]))
return [t for t in tracks if t.misses <= max_misses]
tracks = []
frames = [
[[10, 10, 50, 50]],
[[14, 10, 54, 50]],
[],
[[22, 11, 62, 51]],
]
for dets in frames:
tracks = step(tracks, dets)
print([(t.id, t.hits, t.misses, t.confirmed) for t in tracks])Exercise
In the SORT loop, a track misses three frames in a row, and max_misses is 2. What happens to it, and what would change if the track had a high-confidence match in the fourth frame?
Show answer
The track is deleted after its third consecutive miss, because misses (3) exceeds maxmisses (2). If it had matched in the fourth frame, that match would not revive it, because the deletion already happened. Raising maxmisses to 3 or more would keep the track alive through a three-frame gap, so the object could keep its ID after a longer occlusion.