Sub topic 9
Appearance embeddings and re-identification
This chapter assumes you know how IoU matching, the Hungarian algorithm, and a Kalman filter work in a tracker such as SORT. You also need basic NumPy and a feel for vectors and cosine similarity. By the end you should be able to explain what an appearance embedding is, build an appearance cost matrix, and say when it helps and when it hurts.
Why motion and overlap are not enough
SORT decides who is who from geometry alone. The Kalman filter predicts where each track should be, and IoU measures how well a detection fits that prediction. This works while objects stay apart and keep moving smoothly.
It breaks in two common situations:
- Occlusion. A person walks behind a pole or another person. The track coasts on its prediction, but the person may reappear far from where the prediction says. IoU is then zero, and the old track dies while a new one starts under a new ID.
- Crossing paths. Two people overlap in the image and swap sides. Their boxes are similar in size and position, so IoU cannot tell which detection belongs to which track.
In both cases the geometry is ambiguous, but the objects still look different. One wears a red jacket and the other a grey one. Appearance cues use that visual information.
What an appearance embedding is
An appearance embedding is a fixed-length vector, for example 128 or 512 numbers, computed from the image crop inside a detection box. A neural network called a re-identification (re-ID) network produces it. Re-identification means recognising that two crops show the same individual, even when they come from different times, poses, or camera views.
The network is trained so that distance in embedding space reflects identity:
- Crops of the same person map to nearby vectors.
- Crops of different people map to distant vectors.
Common training objectives are a classification loss over identities in a labelled dataset, a triplet loss (anchor and positive closer than anchor and negative by a margin), or a mix of both. Pedestrian re-ID datasets such as Market-1501 are typical sources. Many trackers also fine-tune on crops from the tracking benchmark's own training set.
Inference per frame is simple: crop each detection, resize it to the network's input size, and run a forward pass. The tracker never needs to know what the individual numbers mean.
Comparing embeddings
Embeddings are usually compared with cosine distance, which is 1 minus the cosine similarity. Normalising each vector to unit length first turns the similarity into a plain dot product. A distance near 0 means the crops look alike. Larger values mean they look different. Random vectors in a high-dimensional space have cosine similarity near 0, so unrelated crops give distances near 1.
A track also holds more than one appearance. A single crop is noisy, because pose, blur, and partial occlusion all shift the embedding. There are two common ways to keep a richer memory:
- Gallery. Keep the last K embeddings of the track (DeepSORT keeps up to 100). The distance to a detection is the smallest distance to any stored sample.
- Exponential moving average (EMA). Keep one vector per track and update it as
f = a*f + (1-a)*newwithanear 0.9, then renormalise. This is cheaper and smoother, but one bad crop leaks into the average.
The code below builds a gallery-based cost matrix, gates it, and solves the assignment.
import numpy as np
from scipy.optimize import linear_sum_assignment
def l2_normalize(x, eps=1e-12):
x = np.asarray(x, dtype=float)
return x / np.maximum(np.linalg.norm(x, axis=-1, keepdims=True), eps)
def appearance_cost(galleries, det_embs):
"""galleries: list of (K_i, D) arrays, one per track.
det_embs: (M, D) array. Returns an (N, M) cosine-distance matrix,
taking the best (smallest) distance over each track's gallery."""
dets = l2_normalize(det_embs)
cost = np.zeros((len(galleries), len(dets)))
for i, gallery in enumerate(galleries):
sims = l2_normalize(gallery) @ dets.T # (K_i, M)
cost[i] = 1.0 - sims.max(axis=0)
return cost
def match_appearance(galleries, det_embs, max_dist=0.3):
cost = appearance_cost(galleries, det_embs)
rows, cols = linear_sum_assignment(cost)
matches = [(r, c) for r, c in zip(rows, cols) if cost[r, c] <= max_dist]
matched_t = {r for r, _ in matches}
matched_d = {c for _, c in matches}
unmatched_t = [i for i in range(len(galleries)) if i not in matched_t]
unmatched_d = [j for j in range(len(det_embs)) if j not in matched_d]
return matches, unmatched_t, unmatched_d
rng = np.random.default_rng(0)
dim = 128
person_a, person_b = rng.normal(size=(2, dim))
galleries = [
person_a + 0.1 * rng.normal(size=(3, dim)), # track 0 looks like A
person_b + 0.1 * rng.normal(size=(3, dim)), # track 1 looks like B
]
detections = np.stack([
person_b + 0.1 * rng.normal(size=dim), # detection 0 is B
person_a + 0.1 * rng.normal(size=dim), # detection 1 is A
rng.normal(size=dim), # detection 2 is a stranger
])
print(match_appearance(galleries, detections))Track 0 pairs with detection 1 and track 1 with detection 0, so the order of the detections does not matter. The stranger stays unmatched and would start a new track. The threshold max_dist plays the same role as the IoU threshold in the earlier chapter: it rejects pairs the solver was forced to pair up.
Combining appearance with motion
Appearance is rarely used alone. A similar-looking person on the other side of the frame is still a bad match. Trackers therefore use both signals, in one of two ways:
- Gating. Use motion to rule out impossible pairs. DeepSORT rejects a pair when the Mahalanobis distance between the Kalman prediction and the detection exceeds a chi-square threshold (9.4877 for four degrees of freedom at 95%). Appearance then ranks the surviving pairs.
- Weighted cost. Use
cost = w * motion_cost + (1 - w) * appearance_cost, then gate. Settingwto 0 lets appearance dominate. This suits moving cameras, where the Kalman prediction is unreliable.
After a match, the tracker adds the new embedding to the gallery or folds it into the EMA. It should do this only when the detection is trustworthy. Pushing a crop of a partly hidden person into the gallery pollutes the track's memory and causes later mismatches.
What appearance buys you, and what it costs
| Property | IoU and motion only | With appearance embeddings |
|---|---|---|
| Speed | Very fast, no neural network | Extra forward pass per detection |
| Short occlusions | Often recovered if the object moves predictably | Recovered even if it reappears elsewhere |
| Long occlusions | Track expires, new ID | Track kept longer, can be re-identified |
| Crossing, similar boxes | Frequent ID switches | Fewer switches when clothing differs |
| Similar-looking objects | Not affected | Can confuse identities (uniforms, vehicles of one model) |
| Moving camera | Predictions drift | Less affected by camera motion |
Appearance helps most for long gaps. DeepSORT keeps lost tracks for around 30 frames and uses appearance to reconnect them, where SORT would already have given up.
Gotchas and failure modes
- Domain shift. A re-ID network trained on street pedestrians may perform poorly on sports, retail footage, or animals. Embeddings from the wrong domain look random or collapse together. Fine-tune on in-domain crops, or test the network by checking same-ID versus different-ID distance histograms on your own data.
- Bad crops. A box that includes half of a neighbour, or only a head, produces an embedding that matches neither person. Low-confidence and heavily overlapping detections are the usual cause. Skip gallery updates for them.
- Look-alike objects. Sports teams, uniformed staff, and cars of the same model are hard. Appearance cannot separate them, so motion must carry more of the load.
- Threshold sensitivity. The cosine threshold is not portable between networks. A value tuned for one model, such as 0.2, may be far too strict or loose for another. Tune it on validation data.
- Latency. Running a CNN on every crop, every frame, can cost more than the tracker itself. Batch the crops, use a small network, or compute embeddings only for detections that need them.
- Stale galleries. Lighting and pose change over time. A gallery limited to recent samples adapts better than one that keeps old ones forever, but it also forgets what the person looked like before an occlusion.
Exercises
Exercise
A track's gallery holds three embeddings. A new detection has cosine distances 0.55, 0.12, and 0.60 to them. What distance does the gallery-based cost use, and why might this be better than averaging the three?
Show answer
The cost is 0.12, the smallest distance. The gallery exists to cover several poses and views of the same object, so a match to any one view is good evidence. Averaging would give about 0.42, which penalises the detection for not resembling views that were never meant to match it.
Exercise
Two pedestrians in identical uniforms cross paths and the tracker swaps their IDs, even though appearance is enabled. Give one reason this happens and one change that could reduce it.
Show answer
The embeddings of the two people are nearly identical, so appearance cost cannot separate them and the assignment depends on small noise. To reduce swaps, weight the motion cost more heavily, tighten the Mahalanobis gate, or fine-tune the re-ID network on data where uniforms are shared so it learns finer cues such as build and gait.