Person Re-Identification
A shopping centre has 40 cameras whose views do not overlap. A child is reported missing; staff have one image of her from the entrance camera and need every other camera where she appears. A tracker (multi-object tracking) cannot help: it follows people within one view, frame to frame, using position and motion. Once someone leaves the view, position means nothing. Person re-identification (re-ID) matches people across cameras and time gaps by appearance alone: given a query image of a person, rank all images in a gallery from other cameras so that the same person comes first.
It looks like face recognition, and the machinery (embeddings, distances, ranking) is the same, but the input is a whole-body crop, typically 128 x 64 pixels or less, seen from behind, from above, in a different light and partly hidden by other people. The face is usually too small to use. What identifies a person over minutes or hours is mainly their clothing, which also defines the limits of re-ID: it works within a day, not across days when people change clothes.
Note: Re-ID tracks individuals through space and time, which is personal data processing under the GDPR even without names, and appearance features combined with camera locations can single out a person. Such systems need a legal basis, a data protection impact assessment, retention limits and clear signage; matching people across cameras in public spaces can fall under the EU AI Act's rules on biometric systems when it relies on physical or behavioural features. Read privacy, consent and licensing. This lesson uses only synthetic "pedestrians" drawn in code.
Query, gallery and the ranking
Two measures are standard (Market-1501, DukeMTMC-reID, withdrawn by its authors in 2019, and later benchmarks report both):
- The CMC curve (cumulative matching characteristic): rank- accuracy, the share of queries whose first correct match is among the top gallery images. Rank-1 is the headline number.
- mAP, the mean over queries of the average precision of each query's ranking. If a query has correct gallery images, found at ranks :
CMC only looks at the first hit; AP also asks whether all images of the person are near the top, which is what an operator searching for every sighting needs. The formula is the all-point AP of detection metrics applied to one ranked list. Benchmarks also remove gallery images of the query's own identity taken by the same camera, because those are too easy; in the data here query and gallery come from different cameras by construction.
The data
The course's make_reid_set draws 64 x 32 crops: a skin-coloured head, a shirt and trousers whose colours belong to the identity, on a noisy background, with a small random horizontal shift. Camera A (queries) has neutral colour; camera B (gallery, two images per person) is warmer: red is multiplied by 1.15 and blue by 0.8, as a different white balance or light would do.
import numpy as np
import matplotlib.pyplot as plt
def make_person(rng, shirt, trousers, cam_gain, h=64, w=32):
"""A 64 x 32 RGB "pedestrian" crop: skin-coloured head, shirt, trousers, on a noisy background.
cam_gain is a per-camera (3,) colour gain (lighting / white balance)."""
img = rng.normal(90, 15, (h, w, 3))
dx = int(rng.integers(-2, 3)) # small horizontal shift
img[4:16, 11 + dx:21 + dx] = [200, 160, 130] # head
img[16:38, 7 + dx:25 + dx] = shirt # torso
img[38:62, 9 + dx:23 + dx] = trousers # legs
img = img * cam_gain + rng.normal(0, 8, (h, w, 3))
return img.clip(0, 255).astype(np.uint8)
def make_reid_set(rng, n_ids=20):
"""Each identity has a shirt and trouser colour; camera A is the query camera, B the gallery camera."""
shirts = rng.integers(20, 236, (n_ids, 3)); trousers = rng.integers(20, 236, (n_ids, 3))
gain_a, gain_b = np.array([1.0, 1.0, 1.0]), np.array([1.15, 1.0, 0.8]) # B is warmer
query = np.array([make_person(rng, shirts[i], trousers[i], gain_a) for i in range(n_ids)])
gallery = np.array([make_person(rng, shirts[i], trousers[i], gain_b) for i in range(n_ids) for _ in range(2)])
return query, np.arange(n_ids), gallery, np.repeat(np.arange(n_ids), 2)
def evaluate(D, q_ids, g_ids, ranks=(1, 5, 10)):
"""D: (queries, gallery) distances. Returns rank-k accuracies (CMC) and mAP."""
order = np.argsort(D, axis=1, kind="stable")
matches = g_ids[order] == q_ids[:, None] # True where the ranked gallery image is correct
first = matches.argmax(axis=1) # rank (0-based) of the first correct match
cmc = {k: float(np.mean(first < k)) for k in ranks}
aps = []
for m in matches:
r = np.flatnonzero(m) # 0-based ranks of all correct matches
aps.append(np.mean(np.arange(1, len(r) + 1) / (r + 1)))
return cmc, float(np.mean(aps))
def report(name, D, q_ids, g_ids):
cmc, mAP = evaluate(D, q_ids, g_ids)
print(f"{name:22s} rank-1 {cmc[1]:.3f} rank-5 {cmc[5]:.3f} rank-10 {cmc[10]:.3f} mAP {mAP:.3f}")
rng = np.random.default_rng(0)
query, q_ids, gallery, g_ids = make_reid_set(rng)
print("query", query.shape, "gallery", gallery.shape, "| chance rank-1:", f"{2 / len(gallery):.3f}")
print("mean RGB, camera A:", query.reshape(-1, 3).mean(axis=0).round(1).tolist(),
"| camera B:", gallery.reshape(-1, 3).mean(axis=0).round(1).tolist())
# Check the metric on the figure's ranking: correct at ranks 1 and 3 of 5
print("AP of [hit, miss, hit, miss, miss]:", evaluate(np.arange(5.0)[None], np.array([7]), np.array([7, 1, 7, 2, 3]))[1].__round__(3))
# Baseline: Euclidean distance between raw pixel vectors
def pixels(x):
return x.reshape(len(x), -1).astype(float)
D = np.linalg.norm(pixels(query)[:, None] - pixels(gallery)[None], axis=2)
report("raw pixels", D, q_ids, g_ids)
fig, axes = plt.subplots(2, 6, figsize=(6, 2.8))
for j in range(6):
axes[0, j].imshow(query[j]); axes[0, j].set_title(f"A: id {j}", fontsize=7)
axes[1, j].imshow(gallery[2 * j]); axes[1, j].set_title(f"B: id {j}", fontsize=7)
for a in axes.ravel():
a.axis("off")
fig.tight_layout()query (20, 64, 32, 3) gallery (40, 64, 32, 3) | chance rank-1: 0.050
mean RGB, camera A: [110.1, 109.0, 104.2] | camera B: [126.7, 109.0, 83.3]
AP of [hit, miss, hit, miss, miss]: 0.833
raw pixels rank-1 0.850 rank-5 0.950 rank-10 0.950 mAP 0.857
Chance rank-1 with 2 correct images among 40 is 0.05. Camera B's warm cast is visible in the means (red up from 110 to 127, blue down from 104 to 83). The metric reproduces the figure's AP of 0.833. And the naive baseline is surprisingly strong: raw pixel distance puts the right person first for 17 of the 20 queries (rank-1 0.850, mAP 0.857). That says more about the data than about the method: these crops are aligned to within two pixels, on a plain background, in identical poses. Shift a real pedestrian by a quarter of the crop, or let them turn round, and raw pixels collapse; that is why descriptors that ignore position exist.
Colour histograms, by body part
A classical re-ID descriptor throws away the exact pixel positions and keeps the colour distribution, which does not care about a two-pixel shift. Two refinements matter. Hue and saturation (HSV, see colour spaces) separate the colour of the clothes from the brightness of the light. And one histogram per horizontal stripe (head, torso, legs) keeps the coarse layout, so a red shirt with blue trousers is not the same as a blue shirt with red trousers. Histograms are compared with the Hellinger distance (Euclidean distance between square-rooted, normalised histograms).
The camera colour shift is the other problem. Grey-world normalisation assumes the average colour of a scene is grey and divides each channel by its mean:
A per-channel gain such as camera B's multiplies and alike, so it cancels exactly; a real camera difference is only partly a gain, so grey-world helps less on real data.
import numpy as np
import cv2
cv2.setLogLevel(0)
def make_person(rng, shirt, trousers, cam_gain, h=64, w=32):
img = rng.normal(90, 15, (h, w, 3))
dx = int(rng.integers(-2, 3))
img[4:16, 11 + dx:21 + dx] = [200, 160, 130]
img[16:38, 7 + dx:25 + dx] = shirt
img[38:62, 9 + dx:23 + dx] = trousers
img = img * cam_gain + rng.normal(0, 8, (h, w, 3))
return img.clip(0, 255).astype(np.uint8)
def make_reid_set(rng, n_ids=20):
shirts = rng.integers(20, 236, (n_ids, 3)); trousers = rng.integers(20, 236, (n_ids, 3))
gain_a, gain_b = np.array([1.0, 1.0, 1.0]), np.array([1.15, 1.0, 0.8])
query = np.array([make_person(rng, shirts[i], trousers[i], gain_a) for i in range(n_ids)])
gallery = np.array([make_person(rng, shirts[i], trousers[i], gain_b) for i in range(n_ids) for _ in range(2)])
return query, np.arange(n_ids), gallery, np.repeat(np.arange(n_ids), 2)
def evaluate(D, q_ids, g_ids, ranks=(1, 5, 10)):
order = np.argsort(D, axis=1, kind="stable")
matches = g_ids[order] == q_ids[:, None]
first = matches.argmax(axis=1)
cmc = {k: float(np.mean(first < k)) for k in ranks}
aps = [np.mean(np.arange(1, m.sum() + 1) / (np.flatnonzero(m) + 1)) for m in matches]
return cmc, float(np.mean(aps))
def report(name, D, q_ids, g_ids):
cmc, mAP = evaluate(D, q_ids, g_ids)
print(f"{name:28s} rank-1 {cmc[1]:.3f} rank-5 {cmc[5]:.3f} mAP {mAP:.3f}")
def grey_world(img):
f = img.astype(float)
means = f.reshape(-1, 3).mean(axis=0)
return (f * means.mean() / means).clip(0, 255).astype(np.uint8)
STRIPES = [(0, 16), (16, 38), (38, 64)] # head, torso, legs (rows)
def hsv_hist(img, parts=True, bins=(12, 4)):
hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
regions = [hsv[a:b] for a, b in STRIPES] if parts else [hsv]
feats = []
for r in regions:
h = cv2.calcHist([np.ascontiguousarray(r)], [0, 1], None, list(bins), [0, 180, 0, 256]).ravel()
feats.append(np.sqrt(h / h.sum())) # square root: Euclidean = Hellinger distance
return np.concatenate(feats)
def distances(fq, fg):
return np.linalg.norm(fq[:, None] - fg[None], axis=2)
rng = np.random.default_rng(0)
query, q_ids, gallery, g_ids = make_reid_set(rng)
for name, parts, gw in [("HSV, whole crop", False, False), ("HSV, 3 stripes", True, False),
("HSV, 3 stripes + grey-world", True, True)]:
prep = grey_world if gw else (lambda im: im)
fq = np.array([hsv_hist(prep(im), parts) for im in query])
fg = np.array([hsv_hist(prep(im), parts) for im in gallery])
report(name, distances(fq, fg), q_ids, g_ids)
print("feature length with stripes:", len(hsv_hist(query[0])))
q, g = query.reshape(-1, 3).mean(axis=0), np.array([grey_world(im) for im in gallery]).reshape(-1, 3).mean(axis=0)
print("mean RGB after grey-world, camera B:", g.round(1).tolist(), "| camera A raw:", q.round(1).tolist())HSV, whole crop rank-1 0.500 rank-5 0.650 mAP 0.590
HSV, 3 stripes rank-1 0.550 rank-5 0.850 mAP 0.686
HSV, 3 stripes + grey-world rank-1 1.000 rank-5 1.000 mAP 1.000
feature length with stripes: 144
mean RGB after grey-world, camera B: [105.8, 105.8, 105.8] | camera A raw: [110.1, 109.0, 104.2]
The histogram descriptors without colour correction are worse than raw pixels here (rank-1 0.500 for the whole crop, 0.550 with stripes): camera B's gain moves the hue and saturation of every shirt, and a histogram bin boundary turns a small colour change into a large histogram change. Stripes help (mAP 0.590 to 0.686, rank-5 0.650 to 0.850), because they keep where each colour is. Grey-world then removes the camera shift completely (all three channel means of camera B become 105.8) and the striped histogram finds every person at rank 1 (mAP 1.000). That perfect score is again a property of the synthetic data: the camera difference is a per-channel gain, which grey-world cancels exactly, and every identity has distinct random colours. With 20 queries, each one is 5 % of rank-1, so differences of one or two queries are noise.
Deep features (recorded)
Modern re-ID models are CNNs (often a ResNet-50 backbone) trained on re-ID data sets to output an embedding, compared by cosine or Euclidean distance like face embeddings. No re-ID model is available offline here, so the recorded example uses ResNet-18 trained on ImageNet, not on people: its 512-d pooled features are generic. The crops are resized to 256 x 128, the usual re-ID input size.
import numpy as np
import cv2
import torch
from torchvision.models import resnet18, ResNet18_Weights
def make_person(rng, shirt, trousers, cam_gain, h=64, w=32):
img = rng.normal(90, 15, (h, w, 3))
dx = int(rng.integers(-2, 3))
img[4:16, 11 + dx:21 + dx] = [200, 160, 130]
img[16:38, 7 + dx:25 + dx] = shirt
img[38:62, 9 + dx:23 + dx] = trousers
img = img * cam_gain + rng.normal(0, 8, (h, w, 3))
return img.clip(0, 255).astype(np.uint8)
def make_reid_set(rng, n_ids=20):
shirts = rng.integers(20, 236, (n_ids, 3)); trousers = rng.integers(20, 236, (n_ids, 3))
gain_a, gain_b = np.array([1.0, 1.0, 1.0]), np.array([1.15, 1.0, 0.8])
query = np.array([make_person(rng, shirts[i], trousers[i], gain_a) for i in range(n_ids)])
gallery = np.array([make_person(rng, shirts[i], trousers[i], gain_b) for i in range(n_ids) for _ in range(2)])
return query, np.arange(n_ids), gallery, np.repeat(np.arange(n_ids), 2)
def evaluate(D, q_ids, g_ids, ranks=(1, 5, 10)):
order = np.argsort(D, axis=1, kind="stable")
matches = g_ids[order] == q_ids[:, None]
first = matches.argmax(axis=1)
cmc = {k: float(np.mean(first < k)) for k in ranks}
aps = [np.mean(np.arange(1, m.sum() + 1) / (np.flatnonzero(m) + 1)) for m in matches]
return cmc, float(np.mean(aps))
def grey_world(img):
f = img.astype(float)
means = f.reshape(-1, 3).mean(axis=0)
return (f * means.mean() / means).clip(0, 255).astype(np.uint8)
torch.manual_seed(0)
net = resnet18(weights=ResNet18_Weights.IMAGENET1K_V1).eval()
net.fc = torch.nn.Identity()
mean, std = np.array([0.485, 0.456, 0.406]), np.array([0.229, 0.224, 0.225])
def embed(crops):
x = np.stack([cv2.resize(c, (128, 256), interpolation=cv2.INTER_LINEAR) / 255.0 for c in crops])
x = torch.tensor(((x - mean) / std).transpose(0, 3, 1, 2), dtype=torch.float32)
with torch.no_grad():
e = net(x).numpy()
return e / np.linalg.norm(e, axis=1, keepdims=True)
rng = np.random.default_rng(0)
query, q_ids, gallery, g_ids = make_reid_set(rng)
for name, prep in [("ResNet-18 (ImageNet)", lambda im: im), ("ResNet-18 + grey-world", grey_world)]:
fq = embed([prep(im) for im in query]); fg = embed([prep(im) for im in gallery])
cmc, mAP = evaluate(1 - fq @ fg.T, q_ids, g_ids) # cosine distance
print(f"{name:24s} rank-1 {cmc[1]:.3f} rank-5 {cmc[5]:.3f} mAP {mAP:.3f}")ResNet-18 (ImageNet) rank-1 0.750 rank-5 0.800 mAP 0.647
ResNet-18 + grey-world rank-1 0.850 rank-5 0.900 mAP 0.795
Generic ImageNet features find the right person first for 15 of 20 queries (rank-1 0.750, mAP 0.647), worse than the raw pixels and far worse than the corrected histograms. Grey-world helps them too (rank-1 0.850, mAP 0.795): an ImageNet network is sensitive to colour casts it was never asked to ignore. A network trained for re-ID on thousands of identities seen by many cameras learns that invariance; benchmark rank-1 accuracies of such models on Market-1501 are reported above 90 %. Without such a model, a tuned classical descriptor can beat a generic deep one, which is worth checking before reaching for a bigger network.
Training a re-ID embedding: batch-hard triplets
A re-ID network is trained so that crops of the same person are closer than crops of different people, with a classification loss over the training identities, a triplet loss, or both (see contrastive and triplet losses for the losses themselves). The re-ID-specific trick is how the triplets are chosen. Random triplets are mostly easy and teach nothing, so each batch is sampled P x K ( identities, images each, e.g. 16 x 4), and for every anchor the hardest positive (farthest image of the same person) and the hardest negative (closest image of anyone else) in the batch are used (Hermans, Beyer and Leibe, 2017):
with margin (0.3 is common) and . The computation is a few lines once the distance matrix of the batch exists; here on the colour-histogram features of a P x K = 4 x 3 batch:
import numpy as np
import cv2
cv2.setLogLevel(0)
def make_person(rng, shirt, trousers, cam_gain, h=64, w=32):
img = rng.normal(90, 15, (h, w, 3))
dx = int(rng.integers(-2, 3))
img[4:16, 11 + dx:21 + dx] = [200, 160, 130]
img[16:38, 7 + dx:25 + dx] = shirt
img[38:62, 9 + dx:23 + dx] = trousers
img = img * cam_gain + rng.normal(0, 8, (h, w, 3))
return img.clip(0, 255).astype(np.uint8)
def hsv_hist(img, bins=(12, 4)):
hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
feats = []
for a, b in [(0, 16), (16, 38), (38, 64)]:
h = cv2.calcHist([np.ascontiguousarray(hsv[a:b])], [0, 1], None, list(bins), [0, 180, 0, 256]).ravel()
feats.append(np.sqrt(h / h.sum()))
return np.concatenate(feats)
def batch_hard_triplet(F, y, margin=0.3):
D = np.linalg.norm(F[:, None] - F[None], axis=2)
same = y[:, None] == y[None, :]
hardest_pos = np.where(same, D, -np.inf).max(axis=1)
hardest_neg = np.where(~same, D, np.inf).min(axis=1)
return np.maximum(margin + hardest_pos - hardest_neg, 0), hardest_pos, hardest_neg
rng = np.random.default_rng(1)
P, K = 4, 3
shirts, trousers = rng.integers(20, 236, (P, 3)), rng.integers(20, 236, (P, 3))
gains = [np.array([1.0, 1.0, 1.0]), np.array([1.15, 1.0, 0.8]), np.array([0.85, 0.95, 1.1])] # 3 cameras
crops = [make_person(rng, shirts[i], trousers[i], gains[k]) for i in range(P) for k in range(K)]
y = np.repeat(np.arange(P), K)
F = np.array([hsv_hist(c) for c in crops])
loss, dp, dn = batch_hard_triplet(F, y)
for a in range(0, P * K, K):
print(f"anchor {a:2d} (id {y[a]}): hardest positive {dp[a]:.3f}, hardest negative {dn[a]:.3f}, loss {loss[a]:.3f}")
print(f"batch loss {loss.mean():.3f}; anchors with loss > 0: {int((loss > 0).sum())} of {P * K}")anchor 0 (id 0): hardest positive 1.309, hardest negative 1.237, loss 0.372
anchor 3 (id 1): hardest positive 1.177, hardest negative 1.229, loss 0.248
anchor 6 (id 2): hardest positive 1.198, hardest negative 1.325, loss 0.173
anchor 9 (id 3): hardest positive 1.232, hardest negative 1.229, loss 0.303
batch loss 0.625; anchors with loss > 0: 12 of 12
With every one of the 12 anchors violates the margin (batch loss 0.625): the colour histograms of the same person seen by three differently tinted cameras are often farther apart than those of two different people (anchor 0: hardest positive 1.309, hardest negative 1.237). That is exactly the signal a trained network uses: the gradient of this loss pulls the anchor and its hardest positive together and pushes the closest impostor away, so a learned embedding becomes invariant to the camera tint that the fixed histogram is not.
Beyond the baseline
- Part-based models (PCB, 2018) split the feature map into horizontal stripes, like the histograms above, and learn one embedding per part, which helps with partial occlusion.
- Re-ranking. The initial ranking is refined with the gallery's own structure: k-reciprocal re-ranking (Zhong et al., 2017) trusts a gallery image more if the query is also among its nearest neighbours, and query expansion averages the query with its top matches and searches again. Both raise mAP noticeably on benchmarks at the cost of computing gallery-to-gallery distances.
- Spatio-temporal constraints. Real deployments know the camera layout: a person cannot walk between two cameras 500 m apart in 10 seconds. Filtering candidates by plausible transit times removes many false matches.
- Domain shift. A model trained on one site's cameras loses a lot of accuracy on another site's; unsupervised domain adaptation and clustering-based pseudo-labels are active research. Always evaluate on the target cameras (distribution shift).
- Clothes-changing re-ID is a separate, much harder benchmark task; appearance models trained on clothing fail when the clothes change.
Pitfalls
- Identity leakage. Training and test sets must contain different people, not just different images; benchmarks split by identity. A model tested on identities it was trained on reports inflated scores (split strategies).
- Same-camera matches. Count only gallery images from other cameras (or report both); same-camera matches of the same person are near-duplicates.
- Rank-1 alone. It hides whether the other sightings are found; report mAP too.
- Small galleries. A 40-image gallery flatters every method; real galleries hold thousands of crops from people who never appear as queries (project 6 measures this distractor effect).
- Colour only. Two people in the same uniform (staff, school children, sports teams) are indistinguishable to a colour descriptor and hard for any appearance model.
- Function creep. A system built to find lost children can also follow anyone; restrict queries, log them, and delete gallery features after a short retention period.
Practice
- A query has 3 correct gallery images, ranked 2, 3 and 10. Compute its AP. Is it a rank-1 hit? A rank-5 hit?
Answer
. Not a rank-1 hit (the first match is at rank 2), but a rank-5 hit.
- Camera B multiplies red by 1.15 and blue by 0.8. Show that grey-world removes this exactly, and say why it may not on real cameras.
Answer
With , the channel mean is , so : the gain cancels, and only the common factor (the mean over the three channels) remains, which changes the overall brightness but not the colour (clipping at 255 aside). Real camera differences also include non-linear tone curves, different sensors, mixed light sources and saturated pixels, which are not a per-channel gain; and the grey-world assumption fails for crops dominated by one colour (a person in a bright red coat).
- Why does batch-hard mining need images per identity in every batch?
Answer
Each anchor needs at least one positive of the same identity in the batch; with there is no positive and the loss is undefined. With larger the hardest positive is a more informative (harder) pair.
Test yourself
What distinguishes re-identification from multi-object tracking?
- Re-ID uses only faces
- Re-ID matches people across non-overlapping cameras and time gaps by appearance, where position and motion give no link
- Tracking needs no detector
- Re-ID works only on video
A query's two correct gallery images are at ranks 1 and 4. What is its AP?
- 0.25
- 0.625
- 0.75
- 1.0
Why are colour histograms computed per horizontal stripe (head, torso, legs) rather than over the whole crop?
- It is faster
- The stripes keep the coarse layout, so a red shirt with blue trousers differs from a blue shirt with red trousers
- Histograms need square images
- To remove the camera colour shift
In batch-hard triplet loss, which negative is used for each anchor?
- A random image of another person
- The closest image of any other identity in the batch
- The farthest image of another identity
- The anchor's own image