Project 2: Human Detection
Goal. Build and evaluate a detector that finds people in still images, compare a classical detector with a modern one on the same test set, and write up the result so that someone else could decide whether to deploy it.
Success criteria. Fixed before looking at any result:
- A labelled test set with known person boxes, built reproducibly from a seed.
- At least two detectors evaluated on exactly that set with AP@0.5 (detection metrics), plus precision, recall and false positives per image at a stated operating threshold.
- An error analysis that says which people are missed and what the false positives are.
- A short write-up with the numbers, the limitations of the test set and the privacy conditions for a real deployment.
The project reuses detection basics (IoU, AP), NMS and Ultralytics YOLO.
Step 1: a test set with known boxes
Real labelled photos of people need consent and licences (privacy, consent and licensing). This project uses the one public-domain person photo that ships with scikit-image, NASA's portrait of the astronaut Eileen Collins (data.astronaut()), and builds a test set from it: the left part of the photo (400 of 512 columns, with the woman in it) is scaled to a height between 90 and 330 pixels, possibly mirrored, made darker or brighter (gain 0.6 to 1.3) and pasted at a random free place onto one of six person-free sample images (coffee cup, rocket, cat, Hubble deep field, grass, brick), resized to 480 x 360. Each image gets 0, 1 or 2 people. The person box in the original photo was drawn by hand once, [8, 12, 366, 512] (hair to the bottom edge, shoulder to shoulder, without the helmet she holds), and is transformed with every paste, so every test box is known exactly.
import numpy as np
import cv2
import matplotlib.pyplot as plt
cv2.setLogLevel(0)
import numpy as np, cv2
from skimage import data
PERSON = [8, 12, 366, 512] # the woman in data.astronaut(), box drawn by hand (x2, y2 exclusive)
def make_people_set(rng, n_images=30, H=360, W=480):
"""Test images: crops of data.astronaut() (one person, box PERSON) pasted at random scale, position,
mirror and brightness onto six person-free sample images. Returns a list of (RGB image, boxes (n, 4))."""
src = data.astronaut()[:, :400]
grey = lambda g: np.repeat(g[:, :, None], 3, axis=2)
bgs = [data.coffee(), data.rocket(), data.chelsea(), data.hubble_deep_field(), grey(data.grass()), grey(data.brick())]
out = []
for k in range(n_images):
img = cv2.resize(bgs[k % len(bgs)], (W, H), interpolation=cv2.INTER_AREA)
boxes, placed = [], []
for _ in range(int(rng.integers(0, 3))): # 0, 1 or 2 people
h = int(rng.integers(90, 331)); s = h / 512; w = round(400 * s)
for _ in range(50):
x, y = int(rng.integers(0, W - w + 1)), int(rng.integers(0, H - h + 1))
if all(x + w <= px or px + pw <= x for px, pw in placed):
break
else:
continue # no free place: skip this person
crop = cv2.resize(src, (w, h), interpolation=cv2.INTER_AREA)
bx1, bx2 = PERSON[0], PERSON[2]
if rng.random() < 0.5: # mirror image
crop = crop[:, ::-1]; bx1, bx2 = 400 - PERSON[2], 400 - PERSON[0]
gain = rng.uniform(0.6, 1.3)
img[y:y + h, x:x + w] = np.clip(crop * gain, 0, 255).astype(np.uint8)
boxes.append([x + round(bx1 * s), y + round(PERSON[1] * s), x + round(bx2 * s), y + round(PERSON[3] * s)])
placed.append((x, w))
out.append((img, np.array(boxes).reshape(-1, 4)))
return out
test = make_people_set(np.random.default_rng(0))
heights = np.concatenate([b[:, 3] - b[:, 1] for _, b in test])
print("images:", len(test), "| people:", len(heights), "| images without people:", sum(len(b) == 0 for _, b in test))
print("person box heights: min", int(heights.min()), "median", int(np.median(heights)), "max", int(heights.max()))
for k in range(3):
print(f"image {k}: {test[k][1].tolist()}")
fig, axes = plt.subplots(1, 4, figsize=(10, 2.2))
for ax, k in zip(axes, [0, 1, 2, 3]):
img, boxes = test[k]
ax.imshow(img)
for x1, y1, x2, y2 in boxes:
ax.add_patch(plt.Rectangle((x1, y1), x2 - x1, y2 - y1, fill=False, color="lime", lw=1.5))
ax.set_title(f"image {k}: {len(boxes)} people", fontsize=8); ax.axis("off")
fig.tight_layout()
plt.show()images: 30 | people: 35 | images without people: 6
person box heights: min 91 median 187 max 321
image 0: [[164, 37, 334, 274], [347, 118, 439, 247]]
image 1: [[301, 42, 458, 261]]
image 2: [[25, 110, 181, 328], [213, 42, 398, 301]]
30 images, 35 people between 91 and 321 pixels tall (median 187), and 6 images with nobody in them, which is where false positives per image are measured. The pictures show what this test set is: the same woman as a pasted rectangle, flag and wall included, at different sizes and brightness. It tests scale, position, mirroring, brightness and background clutter. It does not test other people, poses, clothing, occlusion, crowds or lighting direction, and any score on it is an upper bound for real photos. Saying so in the write-up is part of the result.
Step 2: baseline, the classical pedestrian detector
OpenCV ships the Dalal–Triggs people detector: HOG features (classical features) in a 64 x 128 window, a linear SVM trained on pedestrians, applied at many scales with detectMultiScale. Its SVM margin serves as the score. To compute AP, the threshold hitThreshold is set low () so that weak detections are returned too; the default is 0. The AP helper is the VOC all-point version from detection metrics, for one class.
import numpy as np
import cv2
cv2.setLogLevel(0)
import numpy as np, cv2
from skimage import data
PERSON = [8, 12, 366, 512] # the woman in data.astronaut(), box drawn by hand (x2, y2 exclusive)
def make_people_set(rng, n_images=30, H=360, W=480):
"""Test images: crops of data.astronaut() (one person, box PERSON) pasted at random scale, position,
mirror and brightness onto six person-free sample images. Returns a list of (RGB image, boxes (n, 4))."""
src = data.astronaut()[:, :400]
grey = lambda g: np.repeat(g[:, :, None], 3, axis=2)
bgs = [data.coffee(), data.rocket(), data.chelsea(), data.hubble_deep_field(), grey(data.grass()), grey(data.brick())]
out = []
for k in range(n_images):
img = cv2.resize(bgs[k % len(bgs)], (W, H), interpolation=cv2.INTER_AREA)
boxes, placed = [], []
for _ in range(int(rng.integers(0, 3))): # 0, 1 or 2 people
h = int(rng.integers(90, 331)); s = h / 512; w = round(400 * s)
for _ in range(50):
x, y = int(rng.integers(0, W - w + 1)), int(rng.integers(0, H - h + 1))
if all(x + w <= px or px + pw <= x for px, pw in placed):
break
else:
continue # no free place: skip this person
crop = cv2.resize(src, (w, h), interpolation=cv2.INTER_AREA)
bx1, bx2 = PERSON[0], PERSON[2]
if rng.random() < 0.5: # mirror image
crop = crop[:, ::-1]; bx1, bx2 = 400 - PERSON[2], 400 - PERSON[0]
gain = rng.uniform(0.6, 1.3)
img[y:y + h, x:x + w] = np.clip(crop * gain, 0, 255).astype(np.uint8)
boxes.append([x + round(bx1 * s), y + round(PERSON[1] * s), x + round(bx2 * s), y + round(PERSON[3] * s)])
placed.append((x, w))
out.append((img, np.array(boxes).reshape(-1, 4)))
return out
def iou(a, b):
iw = max(0, min(a[2], b[2]) - max(a[0], b[0])); ih = max(0, min(a[3], b[3]) - max(a[1], b[1]))
return iw * ih / ((a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - iw * ih)
def evaluate(dets, test, thr=0.5, op=None):
"""dets: list per image of (score, box). AP@thr (VOC all-point); TP/FP/FN at score >= op if given."""
n_gt = sum(len(b) for _, b in test); rows = []
for k, (img, gt) in enumerate(test):
used = set()
for s, b in sorted(dets[k], key=lambda d: -d[0]):
ious = [iou(b, g) for g in gt.tolist()]
j = int(np.argmax(ious)) if ious else -1
hit = j >= 0 and ious[j] >= thr and j not in used
used |= {j} if hit else set(); rows.append((s, hit))
rows.sort(key=lambda r: -r[0]); tp = np.array([r[1] for r in rows], float)
if len(tp) == 0:
return 0.0, None
prec, rec = np.cumsum(tp) / np.arange(1, len(tp) + 1), np.cumsum(tp) / n_gt
ap = float(np.sum(np.diff(np.r_[0, rec]) * np.maximum.accumulate(prec[::-1])[::-1]))
if op is None:
return ap, None
hi = [r for r in rows if r[0] >= op]
tp_op = sum(r[1] for r in hi)
return ap, (tp_op, len(hi) - tp_op, n_gt - tp_op)
test = make_people_set(np.random.default_rng(0))
hog = cv2.HOGDescriptor()
hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())
dets = []
for img, gt in test:
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
rects, weights = hog.detectMultiScale(gray, hitThreshold=-0.5, winStride=(8, 8), padding=(8, 8), scale=1.05)
dets.append([(float(w), [int(x), int(y), int(x + w_), int(y + h)]) for (x, y, w_, h), w in zip(rects, np.ravel(weights))])
ap, (tp, fp, fn) = evaluate(dets, test, op=0.0)
print(f"HOG people detector: AP@0.5 {ap:.3f} | at score >= 0 (the default): TP {tp}, FP {fp}, missed {fn}")
print("detections per image (score >= 0):", [sum(s >= 0 for s, _ in d) for d in dets])
best = [max((iou(b, g) for s, b in d for g in gt.tolist()), default=0) for d, (_, gt) in zip(dets, test) if len(gt)]
print("best IoU of any HOG box with a person, per image with people:", np.round(best, 2).tolist())HOG people detector: AP@0.5 0.000 | at score >= 0 (the default): TP 0, FP 23, missed 35
detections per image (score >= 0): [1, 1, 2, 2, 0, 2, 0, 1, 1, 2, 0, 2, 0, 0, 0, 2, 0, 0, 0, 2, 1, 0, 0, 0, 0, 0, 2, 2, 0, 0]
best IoU of any HOG box with a person, per image with people: [0.3, 0.34, 0.31, 0.27, 0.0, 0.31, 0.0, 0.31, 0.31, 0.29, 0.28, 0.17, 0.0, 0.08, 0.03, 0.28, 0.2, 0.38, 0.27, 0.0, 0.0, 0.29, 0.29, 0.27]
The HOG detector finds nobody: AP 0.000, no true positive at any threshold, and 23 false positives at its default threshold, spread over 14 of the 30 images and every background except grass. Its best boxes overlap a person with IoU 0.27 to 0.38: it fires on parts of the body, never on the whole. This is not a bug. The detector was trained on 64 x 128 windows of full-body, upright pedestrians; a waist-up portrait has neither legs nor the pedestrian silhouette it looks for. A model is only as good as the match between its training data and your data, and the first baseline is the cheapest way to find that out.
Step 3: a better classical baseline, faces as a proxy
The people in this test set are photographed from the waist up and face the camera, which is exactly what a frontal-face detector is built for (face detection). A face box can be turned into a person box with fixed proportions. In the source photo the face detector returns [177, 66, 95, 95] (x, y, w, h) and the person box is [8, 12, 366, 512]: the person is about face widths wide, starts face widths above the face and ends face widths below its top. The rule centres the body horizontally on the face, because people may be mirrored. The number of neighbouring detections the cascade merged (detectMultiScale2) serves as the score.
Be honest about this step: the proportions were measured on the same woman who appears in every test image, so the rule fits this test set far better than it would fit other people, poses or camera angles.
import numpy as np
import cv2
cv2.setLogLevel(0)
import numpy as np, cv2
from skimage import data
PERSON = [8, 12, 366, 512] # the woman in data.astronaut(), box drawn by hand (x2, y2 exclusive)
def make_people_set(rng, n_images=30, H=360, W=480):
"""Test images: crops of data.astronaut() (one person, box PERSON) pasted at random scale, position,
mirror and brightness onto six person-free sample images. Returns a list of (RGB image, boxes (n, 4))."""
src = data.astronaut()[:, :400]
grey = lambda g: np.repeat(g[:, :, None], 3, axis=2)
bgs = [data.coffee(), data.rocket(), data.chelsea(), data.hubble_deep_field(), grey(data.grass()), grey(data.brick())]
out = []
for k in range(n_images):
img = cv2.resize(bgs[k % len(bgs)], (W, H), interpolation=cv2.INTER_AREA)
boxes, placed = [], []
for _ in range(int(rng.integers(0, 3))): # 0, 1 or 2 people
h = int(rng.integers(90, 331)); s = h / 512; w = round(400 * s)
for _ in range(50):
x, y = int(rng.integers(0, W - w + 1)), int(rng.integers(0, H - h + 1))
if all(x + w <= px or px + pw <= x for px, pw in placed):
break
else:
continue # no free place: skip this person
crop = cv2.resize(src, (w, h), interpolation=cv2.INTER_AREA)
bx1, bx2 = PERSON[0], PERSON[2]
if rng.random() < 0.5: # mirror image
crop = crop[:, ::-1]; bx1, bx2 = 400 - PERSON[2], 400 - PERSON[0]
gain = rng.uniform(0.6, 1.3)
img[y:y + h, x:x + w] = np.clip(crop * gain, 0, 255).astype(np.uint8)
boxes.append([x + round(bx1 * s), y + round(PERSON[1] * s), x + round(bx2 * s), y + round(PERSON[3] * s)])
placed.append((x, w))
out.append((img, np.array(boxes).reshape(-1, 4)))
return out
def iou(a, b):
iw = max(0, min(a[2], b[2]) - max(a[0], b[0])); ih = max(0, min(a[3], b[3]) - max(a[1], b[1]))
return iw * ih / ((a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - iw * ih)
def match(dets, test, thr=0.5):
"""Greedy matching by score over the whole set. Returns rows (score, hit) and the matched flags per person."""
rows, found = [], []
for k, (img, gt) in enumerate(test):
used = set()
for s, b in sorted(dets[k], key=lambda d: -d[0]):
ious = [iou(b, g) for g in gt.tolist()]
j = int(np.argmax(ious)) if ious else -1
hit = j >= 0 and ious[j] >= thr and j not in used
used |= {j} if hit else set(); rows.append((s, hit))
found.append([j in used for j in range(len(gt))])
return rows, found
def ap_from(rows, n_gt):
rows = sorted(rows, key=lambda r: -r[0]); tp = np.array([r[1] for r in rows], float)
prec, rec = np.cumsum(tp) / np.arange(1, len(tp) + 1), np.cumsum(tp) / n_gt
return float(np.sum(np.diff(np.r_[0, rec]) * np.maximum.accumulate(prec[::-1])[::-1]))
test = make_people_set(np.random.default_rng(0))
n_gt = sum(len(b) for _, b in test)
faces = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
dets = []
for img, gt in test:
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
rects, neighbours = faces.detectMultiScale2(gray, scaleFactor=1.1, minNeighbors=3)
d = []
for (x, y, w, h), n in zip(rects, np.ravel(neighbours)):
cx = x + w / 2
box = [cx - 1.885 * w, y - 0.568 * w, cx + 1.885 * w, y + 4.695 * w]
box = [max(0.0, box[0]), max(0.0, box[1]), min(480.0, box[2]), min(360.0, box[3])]
d.append((int(n), box))
dets.append(d)
rows, found = match(dets, test)
print(f"face proxy: AP@0.5 {ap_from(rows, n_gt):.3f}")
for op in [3, 10, 20]:
hi = [r for r in rows if r[0] >= op]; tp = sum(r[1] for r in hi)
print(f" score >= {op:2d} neighbours: TP {tp}, FP {len(hi) - tp}, missed {n_gt - tp}, precision {tp / max(len(hi), 1):.2f}, recall {tp / n_gt:.2f}")
heights = np.concatenate([b[:, 3] - b[:, 1] for _, b in test]); hit = np.concatenate([f for f in found if f]).astype(bool)
for lo, hi_ in [(90, 150), (150, 250), (250, 331)]:
m = (heights >= lo) & (heights < hi_)
print(f" people {lo}-{hi_ - 1} px tall: found {int(hit[m].sum())} of {int(m.sum())} (any score)")
fp_near = sum(1 for d, (_, gt) in zip(dets, test) for sc, bx in d
if sc >= 3 and len(gt) and max(iou(bx, g) for g in gt.tolist()) >= 0.1 and max(iou(bx, g) for g in gt.tolist()) < 0.5)
print(f" of the false positives at >= 3: {fp_near} overlap a person (box misplaced), the rest are on the background or duplicates")
def mosaic(test):
"""Groups of four test images, each halved, tiled 2 x 2 into one 480 x 360 image: the same people at half size."""
out = []
for g in range(len(test) // 4):
tiles = test[4 * g:4 * g + 4]
img = np.concatenate([np.concatenate([cv2.resize(t[0], (240, 180), interpolation=cv2.INTER_AREA) for t in tiles[r:r + 2]], 1) for r in (0, 2)], 0)
boxes = [np.asarray(b, float) / 2 + [240 * (i % 2), 180 * (i // 2)] * 2 for i, (_, bb) in enumerate(tiles) for b in bb]
out.append((img, np.array(boxes).reshape(-1, 4)))
return out
small = mosaic(test)
sdets = []
for img, gt in small:
rects, neighbours = faces.detectMultiScale2(cv2.cvtColor(img, cv2.COLOR_RGB2GRAY), scaleFactor=1.1, minNeighbors=3)
sdets.append([(int(n), [max(0.0, x + w / 2 - 1.885 * w), max(0.0, y - 0.568 * w), min(480.0, x + w / 2 + 1.885 * w), min(360.0, y + 4.695 * w)])
for (x, y, w, h), n in zip(rects, np.ravel(neighbours))])
srows, _ = match(sdets, small)
print(f"half-size people ({len(small)} mosaics, {sum(len(b) for _, b in small)} people, 45 to 165 px tall): face proxy AP@0.5 {ap_from(srows, sum(len(b) for _, b in small)):.3f}")face proxy: AP@0.5 0.826
score >= 3 neighbours: TP 29, FP 8, missed 6, precision 0.78, recall 0.83
score >= 10 neighbours: TP 22, FP 0, missed 13, precision 1.00, recall 0.63
score >= 20 neighbours: TP 12, FP 0, missed 23, precision 1.00, recall 0.34
people 90-149 px tall: found 4 of 10 (any score)
people 150-249 px tall: found 17 of 17 (any score)
people 250-330 px tall: found 8 of 8 (any score)
of the false positives at >= 3: 3 overlap a person (box misplaced), the rest are on the background or duplicates
half-size people (7 mosaics, 34 people, 45 to 165 px tall): face proxy AP@0.5 0.412
The face proxy works far better: AP 0.826. Its score is a real trade-off: with at least 3 merged neighbours it finds 29 of 35 people with 8 false positives (3 of them boxes on a person that are placed badly, the rest on background texture or second boxes on one person); with at least 10 neighbours it has no false positive left but finds only 22. Size decides recall: it finds every person 150 pixels or taller but only 4 of the 10 between 90 and 149 pixels. Such a person's face is 17 to 28 pixels wide, at or below the 24-pixel minimum of the cascade's window. On the half-size mosaics (the same people at 45 to 165 pixels, four images tiled into one) its AP falls to 0.412. And it would fail on anyone seen from behind or from the side, which this test set never shows.
Step 4: the improved detector, YOLO
The pretrained YOLOv8n and YOLO11n know COCO's person class (id 0). Running them on the same 30 images is a recorded example (PyTorch in Docker); the generator is the same code, so the images are identical. conf=0.01 keeps low-score boxes for the AP; classes=[0] keeps only people.
import numpy as np
import cv2
from ultralytics import YOLO
import numpy as np, cv2
from skimage import data
PERSON = [8, 12, 366, 512] # the woman in data.astronaut(), box drawn by hand (x2, y2 exclusive)
def make_people_set(rng, n_images=30, H=360, W=480):
"""Test images: crops of data.astronaut() (one person, box PERSON) pasted at random scale, position,
mirror and brightness onto six person-free sample images. Returns a list of (RGB image, boxes (n, 4))."""
src = data.astronaut()[:, :400]
grey = lambda g: np.repeat(g[:, :, None], 3, axis=2)
bgs = [data.coffee(), data.rocket(), data.chelsea(), data.hubble_deep_field(), grey(data.grass()), grey(data.brick())]
out = []
for k in range(n_images):
img = cv2.resize(bgs[k % len(bgs)], (W, H), interpolation=cv2.INTER_AREA)
boxes, placed = [], []
for _ in range(int(rng.integers(0, 3))): # 0, 1 or 2 people
h = int(rng.integers(90, 331)); s = h / 512; w = round(400 * s)
for _ in range(50):
x, y = int(rng.integers(0, W - w + 1)), int(rng.integers(0, H - h + 1))
if all(x + w <= px or px + pw <= x for px, pw in placed):
break
else:
continue # no free place: skip this person
crop = cv2.resize(src, (w, h), interpolation=cv2.INTER_AREA)
bx1, bx2 = PERSON[0], PERSON[2]
if rng.random() < 0.5: # mirror image
crop = crop[:, ::-1]; bx1, bx2 = 400 - PERSON[2], 400 - PERSON[0]
gain = rng.uniform(0.6, 1.3)
img[y:y + h, x:x + w] = np.clip(crop * gain, 0, 255).astype(np.uint8)
boxes.append([x + round(bx1 * s), y + round(PERSON[1] * s), x + round(bx2 * s), y + round(PERSON[3] * s)])
placed.append((x, w))
out.append((img, np.array(boxes).reshape(-1, 4)))
return out
def iou(a, b):
iw = max(0, min(a[2], b[2]) - max(a[0], b[0])); ih = max(0, min(a[3], b[3]) - max(a[1], b[1]))
return iw * ih / ((a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - iw * ih)
def match(dets, test, thr=0.5):
rows, found = [], []
for k, (img, gt) in enumerate(test):
used = set()
for s, b in sorted(dets[k], key=lambda d: -d[0]):
ious = [iou(b, g) for g in gt.tolist()]
j = int(np.argmax(ious)) if ious else -1
hit = j >= 0 and ious[j] >= thr and j not in used
used |= {j} if hit else set(); rows.append((s, hit))
found.append([j in used for j in range(len(gt))])
return rows, found
def ap_from(rows, n_gt):
rows = sorted(rows, key=lambda r: -r[0]); tp = np.array([r[1] for r in rows], float)
prec, rec = np.cumsum(tp) / np.arange(1, len(tp) + 1), np.cumsum(tp) / n_gt
return float(np.sum(np.diff(np.r_[0, rec]) * np.maximum.accumulate(prec[::-1])[::-1]))
def mosaic(test):
"""Groups of four test images, each halved, tiled 2 x 2 into one 480 x 360 image: the same people at half size."""
out = []
for g in range(len(test) // 4):
tiles = test[4 * g:4 * g + 4]
img = np.concatenate([np.concatenate([cv2.resize(t[0], (240, 180), interpolation=cv2.INTER_AREA) for t in tiles[r:r + 2]], 1) for r in (0, 2)], 0)
boxes = [np.asarray(b, float) / 2 + [240 * (i % 2), 180 * (i // 2)] * 2 for i, (_, bb) in enumerate(tiles) for b in bb]
out.append((img, np.array(boxes).reshape(-1, 4)))
return out
test = make_people_set(np.random.default_rng(0))
small = mosaic(test)
n_gt = sum(len(b) for _, b in test)
heights = np.concatenate([b[:, 3] - b[:, 1] for _, b in test])
backgrounds = ["coffee", "rocket", "chelsea", "hubble", "grass", "brick"]
for weights in ["yolov8n.pt", "yolo11n.pt"]:
model = YOLO(weights)
dets = []
for img, gt in test:
r = model.predict(img[:, :, ::-1].copy(), conf=0.01, classes=[0], verbose=False)[0]
dets.append(list(zip(r.boxes.conf.tolist(), r.boxes.xyxy.tolist())))
rows, found = match(dets, test)
print(f"{weights}: AP@0.5 {ap_from(rows, n_gt):.3f}")
for op in [0.25, 0.5]:
hi = [r for r in rows if r[0] >= op]; tp = sum(r[1] for r in hi)
print(f" conf >= {op}: TP {tp}, FP {len(hi) - tp}, missed {n_gt - tp}, precision {tp / max(len(hi), 1):.2f}, recall {tp / n_gt:.2f}, "
f"FP per image {(len(hi) - tp) / len(test):.2f}")
hit = np.concatenate([f for f in found if f]).astype(bool)
print(" found (any score) by height 90-149 / 150-249 / 250-330 px:",
" / ".join(f"{int(hit[(heights >= lo) & (heights < h2)].sum())} of {int(((heights >= lo) & (heights < h2)).sum())}" for lo, h2 in [(90, 150), (150, 250), (250, 331)]))
for k, (img, gt) in enumerate(test):
for g in gt.tolist():
cand = [(iou(bx, g), c) for c, bx in dets[k] if c >= 0.25]
best_iou, c = max(cand, default=(0.0, 0.0))
if best_iou < 0.5:
print(f" missed at conf 0.25: image {k} ({backgrounds[k % 6]}), person {g[3] - g[1]} px tall, best box IoU {best_iou:.2f}")
sdets = []
for img, gt in small:
r = model.predict(img[:, :, ::-1].copy(), conf=0.01, classes=[0], verbose=False)[0]
sdets.append(list(zip(r.boxes.conf.tolist(), r.boxes.xyxy.tolist())))
srows, _ = match(sdets, small); n_small = sum(len(b) for _, b in small)
hi = [r for r in srows if r[0] >= 0.25]; tp = sum(r[1] for r in hi)
print(f" half-size people: AP@0.5 {ap_from(srows, n_small):.3f}, at conf 0.25 TP {tp} of {n_small}, FP {len(hi) - tp}")yolov8n.pt: AP@0.5 0.971
conf >= 0.25: TP 34, FP 0, missed 1, precision 1.00, recall 0.97, FP per image 0.00
conf >= 0.5: TP 33, FP 0, missed 2, precision 1.00, recall 0.94, FP per image 0.00
found (any score) by height 90-149 / 150-249 / 250-330 px: 9 of 10 / 17 of 17 / 8 of 8
missed at conf 0.25: image 12 (coffee), person 102 px tall, best box IoU 0.00
half-size people: AP@0.5 0.879, at conf 0.25 TP 26 of 34, FP 2
yolo11n.pt: AP@0.5 1.000
conf >= 0.25: TP 34, FP 0, missed 1, precision 1.00, recall 0.97, FP per image 0.00
conf >= 0.5: TP 34, FP 0, missed 1, precision 1.00, recall 0.97, FP per image 0.00
found (any score) by height 90-149 / 150-249 / 250-330 px: 10 of 10 / 17 of 17 / 8 of 8
missed at conf 0.25: image 12 (coffee), person 102 px tall, best box IoU 0.00
half-size people: AP@0.5 0.960, at conf 0.25 TP 29 of 34, FP 2
Both YOLO models beat the classical detectors clearly: AP 0.971 (YOLOv8n) and 1.000 (YOLO11n), no false positive at conf 0.25 in any of the 30 images, including the six empty ones. Each misses one person at conf 0.25, the same one: image 12, a 102-pixel person pasted onto the coffee inside the cup. It is small and out of context, and YOLO11n still ranks it above every wrong box (hence AP 1.000), only with a score below 0.25. At half size the difference between the models opens: AP 0.879 for YOLOv8n and 0.960 for YOLO11n, with 26 and 29 of 34 people found at conf 0.25 and 2 false positives each. Small people are where detectors, and model choices, differ.
Results
| Detector | AP@0.5 | Operating point | Precision | Recall | FP per image | AP@0.5, half-size people |
|---|---|---|---|---|---|---|
| HOG people detector (OpenCV) | 0.000 | score | 0.00 | 0.00 | 0.77 | not run |
| Face cascade + body proportions | 0.826 | 3 neighbours | 0.78 | 0.83 | 0.27 | 0.412 |
| YOLOv8n, COCO person | 0.971 | conf 0.25 | 1.00 | 0.97 | 0.00 | 0.879 |
| YOLO11n, COCO person | 1.000 | conf 0.25 | 1.00 | 0.97 | 0.00 | 0.960 |
All on the same 30 generated test images (35 people, 6 empty images), IoU 0.5, VOC all-point AP. FP per image is false positives divided by 30.
Error analysis. HOG: wrong training domain (full-body pedestrians), fires on vertical textures. Face proxy: misses every person whose face is under about 24 pixels, and its box is only as good as the fixed body proportions. YOLO: one miss, a small person in an implausible place; recall drops for people under about 100 pixels.
Deployment notes
A working detector is the easy part of a people-detection system. Before running it on real cameras:
- People in video are personal data under the GDPR as soon as they can be identified, directly or with other information; detection alone (boxes, no identity) is less intrusive than recognition, but the video it runs on is still personal data. Decide the purpose (counting, safety zones), keep only what it needs (counts or anonymised boxes, not frames), set a retention period, inform people (signs) and do a data-protection impact assessment, which GDPR Art. 35(3)(c) requires for systematic monitoring of a publicly accessible area on a large scale.
- Do not drift into identification. Face templates used to recognise people are biometric data (GDPR Art. 4(14)), a special category under Art. 9 when processed to uniquely identify someone; re-identification across cameras is identification too, even when it uses clothing rather than biometrics. The EU AI Act (Art. 5(1)(h)) prohibits real-time remote biometric identification in publicly accessible spaces for law enforcement except in narrow cases (targeted search for victims or missing persons, an imminent threat to life or of a terrorist attack, locating suspects of listed serious crimes) (privacy, consent and licensing). Blur faces in anything you store (face detection shows how).
- Evaluate on your cameras. This project's numbers say nothing about a real site. Collect and label a test set from the deployment cameras (with consent and a lawful basis), covering night, rain, crowds, children, wheelchairs and people seen from behind, and report recall per group: a detector that misses one group more often is a safety and fairness problem.
- Choose the operating threshold on validation data and monitor it: a missed person and a false alarm have different costs (a safety stop versus a nuisance).
- Licences. Ultralytics models are AGPL-3.0 or commercially licensed; OpenCV is Apache 2.0.
Your turn
- Change the generator's height range to 40 to 120 pixels and rerun steps 3 and 4. Which detector degrades first?
Hint
The face proxy should collapse almost completely (faces of 8 to 24 pixels), YOLO should keep most people above roughly 60 pixels and lose more below. Compare AP and recall by height bin, not just the overall AP.
- Add partial occlusion: after pasting, cover the lower or upper half of some people with a background patch, keep the full box as ground truth, and measure recall. What is the right ground truth for an occluded person?
Hint
Annotation guidelines differ (annotation tasks): COCO boxes cover only the visible part, other data sets the full extent. Covering the face should hurt the face proxy most; check whether YOLO's boxes shrink to the visible part, which lowers IoU with a full-extent ground truth.
- Run YOLO with
conffrom 0.05 to 0.9 and plot precision and recall againstconf. Which threshold would you choose for a safety stop (missing a person is expensive) and for a people counter on a dashboard?
Hint
The safety stop needs high recall, so a low threshold and a tolerance for false stops; the counter needs both errors balanced. Choose on one half of the test images and report the other half, otherwise the threshold is tuned on the test set.
Write-up template
| Item | Your entry |
|---|---|
| Task and use | e.g. person detection for counting in a corridor |
| Test data | source, number of images and people, size range, what it does not cover |
| Metric and protocol | AP@0.5, VOC all-point; operating threshold and how it was chosen |
| Baseline | detector, AP, precision / recall / FP per image at its threshold |
| Improved model | detector, AP, precision / recall / FP per image, latency on the target hardware |
| Error analysis | missed people by size, occlusion, pose; false positives by type |
| Privacy and law | purpose, data kept, retention, signage, DPIA, no identification |
| Decision | deploy / collect more data / change model, and why |
Test yourself
The OpenCV HOG people detector scored AP 0 on this test set. What is the main reason?
- HOG cannot detect anything in colour images
- It was trained on full-body upright pedestrians, and the test people are waist-up portraits
- The IoU threshold was too strict
- NMS removed all its boxes
Why is the face-proxy result (AP 0.826) optimistic?
- Because AP is always optimistic
- Its body proportions were measured on the same woman who appears in every test image
- Because it uses a GPU
- Because the test set has empty images
Which statement about deploying a person detector on real cameras is correct?
- Detection boxes are never personal data, so no rules apply
- The video is personal data: define the purpose, minimise what is kept, inform people and evaluate on data from the real cameras
- A high AP on a public test set is enough
- Face recognition can be added freely for better accuracy