Sub topic 10
DeepSORT: motion plus appearance
This chapter assumes you know the SORT pipeline from the previous chapters: a Kalman filter predicts each track, IoU measures overlap, and the Hungarian algorithm matches detections to tracks. You also need NumPy and basic ideas about vectors and Gaussian distributions.
Why IoU-only matching breaks
SORT decides identity by geometry alone. A track keeps its ID only if a detection lands close to where the Kalman filter expects it. This fails in two common cases:
- Long occlusions. A person walks behind a pillar for two seconds. The Kalman prediction drifts, because it assumes constant velocity. When the person reappears, the predicted box no longer overlaps the new detection, so the old track dies and a new ID starts.
- Crossings. Two people pass each other. Their boxes overlap, and the Hungarian algorithm may swap the assignments. Geometry alone cannot tell the two apart.
DeepSORT (Wojke et al., 2017) keeps SORT's Kalman filter and Hungarian matching and adds an appearance cue. Each detection is described by a feature vector, and each track remembers what its object looked like. Appearance does not depend on position, so it can reconnect a track after the object has moved far from the prediction.
The appearance descriptor
An appearance descriptor is a small CNN that maps a cropped detection to a vector. The original DeepSORT uses a 128-dimensional vector from a network trained on the MARS person re-identification dataset. The vector is L2-normalized, so every descriptor has length 1.
The network is trained so that crops of the same person land close together and crops of different people land far apart. This is the re-identification idea from the previous chapter. Any re-ID network can replace the original one, but it must be trained for your object class. A pedestrian descriptor will not separate vehicles.
The descriptor runs once per detection per frame. That cost often exceeds the cost of the tracker itself, so batch the crops through the network on a GPU.
Track galleries and cosine distance
One crop is a noisy view of an object. Pose, lighting, and partial occlusion all change the vector. DeepSORT therefore stores a gallery per track: the descriptors from its last N matched detections, with N = 100 in the original.
To compare a track with a detection, take the smallest cosine distance between the detection's descriptor and any descriptor in the gallery:
dapp(i, j) = min over k of (1 − rj · g_ik)
Here rj is the detection descriptor and gik is the k-th gallery vector of track i. Because the vectors are unit length, the dot product is the cosine similarity. Using the minimum means a detection only has to resemble one past view of the track.
Gating with the Mahalanobis distance
Appearance alone can confuse two people in similar clothes who are far apart. DeepSORT first rules out detections that the motion model finds implausible. The Kalman filter gives a predicted mean and a covariance S for the measurement. The squared Mahalanobis distance of detection j from track i is:
dmotion(i, j) = (zj − μi)ᵀ Si⁻¹ (zj − μi)
Under a Gaussian model this value follows a chi-square distribution. The paper gates at the 95% quantile for 4 degrees of freedom (box center, aspect ratio, height), which is 9.4877. The Kalman filter in the earlier example measures only the center, which has 2 degrees of freedom, so the matching threshold is 5.9915.
Combining the costs
The paper's combined cost is a weighted sum:
c(i, j) = λ · dmotion(i, j) + (1 − λ) · dapp(i, j)
A pair is admissible only if it passes both gates. The two gates and what they do:
| Gate | Test | Typical value | What it removes |
|---|---|---|---|
| Motion | Mahalanobis distance below the chi-square quantile | 9.4877 (4 dof) | Detections far from the prediction |
| Appearance | Cosine distance below a threshold | 0.2 | Detections that look different |
The paper sets λ = 0 when the camera moves, so the cost is pure appearance and the Mahalanobis test is used only as a gate. A moving camera makes the Kalman prediction unreliable as a distance, but it still rules out wildly distant detections. Many implementations follow this and use appearance as the cost, with motion as the gate.
The matching cascade
DeepSORT does not solve one global assignment. It runs a matching cascade that gives priority to recently seen tracks. A track that was matched in the last frame (age 1) is matched first, then tracks missed once (age 2), and so on up to the maximum age, which is 30 in the paper.
The reason is a known failure of global matching. When a track has been occluded for a long time, its Kalman covariance grows. A large covariance makes the Mahalanobis distance small for many detections, so the stale track can steal a detection from a track that has been visible all along. The cascade prevents this by letting fresher tracks claim detections first.
After the cascade, DeepSORT runs a plain IoU assignment, as in SORT. It covers unconfirmed tracks and tracks with age 1 that are still unmatched. This helps with sudden appearance changes and with tracks that have only just started.
The lifecycle rules from the earlier chapter still apply. A new track is tentative and becomes confirmed after 3 consecutive hits. A track is deleted after more than 30 frames without a match, and a tentative track is deleted on its first miss.
A runnable sketch
The code below implements the appearance cost, the Mahalanobis gate, and the cascade. It uses scipy.optimize.linear_sum_assignment, as the earlier chapter did. In the demo, two tracks are 10 pixels apart, so geometry cannot separate them, but their appearance can.
import numpy as np
from scipy.optimize import linear_sum_assignment
INFTY = 1e5
def unit(v):
v = np.asarray(v, dtype=float)
return v / np.linalg.norm(v, axis=-1, keepdims=True)
def cosine_cost(galleries, feats):
"""galleries: list of (K_i, D) unit-vector arrays; feats: (M, D) unit vectors."""
cost = np.zeros((len(galleries), len(feats)))
for i, g in enumerate(galleries):
cost[i] = 1.0 - (g @ feats.T).max(axis=0) # min distance = 1 - max similarity
return cost
def gate(cost, means, covs, centers, thresh=5.9915):
"""Set cost to INFTY where the squared Mahalanobis distance exceeds thresh."""
out = cost.copy()
for i, (m, S) in enumerate(zip(means, covs)):
d = centers - m
maha = np.einsum("ij,jk,ik->i", d, np.linalg.inv(S), d)
out[i, maha > thresh] = INFTY
return out
def cascade(cost, ages, max_age=30, thresh=0.2):
"""ages[i] = frames since track i was last matched (1 = matched last frame)."""
unmatched_d = list(range(cost.shape[1]))
matches = []
for age in range(1, max_age + 1):
rows = [i for i, a in enumerate(ages) if a == age]
if not rows or not unmatched_d:
continue
sub = cost[np.ix_(rows, unmatched_d)]
r, c = linear_sum_assignment(sub)
for ri, ci in zip(r, c):
if sub[ri, ci] <= thresh:
matches.append((rows[ri], unmatched_d[ci]))
taken = {d for _, d in matches}
unmatched_d = [d for d in unmatched_d if d not in taken]
matched_t = {t for t, _ in matches}
unmatched_t = [i for i in range(len(ages)) if i not in matched_t]
return matches, unmatched_t, unmatched_d
galleries = [unit([[1.0, 0.0]]), unit([[0.0, 1.0]])]
feats = unit([[0.1, 1.0], [1.0, 0.1]])
means = [np.array([100.0, 100.0]), np.array([110.0, 100.0])]
covs = [np.eye(2) * 25.0, np.eye(2) * 25.0]
centers = np.array([[105.0, 100.0], [105.0, 101.0]])
cost = gate(cosine_cost(galleries, feats), means, covs, centers)
print(np.round(cost, 3))
print(cascade(cost, ages=[1, 3]))The printed matches are [(0, 1), (1, 0)]. Track 0 takes detection 1 and track 1 takes detection 0, even though both detections sit between the two predicted positions.
Gotchas and failure modes
- Gallery contamination. If a wrong match enters a gallery, every later comparison is polluted. Some implementations add a gallery only when the match is confident.
- Poor crops. Heavily occluded or tiny boxes give unreliable vectors. Skipping the gallery update for low-quality detections helps.
- Domain shift. A descriptor trained on street pedestrians may fail on sports players in identical uniforms. Fine-tune the re-ID network on your own data.
- Threshold tuning. The 0.2 cosine threshold fits the original network. A different descriptor needs its own threshold, tuned on validation data.
- Cost. Embedding every detection slows the pipeline. A tracker that runs at 100+ FPS as SORT may run at 20 FPS with DeepSORT, depending on the crop count.
- Camera motion. Appearance helps, but the Kalman prediction still degrades. Camera motion compensation is a separate fix, covered in the failure modes chapter.
Exercise
A track has been occluded for 12 frames, and its Kalman covariance has grown large. Why can a global Hungarian match on Mahalanobis distance assign it a detection that belongs to a track visible in every frame, and how does the matching cascade prevent this?
Show answer
A large covariance makes the Mahalanobis distance small for many detections, so the stale track looks like a good match for detections far from its prediction. In a single global assignment it can win a detection from a visible track. The cascade matches tracks with age 1 first, so the visible track claims its detection before the stale track (age 12) is considered. The stale track only sees the detections left over.
Exercise
In the code above, change ages=[1, 3] to ages=[40, 40] with max_age=30. What does cascade return, and why?
Show answer
It returns no matches, [0, 1] as unmatched tracks, and [0, 1] as unmatched detections. The loop only visits ages 1 to 30, so tracks with age 40 are never matched. In a full tracker such tracks would already have been deleted for exceeding the maximum age.