Sub topic 8
Putting it together: SORT
This chapter assembles the pieces from earlier chapters into SORT (Simple Online and Realtime Tracking, Bewley et al., 2016). It assumes you have read the chapters on IoU, Hungarian matching, the Kalman filter, and track lifecycles. You should be comfortable with NumPy and with a Kalman filter's predict and update steps.
What SORT is
SORT is a tracking-by-detection algorithm with only two ingredients:
- A Kalman filter per track that predicts where the box will be in the next frame.
- Hungarian matching on IoU between those predicted boxes and the new detections.
It has no appearance model and no learned components. All the intelligence lives in the detector, which makes SORT very fast, often thousands of frames per second on the tracker alone. It is also the baseline that DeepSORT and ByteTrack modify.
SORT is online. It uses only the current and earlier frames and never revises a past decision. That matters for live video, and it explains several of the failure modes below.
The state vector
The Kalman filter in the previous chapter tracked a center point. SORT tracks a whole box with a seven-dimensional state:
[cx, cy, s, r, vx, vy, vs]
cx, cyis the box center.sis the box area (scale).ris the aspect ratio, width divided by height.vx, vy, vsare the velocities of the center and the area.
The aspect ratio has no velocity term. SORT assumes it stays constant. Area changes as an object approaches or leaves the camera, so it gets a velocity. The measurement is the four values [cx, cy, s, r], taken from a detection.
The filter works in this parameterization, and the matcher works in corner format. Converting between [x1, y1, x2, y2] and [cx, cy, s, r] is the only bookkeeping you need:
s = w * hr = w / hw = sqrt(s * r)h = s / w
One frame of SORT
The order is fixed:
- Predict. Every existing track advances one step. This happens even for tracks that will not be matched. A track that gets no detection keeps moving along its predicted path, which is why it can be re-matched after a short gap.
- Match. Compute the IoU matrix between predicted boxes and detections. Solve the assignment on
1 - IoU. Reject pairs whose IoU is below the threshold (0.3 in the original paper). - Update. Each matched track runs a Kalman update with its detection.
- Create. Each unmatched detection starts a new track. Its velocity is unknown, so the initial velocity variance is very large and the filter trusts the first few measurements heavily.
- Delete. Tracks unmatched for more than
max_ageframes are removed. The paper uses 1, so a track survives one missed frame and dies on the second.
The parameters that matter
| Parameter | Typical value | What it controls |
|---|---|---|
| `iou_thresh` | 0.3 | Minimum overlap for a match. Too high rejects fast objects. Too low allows wrong matches. |
| `max_age` | 1 (paper), often 5 to 30 in practice | How many consecutive missed frames a track survives. |
| `min_hits` | 3 | Consecutive matches before a track is reported. Suppresses short false-positive tracks. |
| Detection score cutoff | set before the tracker | SORT sees only detections that already passed this filter. |
max_age and min_hits pull in opposite directions. A larger max_age bridges longer occlusions but keeps dead tracks alive, and a stale prediction can steal a detection that belongs to a new object. A larger min_hits removes flicker but delays the first output of every real object.
A complete implementation
The script below runs on its own with NumPy and SciPy. It repeats iou_matrix and match from the matching chapter. Its Track class replaces the earlier lifecycle class, and a Kalman filter now sits inside each track. Unlike the reference implementation, a new track counts its first detection as a hit.
import numpy as np
from scipy.optimize import linear_sum_assignment
def iou_matrix(boxes_a, boxes_b):
a = np.asarray(boxes_a, dtype=float).reshape(-1, 1, 4)
b = np.asarray(boxes_b, dtype=float).reshape(1, -1, 4)
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)
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)
matches = [(r, c) for r, c in zip(rows, cols) if iou[r, c] >= iou_thresh]
mt = {r for r, _ in matches}
md = {c for _, c in matches}
return (matches,
[i for i in range(len(track_boxes)) if i not in mt],
[j for j in range(len(det_boxes)) if j not in md])
def box_to_z(box):
w, h = box[2] - box[0], box[3] - box[1]
return np.array([box[0] + w / 2, box[1] + h / 2, w * h, w / max(h, 1e-9)])
def x_to_box(x):
s, r = max(x[2], 1e-6), max(x[3], 1e-6)
w = np.sqrt(s * r)
h = s / w
return np.array([x[0] - w / 2, x[1] - h / 2, x[0] + w / 2, x[1] + h / 2])
class Track:
_count = 0
def __init__(self, box):
Track._count += 1
self.id = Track._count
self.x = np.zeros(7)
self.x[:4] = box_to_z(box)
self.P = np.diag([10.0, 10.0, 10.0, 10.0, 1e4, 1e4, 1e4])
self.F = np.eye(7)
self.F[0, 4] = self.F[1, 5] = self.F[2, 6] = 1.0
self.H = np.eye(4, 7)
self.Q = np.diag([1.0, 1.0, 1.0, 1.0, 0.01, 0.01, 1e-4])
self.R = np.diag([1.0, 1.0, 10.0, 10.0])
self.hits = 1
self.hit_streak = 1
self.time_since_update = 0
def predict(self):
if self.x[6] + self.x[2] <= 0: # area would go negative
self.x[6] = 0.0
self.x = self.F @ self.x
self.P = self.F @ self.P @ self.F.T + self.Q
if self.time_since_update > 0:
self.hit_streak = 0
self.time_since_update += 1
return x_to_box(self.x)
def update(self, box):
self.time_since_update = 0
self.hits += 1
self.hit_streak += 1
y = box_to_z(box) - 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(7) - K @ self.H) @ self.P
class Sort:
def __init__(self, max_age=1, min_hits=3, iou_thresh=0.3):
self.max_age, self.min_hits, self.iou_thresh = max_age, min_hits, iou_thresh
self.tracks = []
self.frame_count = 0
def update(self, dets):
dets = np.asarray(dets, dtype=float).reshape(-1, 4)
self.frame_count += 1
preds = [t.predict() for t in self.tracks]
matches, _, unmatched_d = match(preds, dets, self.iou_thresh)
for ti, di in matches:
self.tracks[ti].update(dets[di])
for di in unmatched_d:
self.tracks.append(Track(dets[di]))
out = []
for t in self.tracks:
confirmed = t.hit_streak >= self.min_hits or self.frame_count <= self.min_hits
if t.time_since_update < 1 and confirmed:
out.append(np.append(x_to_box(t.x), t.id))
self.tracks = [t for t in self.tracks if t.time_since_update <= self.max_age]
return np.array(out).reshape(-1, 5)
tracker = Sort(max_age=1, min_hits=3)
frames = []
for i in range(10):
if i == 4: # the detector misses the object once
frames.append(np.empty((0, 4)))
else:
frames.append([[10 + 4 * i, 10, 50 + 4 * i, 50]])
for i, dets in enumerate(frames):
out = tracker.update(dets)
print(i, [int(row[4]) for row in out])The output is [1] for frames 0 to 3, [] for frames 4 to 6, and [1] for frames 7 to 9. The object keeps ID 1 across the gap, which is the purpose of coasting on the Kalman prediction.
The empty output on frames 5 and 6 is deliberate. The track was matched again on frame 5, so it exists, but it is not reported. Its hit_streak was reset to zero by the miss and has to climb back to min_hits before the track is output again.
Gotchas and failure modes
- Predict before match, always. Matching raw previous boxes instead of predictions makes fast-moving objects fall below the IoU threshold.
- Velocity needs time to settle. A new track has a huge velocity variance, so for the first frames the prediction is roughly "stay where you were." Fast objects that enter the scene at speed can fail their second match, and the tracker then creates a duplicate track.
- IoU gives no gradient at zero overlap. If a prediction and a detection do not overlap at all, their IoU is 0 whatever the distance between them. Any object moving farther per frame than its own width cannot be matched. Lower frame rates and small objects suffer most.
- Occlusion causes ID switches. After an occlusion longer than
max_age, the track is gone. When the object returns it gets a new ID. A longermax_agehelps only if the Kalman extrapolation stays accurate, and constant-velocity prediction degrades quickly when the object turns or stops. - Camera motion breaks the motion model. The filter models motion in image coordinates. A panning camera makes every track appear to jump, and IoU collapses for all of them at once.
- Detector quality sets the ceiling. A hard confidence cutoff before tracking discards weak detections that often belong to partly occluded objects. This is the weakness ByteTrack addresses later.
When SORT is the right choice
SORT works well when objects are visible most of the time, motion is smooth, the camera is mostly still, and the tracker's compute budget is tiny. Typical uses are traffic counting from a fixed camera, conveyor belts, and as a first baseline when you build a tracking pipeline. If identities must survive long occlusions or crowds with similar-looking objects, add appearance features (DeepSORT). If weak detections are the problem, change the association strategy (ByteTrack).
Exercise
A tracker uses maxage=1 and minhits=3. An object is detected in frames 1, 2, 3, and 4, is missed in frame 5, and is detected again in frames 6, 7, and 8. Assuming matches succeed, in which of frames 5 to 8 does SORT report this object, using this chapter's rules for a track that has been running since frame 1?
Show answer
It is reported only in frame 8. In frame 5 the track coasts with timesinceupdate = 1, so it is not output. In frame 6 it is matched, but the miss reset hitstreak to 0 and it is now 1. Frame 7 gives a streak of 2. Frame 8 gives a streak of 3, which reaches minhits, so the track is output again. The track is never deleted, because timesinceupdate stays within max_age.
Exercise
Two cars drive toward each other and pass at a combined speed that moves each car more than its own width per frame. Explain why SORT is likely to lose both tracks even when the detector finds both cars in every frame, and name one change that would help.
Show answer
Each car's predicted box and its true detection no longer overlap, so IoU is 0 and the pair is rejected by the threshold. Both tracks go unmatched and are deleted after max_age frames, and both detections start new tracks with new IDs. Helpful changes include a higher frame rate, a distance-based cost such as center distance or Mahalanobis distance from the Kalman covariance, or appearance features that do not depend on overlap.