Sub topic 8
Putting it together: SORT
This chapter assumes you know Python, NumPy arrays, bounding boxes, and the basic idea of a Kalman filter. You also need to understand IoU, which measures the overlap between two bounding boxes.
SORT, or Simple Online and Realtime Tracking, combines three parts:
- A detector supplies bounding boxes for each video frame.
- A Kalman filter predicts where each existing object will move.
- The Hungarian algorithm matches predictions to new detections using IoU.
SORT does not recognize objects by appearance. It keeps an identity only while motion and box overlap provide enough evidence.
SORT's frame-by-frame loop
For every frame, SORT performs this sequence:
- Predict the next position of every active track.
- Compute IoU between predicted boxes and current detections.
- Solve the one-to-one assignment problem.
- Reject assignments below an IoU threshold.
- Update matched tracks with their detections.
- Increase the miss count for unmatched tracks.
- Create tracks for unmatched detections.
- Delete tracks that have missed too many frames.
The prediction step lets a track survive a short detection gap. The assignment step prevents one detection from receiving two identities.
A compact SORT-style implementation
The example uses a constant-velocity filter for each box center. It keeps the box width and height from the latest detection. Install the dependencies with pip install numpy scipy.
import numpy as np
from scipy.optimize import linear_sum_assignment
def iou_matrix(a, b):
a = np.asarray(a, float)[:, None, :]
b = np.asarray(b, float)[None, :, :]
x1 = np.maximum(a[..., 0], b[..., 0])
y1 = np.maximum(a[..., 1], b[..., 1])
x2 = np.minimum(a[..., 2], b[..., 2])
y2 = np.minimum(a[..., 3], b[..., 3])
inter = np.clip(x2 - x1, 0, None) * np.clip(y2 - y1, 0, None)
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)
class Track:
next_id = 1
def __init__(self, box):
self.id = Track.next_id
Track.next_id += 1
self.w = box[2] - box[0]
self.h = box[3] - box[1]
cx = (box[0] + box[2]) / 2
cy = (box[1] + box[3]) / 2
self.x = np.array([cx, cy, 0., 0.])
self.P = np.diag([10., 10., 100., 100.])
self.misses = 0
@property
def box(self):
cx, cy = self.x[:2]
return [cx - self.w / 2, cy - self.h / 2,
cx + self.w / 2, cy + self.h / 2]
def predict(self):
F = np.array([[1, 0, 1, 0], [0, 1, 0, 1],
[0, 0, 1, 0], [0, 0, 0, 1.]])
self.x = F @ self.x
self.P = F @ self.P @ F.T + np.eye(4) * 0.01
def update(self, box):
z = np.array([(box[0] + box[2]) / 2,
(box[1] + box[3]) / 2])
H = np.array([[1, 0, 0, 0], [0, 1, 0, 0.]])
R = np.eye(2)
y = z - H @ self.x
S = H @ self.P @ H.T + R
K = self.P @ H.T @ np.linalg.inv(S)
self.x += K @ y
self.P = (np.eye(4) - K @ H) @ self.P
self.w, self.h = box[2] - box[0], box[3] - box[1]
self.misses = 0
def sort_step(tracks, detections, threshold=0.3, max_misses=2):
for track in tracks:
track.predict()
unmatched_tracks = set(range(len(tracks)))
unmatched_detections = set(range(len(detections)))
matches = []
if tracks and detections:
ious = iou_matrix([t.box for t in tracks], detections)
rows, cols = linear_sum_assignment(1 - ious)
for r, c in zip(rows, cols):
if ious[r, c] >= threshold:
matches.append((r, c))
unmatched_tracks.discard(r)
unmatched_detections.discard(c)
for ti, di in matches:
tracks[ti].update(detections[di])
for ti in unmatched_tracks:
tracks[ti].misses += 1
for di in unmatched_detections:
tracks.append(Track(detections[di]))
return [t for t in tracks if t.misses <= max_misses]
tracks = []
for detections in [
[[10, 10, 50, 50]],
[[14, 10, 54, 50]],
[],
[[22, 11, 62, 51]],
]:
tracks = sort_step(tracks, detections)
print([(t.id, [round(v, 1) for v in t.box]) for t in tracks])Tuning and limitations
The IoU threshold controls how easily a detection can attach to a track. A threshold that is too high causes fragmentation. A threshold that is too low can cause identity switches when objects are close together.
max_misses controls how long a track can coast without a detection. Longer values help with brief occlusion but may preserve stale identities after an object leaves the scene.
SORT is fast because it uses only motion and geometry. It struggles when objects cross, the camera moves rapidly, or the detector misses an object for many frames. Appearance features and camera-motion compensation address some of these cases, but they add computation and tuning choices.
Exercise
Two nearby people cross paths, and SORT assigns person A's ID to person B. Which SORT limitation caused this error, and what kind of additional cue could reduce it?
Show answer
IoU and motion were not sufficient to distinguish the people during the crossing. An appearance embedding from a re-identification model could provide an additional identity cue.