Project 11: Person Tracking
A public library wants three numbers from the camera above its entrance: how many people come in and go out each hour, how many are inside right now (the fire certificate allows 40), and how long people wait at the help desk. Nobody wants to know who they are. This project builds that people counter end to end: it measures what a pretrained person detector really delivers on this kind of footage, simulates a door scene with the awkward cases (pairs walking together, people who hesitate at the door, a queue at the desk), tracks and counts, picks the camera position and the counting rule on development clips, tests once, and runs a pilot day through a service that only ever receives counts. Level: advanced. Main skills: detector characterisation, tracking by detection, event rules, product metrics, privacy by design.
Two earlier projects already track things. Multi-object tracking improves the tracker itself and scores it with MOTA and IDF1; real-time video analytics counts vehicles on lanes within a latency budget. This one is about people and the product: the number that matters is the hourly count and the occupancy, not IDF1, and the decisions that move it most turn out to be the counting rule and where the camera hangs, not the tracker's internals. The tracker is the compact SORT of those projects; read multi-object tracking for the Kalman filter, the Hungarian matching and the metrics.
Note: Video of people is personal data even when nobody is named. In the EU and UK a people counter needs a lawful basis (for a private business usually legitimate interests, with a balancing test; a public library run by a public authority cannot use legitimate interests for its tasks and relies on public task, Article 6(1)(e)), signs at the entrance that say what is recorded and why, and, for systematic monitoring of a publicly accessible area on a large scale, a data protection impact assessment. Staff are filmed too, which can bring in workplace monitoring rules and works councils. The design here follows data minimisation: frames are processed on the device and thrown away, and only counts and durations leave it (privacy, consent and licensing, governance). All people in this lesson are synthetic.
Goal and success criteria
Fixed before any result:
| Requirement | Metric | Target | Measured on |
|---|---|---|---|
| Entries and exits | summed absolute error of the in and out counts, as a share of the true crossings | at most 5 % | 6 test clips (3 normal, 3 busy), once |
| Occupancy | at the end of every hour | at most 2 people | the pilot day |
| Desk waiting time | median desk visit (at least 3 s) | within 0.5 s of the truth | the pilot day |
| Privacy | what leaves the device | counts and durations only: no frames, boxes or track ids | a schema test on the service |
Occupancy is a running sum, with at opening, so every counting error stays in it until the next reset. That is why the count target is strict.
Step 1: what the detector delivers (recorded)
A counter is only as good as the detections it gets. Before simulating anything, measure the pretrained YOLO11n (COCO's person class, see Ultralytics YOLO) on frames that look like the door camera: the astronaut from scikit-image walking across a brick wall at four distances from the camera, and two people passing each other. The person box inside the photo is the one drawn by hand in project 2 of the CV course, which measured YOLO on still images; here the question is how often a person is lost in a sequence of frames, because that is what breaks a track. This example imports ultralytics, so it is recorded: run on a CPU in Docker, output saved.
import numpy as np
import cv2
from ultralytics import YOLO
from skimage import data
PERSON = [8, 12, 366, 512] # the woman in data.astronaut()[:, :400] (x2, y2 exclusive), as in CV project 2
SRC = data.astronaut()[:, :400]
BG = cv2.resize(np.repeat(data.brick()[:, :, None], 3, axis=2), (480, 270), interpolation=cv2.INTER_AREA)
def paste(img, h, cx, mirror=False):
"""Paste the person, h pixels tall, standing on the floor (bottom of the image), centre at x = cx.
Returns the true person box [x1, y1, x2, y2] in the frame (clipped to the image)."""
s = h / 512; w = round(400 * s)
crop = cv2.resize(SRC, (w, h), interpolation=cv2.INTER_AREA)
b1, b2 = PERSON[0], PERSON[2]
if mirror:
crop = crop[:, ::-1]; b1, b2 = 400 - PERSON[2], 400 - PERSON[0]
x0 = int(round(cx - w / 2)); y0 = 270 - h
xa, xb = max(x0, 0), min(x0 + w, 480)
img[y0:, xa:xb] = crop[:, xa - x0:xb - x0]
return [max(x0 + round(b1 * s), 0), y0 + round(PERSON[1] * s), min(x0 + round(b2 * s), 480), 270]
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)
model = YOLO("yolo11n.pt")
def people(img, conf=0.25):
r = model.predict(img[:, :, ::-1].copy(), conf=conf, classes=[0], verbose=False)[0]
return r.boxes.xyxy.tolist(), r.boxes.conf.tolist()
# A: one person walks through the door view, 30 frames, at four camera distances (person heights)
for h in [50, 80, 120, 180]:
hits, ious, confs = 0, [], []
for t in range(30):
img = BG.copy()
gt = paste(img, h, 40 + 400 * t / 29)
boxes, cs = people(img)
best = max([(iou(b, gt), c) for b, c in zip(boxes, cs)], default=(0.0, 0.0))
if best[0] >= 0.5:
hits += 1; ious.append(best[0]); confs.append(best[1])
print(f"person {h:3d} px tall: detected in {hits:2d} of 30 frames, mean IoU {np.mean(ious) if ious else 0:.2f}, "
f"mean conf {np.mean(confs) if confs else 0:.2f}")
# B: two people, 150 px tall, walk towards each other and pass (the right one is in front)
counts, merged = [], 0
for t in range(30):
img = BG.copy()
a = paste(img, 150, 60 + 360 * t / 29)
b = paste(img, 150, 420 - 360 * t / 29, mirror=True)
boxes, _ = people(img)
counts.append(len(boxes))
print("boxes per frame while passing:", "".join(str(c) for c in counts))
print("frames with 2 people but fewer than 2 boxes:", sum(c < 2 for c in counts), "of 30")person 50 px tall: detected in 7 of 30 frames, mean IoU 0.90, mean conf 0.42
person 80 px tall: detected in 29 of 30 frames, mean IoU 0.96, mean conf 0.75
person 120 px tall: detected in 30 of 30 frames, mean IoU 0.97, mean conf 0.87
person 180 px tall: detected in 30 of 30 frames, mean IoU 0.96, mean conf 0.90
boxes per frame while passing: 222222222222211112222222222222
frames with 2 people but fewer than 2 boxes: 4 of 30
Two facts come out, and the simulation below uses both. A person at least 80 pixels tall is found in nearly every frame (29 and 30 of 30, IoU about 0.96), but at 50 pixels only 7 of 30 frames have a box: the camera must be mounted so that people are at least about 80 pixels tall where they cross the line. And when two people overlap, the detector returns one box for both during the 4 frames of the pass. The simulated detector therefore misses 3 % of the visible people, misses anyone more than half covered by a person nearer the camera, and jitters the box corners by 2 pixels. A real project measures these rates on a few hundred labelled frames from its own camera (annotation tasks).
The data
make_clip simulates one minute at the door at 10 frames per second (detection on every third frame of a 30 fps stream is typical on an edge device). People arrive at random from outside (left) and inside (right) and follow a script:
- in and out: walk through, 6 to 10 pixels per frame; a quarter of them come as a pair, 2 to 4 frames apart;
- loiter: walk to the door, sway back and forth across the line for 2 to 5 seconds (reading the opening hours), turn back;
- hesitate: the same sway, then go in;
- 40 % of those who go in stop at the help desk () for 3 to 12 seconds, where they lean over the counter and the detector misses a quarter of their frames.
The truth is known exactly: a loiterer never entered, a hesitating visitor entered once. The same scripts are rendered by two cameras. The side camera sees full-body boxes, and a person nearer the camera hides the one behind; the overhead camera sees 44 x 44 pixel head-and-shoulder boxes spread across the width of the door, so two people walking side by side are apart in the image.
Development clips are seeds 0 to 2; every choice is made on them. Test clips are seeds 10 to 15, used once. The pilot day uses seeds 20 to 27. Each runnable example below is a complete program that regenerates the clips it needs. The scores are about this generator: a real door has children, prams, umbrellas and people carrying boxes, which no simulator covers, so a pilot with hand counts is part of the project (see Extensions).
Step 2: the baseline and three counting rules
The first pipeline uses the side camera, the compact tracker (max_age 5 frames, min_hits 3) and three rules that turn a track into crossings:
- naive: every change of side of the box centre counts;
- once per track: the first crossing only, the rule of the video analytics project, which is right for cars that never turn back;
- band: hysteresis. A track changes side only when its centre is more than 30 pixels past the line; inside the band it keeps its last side. A person can go in and come back out on one track and is counted twice, correctly.
The rules are also applied to the true paths, and the example counts the crossers who were never detected within 40 pixels of the line.
import numpy as np
from scipy.optimize import linear_sum_assignment
W, LINE, DESK = 480, 240, (360, 440) # frame width, door line x, help-desk zone (outside is left)
def make_clip(rng, rate=(0.02, 0.02), n=600):
"""One minute at the door at 10 fps. People arrive from outside or inside (rate per frame) and follow
a script: in, out, loiter (sways across the line, turns back) or hesitate (sways, then goes in).
Some who go in stop at the desk; a quarter of in/out walkers come as a pair.
Returns (pid, kind, start frame, x path, height, u = position across the door 0..1) per person."""
walk = lambda a, b, v: list(np.linspace(a, b, max(int(abs(b - a) / v), 1) + 1)[1:])
people = []
for t0 in range(n - 60):
for side in (0, 1):
if rng.random() >= rate[side]:
continue
v = rng.uniform(6, 10)
kind = "out" if side else str(rng.choice(["in", "loiter", "hesitate"], p=[0.7, 0.15, 0.15]))
xs = walk(510, -30, v) if side else walk(-30, LINE - 15, v)
if kind in ("loiter", "hesitate"): # sway across the line for 2-5 s
k = np.arange(int(rng.integers(20, 50)))
xs += list(LINE + rng.uniform(10, 25) * np.sin(k / 3) + rng.normal(0, 1, k.size))
if kind == "loiter":
xs += walk(xs[-1], -30, v)
elif side == 0 and rng.random() < 0.4: # stops at the desk for 3-12 s
xd = rng.uniform(380, 420)
xs += walk(xs[-1], xd, v) + list(xd + rng.normal(0, 1, int(rng.integers(30, 120))))
xs += walk(xs[-1], 510, v)
elif side == 0:
xs += walk(xs[-1], 510, v)
h = rng.uniform(110, 140)
for lag in ([0, int(rng.integers(2, 5))] if kind in ("in", "out") and rng.random() < 0.25 else [0]):
people.append((len(people), kind, t0 + lag, np.array(xs), h * rng.uniform(0.9, 1.1), rng.uniform(0, 1)))
return people
def view(people, camera="side", n=600):
"""Per frame a list of (pid, box). side: full-body boxes, people with larger u nearer the camera
(lower in the image, in front); top: an overhead camera sees 44 x 44 px head-and-shoulder boxes."""
frames = [[] for _ in range(n)]
for pid, kind, t0, xs, h, u in people:
for i, cx in enumerate(xs):
hw = 0.22 * h if camera == "side" else 22
y1, y2 = (240 + 28 * u - h, 240 + 28 * u) if camera == "side" else (10 + 206 * u, 54 + 206 * u)
b = [max(cx - hw, 0), y1, min(cx + hw, W), y2]
if t0 + i < n and b[2] - b[0] >= 10: # at least 10 px inside the frame
frames[t0 + i].append((pid, b))
return frames
def detector(frames, rng, p_miss=0.03, p_desk=0.25, jitter=2.0, fp_rate=0.01):
"""Simulated person detector (numbers from step 1): misses people more than half covered by a box
nearer the camera (lower in the image; overhead, NMS keeps one of two boxes that overlap so much), drops others with p_miss (p_desk at the desk, where people lean over the
counter), jitters corners, adds a rare 44 x 44 false box. Returns per frame a (k, 4) array (no ids)
and, for the analysis only, the set of people detected."""
out, seen = [], []
for objs in frames:
dets, ids = [], set()
for pid, b in objs:
cover = max([max(0, min(b[2], c[2]) - max(b[0], c[0])) * max(0, min(b[3], c[3]) - max(b[1], c[1]))
for q, c in objs if q != pid and c[3] > b[3]], default=0) / ((b[2] - b[0]) * (b[3] - b[1]))
p = p_desk if DESK[0] <= (b[0] + b[2]) / 2 < DESK[1] else p_miss
if cover <= 0.5 and rng.random() > p:
dets.append(np.array(b) + rng.normal(0, jitter, 4)); ids.add(pid)
if rng.random() < fp_rate:
x, y = rng.uniform(0, W - 44), rng.uniform(0, 226)
dets.append(np.array([x, y, x + 44, y + 44]))
out.append(np.array(dets).reshape(-1, 4)); seen.append(ids)
return out, seen
def iou(a, b):
a, b = a[:, None], b[None]
inter = (np.clip(np.minimum(a[..., 2], b[..., 2]) - np.maximum(a[..., 0], b[..., 0]), 0, None)
* np.clip(np.minimum(a[..., 3], b[..., 3]) - np.maximum(a[..., 1], b[..., 1]), 0, None))
area = lambda r: (r[..., 2] - r[..., 0]) * (r[..., 3] - r[..., 1])
return inter / (area(a) + area(b) - inter)
def track(dets, max_age=5, min_hits=3, iou_thr=0.2):
"""Compact SORT-style tracker (constant velocity, IoU + Hungarian, min_hits, max_age).
Returns {track id: [(frame, centre x), ...]} for confirmed tracks."""
tracks, nid, P = [], 1, {}
for f, D in enumerate(dets):
pred = np.array([t["box"] + t["v"] * (t["miss"] + 1) for t in tracks]).reshape(-1, 4)
C = iou(pred, D) if len(pred) and len(D) else np.zeros((len(pred), len(D)))
pairs = [(r, c) for r, c in zip(*linear_sum_assignment(-C)) if C[r, c] >= iou_thr]
for t in tracks:
t["miss"] += 1
for r, c in pairs:
t = tracks[r]
t["v"] = 0.5 * t["v"] + 0.5 * (D[c] - t["box"]) / t["miss"]
t["box"], t["miss"], t["hits"] = D[c], 0, t["hits"] + 1
tracks = [t for t in tracks if t["miss"] <= max_age]
tracks += [dict(id=None, box=D[c], v=np.zeros(4), miss=0, hits=1) for c in set(range(len(D))) - {c for _, c in pairs}]
for t in tracks:
if t["id"] is None and t["hits"] >= min_hits:
t["id"], nid = nid, nid + 1
if t["id"] is not None and t["miss"] == 0:
P.setdefault(t["id"], []).append((f, (t["box"][0] + t["box"][2]) / 2))
return P
def count_band(P, band=30):
"""Hysteresis: a track's side changes only when its centre is more than `band` px past the line."""
n_in = n_out = 0
for p in P.values():
side = None
for _, c in p:
new = "out" if c < LINE - band else "in" if c > LINE + band else side
n_in += side == "out" and new == "in"; n_out += side == "in" and new == "out"
side = new
return n_in, n_out
def truth(people):
return sum(k in ("in", "hesitate") for _, k, *_ in people), sum(k == "out" for _, k, *_ in people)
def count_naive(P):
"""Every change of side of the centre is a crossing."""
n_in = n_out = 0
for p in P.values():
s = np.sign(np.array([c for _, c in p]) - LINE); s = s[s != 0]
n_in += int(np.sum((s[:-1] < 0) & (s[1:] > 0))); n_out += int(np.sum((s[:-1] > 0) & (s[1:] < 0)))
return n_in, n_out
def count_once(P):
"""Only the first crossing of each track, as in the CV video-analytics project."""
n_in = n_out = 0
for p in P.values():
s = np.sign(np.array([c for _, c in p]) - LINE); s = s[s != 0]
k = np.flatnonzero(s[:-1] != s[1:])
n_in += len(k) > 0 and s[k[0]] < 0; n_out += len(k) > 0 and s[k[0]] > 0
return n_in, n_out
print("clip people truth in/out naive once band 30 band on true paths tracks crossers never seen at the line")
for seed in (0, 1, 2): # development clips
people = make_clip(np.random.default_rng(seed))
frames = view(people, "side")
D, seen = detector(frames, np.random.default_rng(100 + seed))
P = track(D)
G = {pid: [(t, (b[0] + b[2]) / 2) for t, objs in enumerate(frames) for q, b in objs if q == pid] for pid, *_ in people}
near = {pid: any(pid in seen[t] for t, c in G[pid] if abs(c - LINE) < 40) for pid, *_ in people}
blind = [k for pid, k, *_ in people if k in ("in", "out", "hesitate") and not near[pid]]
fmt = lambda c: f"{c[0]:2d} / {c[1]:2d}"
print(f"{seed:4d} {len(people):6d} {fmt(truth(people)):12s} {fmt(count_naive(P))} {fmt(count_once(P))} "
f"{fmt(count_band(P))} {fmt(count_band(G)):18s} {len(P):6d} {len(blind)} ({', '.join(sorted(blind))})")clip people truth in/out naive once band 30 band on true paths tracks crossers never seen at the line
0 37 14 / 23 13 / 20 9 / 16 9 / 17 14 / 23 46 7 (in, in, in, out, out, out, out)
1 28 13 / 13 15 / 13 11 / 8 10 / 8 13 / 13 33 7 (in, in, out, out, out, out, out)
2 28 18 / 9 19 / 14 12 / 6 11 / 6 18 / 9 43 6 (in, in, in, in, out, out)
Read the table from the right. On the true paths the band rule gives exactly the truth in all three clips (14 / 23, 13 / 13, 18 / 9): the rule is right, loiterers and hesitating visitors included. The naive rule happens to come close in clips 0 and 1 (13 / 20, 15 / 13), but for the wrong reasons: every sway of a loiterer adds a crossing in and out, and that over-count partly cancels an under-count; in clip 2 it reports 14 exits for 9. On the tracker's output the band rule under-counts badly (9 / 17, 10 / 8, 11 / 6), and the last two columns say why. There are more tracks than people (46 for 37 in clip 0), so tracks break, and 6 or 7 people per clip who crossed were never detected near the line at all: they were hidden behind someone nearer the camera, most often the other person of a pair. No tracker can count a person it never sees. This is the error analysis that decides the next step (error analysis).
Step 3: choosing the camera and the rule, then testing once
Two cameras, two values of max_age (0.3 s or 1 s of coasting) and three band widths are compared on the development clips by the summed absolute count error. The overhead camera with max_age 10 and a 30-pixel band is then run once on the six test clips, three normal and three busy minutes with twice the arrival rate. The side camera is shown on the same test clips only for reference; it was not chosen on them.
import numpy as np
from scipy.optimize import linear_sum_assignment
W, LINE, DESK = 480, 240, (360, 440) # frame width, door line x, help-desk zone (outside is left)
def make_clip(rng, rate=(0.02, 0.02), n=600):
"""One minute at the door at 10 fps. People arrive from outside or inside (rate per frame) and follow
a script: in, out, loiter (sways across the line, turns back) or hesitate (sways, then goes in).
Some who go in stop at the desk; a quarter of in/out walkers come as a pair.
Returns (pid, kind, start frame, x path, height, u = position across the door 0..1) per person."""
walk = lambda a, b, v: list(np.linspace(a, b, max(int(abs(b - a) / v), 1) + 1)[1:])
people = []
for t0 in range(n - 60):
for side in (0, 1):
if rng.random() >= rate[side]:
continue
v = rng.uniform(6, 10)
kind = "out" if side else str(rng.choice(["in", "loiter", "hesitate"], p=[0.7, 0.15, 0.15]))
xs = walk(510, -30, v) if side else walk(-30, LINE - 15, v)
if kind in ("loiter", "hesitate"): # sway across the line for 2-5 s
k = np.arange(int(rng.integers(20, 50)))
xs += list(LINE + rng.uniform(10, 25) * np.sin(k / 3) + rng.normal(0, 1, k.size))
if kind == "loiter":
xs += walk(xs[-1], -30, v)
elif side == 0 and rng.random() < 0.4: # stops at the desk for 3-12 s
xd = rng.uniform(380, 420)
xs += walk(xs[-1], xd, v) + list(xd + rng.normal(0, 1, int(rng.integers(30, 120))))
xs += walk(xs[-1], 510, v)
elif side == 0:
xs += walk(xs[-1], 510, v)
h = rng.uniform(110, 140)
for lag in ([0, int(rng.integers(2, 5))] if kind in ("in", "out") and rng.random() < 0.25 else [0]):
people.append((len(people), kind, t0 + lag, np.array(xs), h * rng.uniform(0.9, 1.1), rng.uniform(0, 1)))
return people
def view(people, camera="side", n=600):
"""Per frame a list of (pid, box). side: full-body boxes, people with larger u nearer the camera
(lower in the image, in front); top: an overhead camera sees 44 x 44 px head-and-shoulder boxes."""
frames = [[] for _ in range(n)]
for pid, kind, t0, xs, h, u in people:
for i, cx in enumerate(xs):
hw = 0.22 * h if camera == "side" else 22
y1, y2 = (240 + 28 * u - h, 240 + 28 * u) if camera == "side" else (10 + 206 * u, 54 + 206 * u)
b = [max(cx - hw, 0), y1, min(cx + hw, W), y2]
if t0 + i < n and b[2] - b[0] >= 10: # at least 10 px inside the frame
frames[t0 + i].append((pid, b))
return frames
def detector(frames, rng, p_miss=0.03, p_desk=0.25, jitter=2.0, fp_rate=0.01):
"""Simulated person detector (numbers from step 1): misses people more than half covered by a box
nearer the camera (lower in the image; overhead, NMS keeps one of two boxes that overlap so much), drops others with p_miss (p_desk at the desk, where people lean over the
counter), jitters corners, adds a rare 44 x 44 false box. Returns per frame a (k, 4) array (no ids)
and, for the analysis only, the set of people detected."""
out, seen = [], []
for objs in frames:
dets, ids = [], set()
for pid, b in objs:
cover = max([max(0, min(b[2], c[2]) - max(b[0], c[0])) * max(0, min(b[3], c[3]) - max(b[1], c[1]))
for q, c in objs if q != pid and c[3] > b[3]], default=0) / ((b[2] - b[0]) * (b[3] - b[1]))
p = p_desk if DESK[0] <= (b[0] + b[2]) / 2 < DESK[1] else p_miss
if cover <= 0.5 and rng.random() > p:
dets.append(np.array(b) + rng.normal(0, jitter, 4)); ids.add(pid)
if rng.random() < fp_rate:
x, y = rng.uniform(0, W - 44), rng.uniform(0, 226)
dets.append(np.array([x, y, x + 44, y + 44]))
out.append(np.array(dets).reshape(-1, 4)); seen.append(ids)
return out, seen
def iou(a, b):
a, b = a[:, None], b[None]
inter = (np.clip(np.minimum(a[..., 2], b[..., 2]) - np.maximum(a[..., 0], b[..., 0]), 0, None)
* np.clip(np.minimum(a[..., 3], b[..., 3]) - np.maximum(a[..., 1], b[..., 1]), 0, None))
area = lambda r: (r[..., 2] - r[..., 0]) * (r[..., 3] - r[..., 1])
return inter / (area(a) + area(b) - inter)
def track(dets, max_age=5, min_hits=3, iou_thr=0.2):
"""Compact SORT-style tracker (constant velocity, IoU + Hungarian, min_hits, max_age).
Returns {track id: [(frame, centre x), ...]} for confirmed tracks."""
tracks, nid, P = [], 1, {}
for f, D in enumerate(dets):
pred = np.array([t["box"] + t["v"] * (t["miss"] + 1) for t in tracks]).reshape(-1, 4)
C = iou(pred, D) if len(pred) and len(D) else np.zeros((len(pred), len(D)))
pairs = [(r, c) for r, c in zip(*linear_sum_assignment(-C)) if C[r, c] >= iou_thr]
for t in tracks:
t["miss"] += 1
for r, c in pairs:
t = tracks[r]
t["v"] = 0.5 * t["v"] + 0.5 * (D[c] - t["box"]) / t["miss"]
t["box"], t["miss"], t["hits"] = D[c], 0, t["hits"] + 1
tracks = [t for t in tracks if t["miss"] <= max_age]
tracks += [dict(id=None, box=D[c], v=np.zeros(4), miss=0, hits=1) for c in set(range(len(D))) - {c for _, c in pairs}]
for t in tracks:
if t["id"] is None and t["hits"] >= min_hits:
t["id"], nid = nid, nid + 1
if t["id"] is not None and t["miss"] == 0:
P.setdefault(t["id"], []).append((f, (t["box"][0] + t["box"][2]) / 2))
return P
def count_band(P, band=30):
"""Hysteresis: a track's side changes only when its centre is more than `band` px past the line."""
n_in = n_out = 0
for p in P.values():
side = None
for _, c in p:
new = "out" if c < LINE - band else "in" if c > LINE + band else side
n_in += side == "out" and new == "in"; n_out += side == "in" and new == "out"
side = new
return n_in, n_out
def truth(people):
return sum(k in ("in", "hesitate") for _, k, *_ in people), sum(k == "out" for _, k, *_ in people)
def run(people, seed, camera, max_age=10, band=30):
D, _ = detector(view(people, camera), np.random.default_rng(100 + seed))
return count_band(track(D, max_age=max_age), band)
dev = {s: make_clip(np.random.default_rng(s)) for s in (0, 1, 2)}
print("development clips 0-2: summed |error| of in and out counts")
for camera in ("side", "top"):
for max_age in (3, 10):
row = []
for band in (10, 20, 30):
err = 0
for s, people in dev.items():
(i, o), (a, b) = run(people, s, camera, max_age, band), truth(people)
err += abs(i - a) + abs(o - b)
row.append(f"band {band}: {err:2d}")
print(f" {camera} camera, max_age {max_age:2d}: " + " ".join(row))
print("test clips (used once): overhead camera, max_age 10, band 30; side camera for reference")
tot = {"side": [0, 0], "top": [0, 0]}
for s, rate in [(10, 0.02), (11, 0.02), (12, 0.02), (13, 0.04), (14, 0.04), (15, 0.04)]:
people = make_clip(np.random.default_rng(s), rate=(rate, rate)); a, b = truth(people)
line = f" clip {s} ({'busy' if rate > 0.02 else 'normal'}): truth {a:2d} in / {b:2d} out"
for camera in ("top", "side"):
i, o = run(people, s, camera)
tot[camera][0] += abs(i - a) + abs(o - b); tot[camera][1] += a + b
line += f" | {camera} {i:2d} / {o:2d}"
print(line)
for camera, (e, n) in tot.items():
print(f" {camera}: summed |error| {e} of {n} crossings ({100 * e / n:.1f} %)")development clips 0-2: summed |error| of in and out counts
side camera, max_age 3: band 10: 12 band 20: 31 band 30: 35
side camera, max_age 10: band 10: 11 band 20: 19 band 30: 23
top camera, max_age 3: band 10: 34 band 20: 2 band 30: 0
top camera, max_age 10: band 10: 34 band 20: 2 band 30: 0
test clips (used once): overhead camera, max_age 10, band 30; side camera for reference
clip 10 (normal): truth 9 in / 15 out | top 9 / 15 | side 9 / 13
clip 11 (normal): truth 6 in / 12 out | top 6 / 12 | side 6 / 10
clip 12 (normal): truth 13 in / 15 out | top 13 / 15 | side 11 / 13
clip 13 (busy): truth 30 in / 30 out | top 28 / 28 | side 24 / 22
clip 14 (busy): truth 16 in / 39 out | top 16 / 36 | side 8 / 23
clip 15 (busy): truth 21 in / 23 out | top 21 / 23 | side 14 / 20
side: summed |error| 56 of 229 crossings (24.5 %)
top: summed |error| 7 of 229 crossings (3.1 %)
On the side camera no setting fixes the hidden companions: the best development error is 11, with the narrow 10-pixel band, which again over-counts sways to compensate for missed people (a "good" setting that works by cancelling two errors will not survive a different mix of visitors). The overhead camera removes the occlusion and the development error drops to 0 at a 30-pixel band; the 10-pixel band is too narrow for loiterers who sway up to 25 pixels (error 34). max_age makes no difference on these clips; 10 frames is kept because the desk zone loses a quarter of its detections and a second of coasting costs nothing at this frame rate.
On the test clips the overhead counter is exact in the normal minutes and loses 7 crossings in the busy ones (28 / 28 for 30 / 30, 16 / 36 for 16 / 39), when people's head boxes overlap enough for one to be suppressed: 7 of 229 crossings, 3.1 %, within the 5 % target. The side camera would have missed 24.5 %. The decision that mattered most was a mounting bracket, not a model. One honest caveat: COCO detectors are trained mostly on photos taken from the side, and top-down views of heads are rare in COCO, so a real overhead counter needs a detector fine-tuned on overhead footage (project 10 builds and fine-tunes such a dataset); the simulation assumes it reaches the same 3 % miss rate.
Step 4: the pilot day, through the service
Before the library relies on it, the counter runs for a day. The pilot day has one sample minute per opening hour (9:00 to 16:00): many arrivals in the morning, people leaving in the afternoon. The device runs the overhead pipeline chosen in step 3 and sends one summary per hour to a small service, which keeps the occupancy (the running sum above) and builds reports. The service runs in memory through httpx.ASGITransport, exactly as in FastAPI basics.
Privacy is enforced by the interface, not by a promise. The request model has extra="forbid", so a summary that carries track ids, boxes or crops is rejected with a 422, and the desk median is suppressed when it would describe fewer than 5 visits (one person's visit is not an average). The example also runs the side camera on the same day for comparison, and measures the desk visits with 3 frames of coasting instead of 10, to see what coasting buys.
import numpy as np
from scipy.optimize import linear_sum_assignment
W, LINE, DESK = 480, 240, (360, 440) # frame width, door line x, help-desk zone (outside is left)
def make_clip(rng, rate=(0.02, 0.02), n=600):
"""One minute at the door at 10 fps. People arrive from outside or inside (rate per frame) and follow
a script: in, out, loiter (sways across the line, turns back) or hesitate (sways, then goes in).
Some who go in stop at the desk; a quarter of in/out walkers come as a pair.
Returns (pid, kind, start frame, x path, height, u = position across the door 0..1) per person."""
walk = lambda a, b, v: list(np.linspace(a, b, max(int(abs(b - a) / v), 1) + 1)[1:])
people = []
for t0 in range(n - 60):
for side in (0, 1):
if rng.random() >= rate[side]:
continue
v = rng.uniform(6, 10)
kind = "out" if side else str(rng.choice(["in", "loiter", "hesitate"], p=[0.7, 0.15, 0.15]))
xs = walk(510, -30, v) if side else walk(-30, LINE - 15, v)
if kind in ("loiter", "hesitate"): # sway across the line for 2-5 s
k = np.arange(int(rng.integers(20, 50)))
xs += list(LINE + rng.uniform(10, 25) * np.sin(k / 3) + rng.normal(0, 1, k.size))
if kind == "loiter":
xs += walk(xs[-1], -30, v)
elif side == 0 and rng.random() < 0.4: # stops at the desk for 3-12 s
xd = rng.uniform(380, 420)
xs += walk(xs[-1], xd, v) + list(xd + rng.normal(0, 1, int(rng.integers(30, 120))))
xs += walk(xs[-1], 510, v)
elif side == 0:
xs += walk(xs[-1], 510, v)
h = rng.uniform(110, 140)
for lag in ([0, int(rng.integers(2, 5))] if kind in ("in", "out") and rng.random() < 0.25 else [0]):
people.append((len(people), kind, t0 + lag, np.array(xs), h * rng.uniform(0.9, 1.1), rng.uniform(0, 1)))
return people
def view(people, camera="side", n=600):
"""Per frame a list of (pid, box). side: full-body boxes, people with larger u nearer the camera
(lower in the image, in front); top: an overhead camera sees 44 x 44 px head-and-shoulder boxes."""
frames = [[] for _ in range(n)]
for pid, kind, t0, xs, h, u in people:
for i, cx in enumerate(xs):
hw = 0.22 * h if camera == "side" else 22
y1, y2 = (240 + 28 * u - h, 240 + 28 * u) if camera == "side" else (10 + 206 * u, 54 + 206 * u)
b = [max(cx - hw, 0), y1, min(cx + hw, W), y2]
if t0 + i < n and b[2] - b[0] >= 10: # at least 10 px inside the frame
frames[t0 + i].append((pid, b))
return frames
def detector(frames, rng, p_miss=0.03, p_desk=0.25, jitter=2.0, fp_rate=0.01):
"""Simulated person detector (numbers from step 1): misses people more than half covered by a box
nearer the camera (lower in the image; overhead, NMS keeps one of two boxes that overlap so much), drops others with p_miss (p_desk at the desk, where people lean over the
counter), jitters corners, adds a rare 44 x 44 false box. Returns per frame a (k, 4) array (no ids)
and, for the analysis only, the set of people detected."""
out, seen = [], []
for objs in frames:
dets, ids = [], set()
for pid, b in objs:
cover = max([max(0, min(b[2], c[2]) - max(b[0], c[0])) * max(0, min(b[3], c[3]) - max(b[1], c[1]))
for q, c in objs if q != pid and c[3] > b[3]], default=0) / ((b[2] - b[0]) * (b[3] - b[1]))
p = p_desk if DESK[0] <= (b[0] + b[2]) / 2 < DESK[1] else p_miss
if cover <= 0.5 and rng.random() > p:
dets.append(np.array(b) + rng.normal(0, jitter, 4)); ids.add(pid)
if rng.random() < fp_rate:
x, y = rng.uniform(0, W - 44), rng.uniform(0, 226)
dets.append(np.array([x, y, x + 44, y + 44]))
out.append(np.array(dets).reshape(-1, 4)); seen.append(ids)
return out, seen
def iou(a, b):
a, b = a[:, None], b[None]
inter = (np.clip(np.minimum(a[..., 2], b[..., 2]) - np.maximum(a[..., 0], b[..., 0]), 0, None)
* np.clip(np.minimum(a[..., 3], b[..., 3]) - np.maximum(a[..., 1], b[..., 1]), 0, None))
area = lambda r: (r[..., 2] - r[..., 0]) * (r[..., 3] - r[..., 1])
return inter / (area(a) + area(b) - inter)
def track(dets, max_age=5, min_hits=3, iou_thr=0.2):
"""Compact SORT-style tracker (constant velocity, IoU + Hungarian, min_hits, max_age).
Returns {track id: [(frame, centre x), ...]} for confirmed tracks."""
tracks, nid, P = [], 1, {}
for f, D in enumerate(dets):
pred = np.array([t["box"] + t["v"] * (t["miss"] + 1) for t in tracks]).reshape(-1, 4)
C = iou(pred, D) if len(pred) and len(D) else np.zeros((len(pred), len(D)))
pairs = [(r, c) for r, c in zip(*linear_sum_assignment(-C)) if C[r, c] >= iou_thr]
for t in tracks:
t["miss"] += 1
for r, c in pairs:
t = tracks[r]
t["v"] = 0.5 * t["v"] + 0.5 * (D[c] - t["box"]) / t["miss"]
t["box"], t["miss"], t["hits"] = D[c], 0, t["hits"] + 1
tracks = [t for t in tracks if t["miss"] <= max_age]
tracks += [dict(id=None, box=D[c], v=np.zeros(4), miss=0, hits=1) for c in set(range(len(D))) - {c for _, c in pairs}]
for t in tracks:
if t["id"] is None and t["hits"] >= min_hits:
t["id"], nid = nid, nid + 1
if t["id"] is not None and t["miss"] == 0:
P.setdefault(t["id"], []).append((f, (t["box"][0] + t["box"][2]) / 2))
return P
def count_band(P, band=30):
"""Hysteresis: a track's side changes only when its centre is more than `band` px past the line."""
n_in = n_out = 0
for p in P.values():
side = None
for _, c in p:
new = "out" if c < LINE - band else "in" if c > LINE + band else side
n_in += side == "out" and new == "in"; n_out += side == "in" and new == "out"
side = new
return n_in, n_out
def truth(people):
return sum(k in ("in", "hesitate") for _, k, *_ in people), sum(k == "out" for _, k, *_ in people)
import asyncio, httpx
from fastapi import FastAPI
from pydantic import BaseModel, ConfigDict, Field
def desk_visits(P, min_s=3.0):
"""Seconds from the first to the last frame with the centre in the desk zone, per track (>= min_s)."""
out = []
for p in P.values():
f = [t for t, c in p if DESK[0] <= c < DESK[1]]
if f and (f[-1] - f[0] + 1) / 10 >= min_s:
out.append(round((f[-1] - f[0] + 1) / 10, 1))
return sorted(out)
class Summary(BaseModel): # all the device may send
model_config = ConfigDict(extra="forbid") # anything else (ids, boxes, crops) is rejected
hour: int = Field(ge=0, le=23)
entries: int = Field(ge=0)
exits: int = Field(ge=0)
desk_seconds: list[float] = []
app = FastAPI(title="footfall")
STORE = {"occupancy": 0, "hours": {}}
MIN_GROUP = 5 # no dwell statistics from fewer visits
@app.post("/summaries")
async def add(s: Summary):
STORE["occupancy"] = max(STORE["occupancy"] + s.entries - s.exits, 0)
STORE["hours"][s.hour] = s
return {"occupancy": STORE["occupancy"], "over_limit": STORE["occupancy"] > 40}
@app.get("/report")
async def report(hour: int | None = None):
rows = [s for h, s in STORE["hours"].items() if hour is None or h == hour]
d = [x for s in rows for x in s.desk_seconds]
return {"entries": sum(s.entries for s in rows), "exits": sum(s.exits for s in rows), "desk_visits": len(d),
"desk_median_s": round(float(np.median(d)), 1) if len(d) >= MIN_GROUP else "suppressed (< 5 visits)"}
# The pilot day: one sample minute per opening hour, arrivals in the morning, people leaving in the afternoon
RATES = [(0.03, 0.0), (0.03, 0.007), (0.025, 0.01), (0.02, 0.014), (0.02, 0.014), (0.015, 0.018), (0.01, 0.021), (0.0, 0.021)]
async def main():
true_occ = side_occ = 0
visits = {"true": [], "max_age 10": [], "max_age 3": []}
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:
print("hour true in/out sent in/out desk visits occupancy: true service side camera")
for h, rate in enumerate(RATES):
people = make_clip(np.random.default_rng(20 + h), rate=rate)
a, b = truth(people); true_occ += a - b
top = view(people, "top")
D, _ = detector(top, np.random.default_rng(120 + h))
P = track(D, max_age=10) # the overhead pipeline chosen in step 3
s = {"hour": 9 + h, "entries": count_band(P)[0], "exits": count_band(P)[1], "desk_seconds": desk_visits(P)}
occ = (await client.post("/summaries", json=s)).json()["occupancy"]
si, so = count_band(track(detector(view(people, "side"), np.random.default_rng(120 + h))[0]))
side_occ += si - so
visits["true"] += desk_visits({pid: [(t, (bx[0] + bx[2]) / 2) for t, objs in enumerate(top) for q, bx in objs if q == pid] for pid, *_ in people})
visits["max_age 10"] += s["desk_seconds"]; visits["max_age 3"] += desk_visits(track(D, max_age=3))
print(f"{9 + h:2d}:00 {a:2d} / {b:2d} {s['entries']:2d} / {s['exits']:2d} {len(s['desk_seconds']):2d} {true_occ:3d} {occ:3d} {side_occ:3d}")
for k, v in visits.items():
print(f"desk visits, {k:10s}: {len(v)}, median {np.median(v):.1f} s")
print("report 14:00:", (await client.get("/report", params={"hour": 14})).json())
print("report day :", (await client.get("/report")).json())
r = await client.post("/summaries", json={**s, "track_ids": [4, 7]})
print("summary with track ids ->", r.status_code, r.json()["detail"][0]["type"])
asyncio.run(main())hour true in/out sent in/out desk visits occupancy: true service side camera
9:00 15 / 0 15 / 0 8 15 15 11
10:00 20 / 4 20 / 4 8 31 31 23
11:00 19 / 8 18 / 8 10 42 41 28
12:00 10 / 12 10 / 11 5 40 40 28
13:00 14 / 10 14 / 10 6 44 44 30
14:00 5 / 12 5 / 12 2 37 37 24
15:00 6 / 19 6 / 19 1 24 24 10
16:00 0 / 13 0 / 13 0 11 11 -3
desk visits, true : 42, median 7.1 s
desk visits, max_age 10: 40, median 7.2 s
desk visits, max_age 3 : 40, median 6.8 s
report 14:00: {'entries': 5, 'exits': 12, 'desk_visits': 2, 'desk_median_s': 'suppressed (< 5 visits)'}
report day : {'entries': 88, 'exits': 77, 'desk_visits': 40, 'desk_median_s': 7.2}
summary with track ids -> 422 extra_forbidden
The service's occupancy is never more than 1 person off (41 for 42 at 11:00, from one missed entry) and the peak of 44 at 13:00 is reported exactly, so the occupancy target is met. The side camera, which looked only "a bit low" on single minutes, reports 30 at the 13:00 peak, 14 people too few, and ends the day at , an impossible number. A count that is too low is the dangerous direction for a capacity limit: the library would let people in while it is already full. Missed entries and missed exits do not cancel; they accumulate, like a random walk with a drift. Note that the service clamps the occupancy at 0, which would hide such a drift: in production also log the raw sum, and reset to 0 at closing time.
The desk target is met as well: 40 visits with a median of 7.2 s against 42 true visits with 7.1 s. Two visits are missing; a missed first or last frame can push a visit that is close to the 3-second minimum below it, and two people standing together at the desk can be suppressed to one box. With 3 frames of coasting the median drops to 6.8 s, because breaks in a track at the desk shorten the visits. The effect is small here, but its direction is general: track fragmentation biases dwell times down, and identity switches can merge two people into one long visit.
The two reports show what the library sees: for 14:00, 5 entries, 12 exits and 2 desk visits whose median is withheld; for the day, 88 entries, 77 exits and a desk median of 7.2 s over 40 visits. The last request shows the privacy contract at work: a summary with track_ids never reaches the store. What stays on the device is deleted once the minute is summarised; what the server holds cannot be traced back to a person.
Extensions
- Hand-counted pilot. Count a few busy hours by hand (or from a recording, under the same privacy rules) and compare; real counters are judged by this, and it reveals children, prams and groups the simulator does not have.
- A library tracker. Ultralytics has ByteTrack and BoT-SORT built in (
model.track(source, tracker="bytetrack.yaml", persist=True)); it needs thelappackage, which the course's Docker image does not have. Compare it with the compact tracker on the same events, not on MOTA (object tracking, beyond SORT). - Several doors. Sum entries and exits over all doors of the building; a person who enters by one door and leaves by another needs no re-identification for occupancy (for that, see project 12, and why it is a much bigger privacy step).
- Monitoring. The share of tracks that start or end in the middle of the frame is a cheap health signal: when it rises, the camera has moved or the light has changed (monitoring ML systems, edge deployment).
- Latency. At 10 fps the device has 100 ms per frame for detection and tracking; measure it as in the video analytics project.
Write-up template
Problem and users: who needs which number (entries, occupancy, waiting time), how often
Success criteria (fixed before results): metric, target, measured on
Detector characterisation: model, camera height, person size in pixels, miss rate, overlap behaviour
Data: real or simulated, clips, development / test / pilot split, what the simulator does not cover
Counting rule and parameters: chosen on development clips only; why
Results on the test clips (once): in/out error, normal and busy
Pilot: occupancy error per hour, dwell median, hand counts
Privacy: lawful basis, signage, DPIA, what leaves the device, retention, who can see what
Limitations and monitoring: groups, children, light, camera moved; reset policyPractice
- In step 2, why does the band rule on the true paths matter, even though the truth is known from the scripts anyway?
Answer
It tests the rule separately from the detector and the tracker. If the rule were wrong on perfect paths (for example the "once per track" rule, which counts a loiterer as an entry), no amount of tracking would fix the counts. Because the band rule reproduces the truth exactly, the remaining errors must come from detection and tracking, which is where step 3 looks.
- The library asks for an alarm when occupancy exceeds 40. With the side camera, which way is the error, and what would you tell them?
Answer
Too low: hidden companions are missed on the way in (and out), and the running sum loses them for good; on the pilot day the peak of 44 was reported as 30. The alarm would fire late or never. Either move the camera overhead, or, if that is impossible, do not use the counter for safety, only for trends, and say so in the write-up.
- Change step 3 so that the band width is chosen by the test clips instead of the development clips. Why is the reported 3.1 % then no longer an honest estimate?
Answer
The test clips would have been used to pick the setting, so the reported error is the best of several tries on the same data and is optimistic (data leakage). Choose on development clips, test once.
- Make the desk harder: run step 4 with
p_desk=0.6in the detector and comparemax_age3 and 10. What happens to the number and the median of the desk visits?
Answer
With most desk frames missed, short coasting breaks each visit into several tracks: the number of visits changes (fragments shorter than 3 s disappear, long ones split) and the median falls. A longer max_age bridges the gaps. Run it to get the numbers; the direction, dwell biased down by fragmentation, is the point.
Test yourself
On the true paths, which counting rule reproduces the true entries and exits, loiterers included?
- Every change of side counts
- Only the first crossing of each track
- Hysteresis: a side change needs the centre more than 30 px past the line
- None of them
Why did the side camera under-count, whatever the tracker settings?
- The band was too wide
- People hidden behind someone nearer the camera, often their companion, are never detected near the line, and the tracker cannot count what it never sees
- The detector produced too many false boxes
- The frame rate was too low
The overhead counter was tested once on six test clips. What was its error, and does it meet the target?
- 0 %, so the problem is solved for real doors
- 3.1 % (7 of 229 crossings), within the 5 % target on this generator
- 24.5 %, so it fails
- 3.1 %, but the target was 1 %
Why is under-counting entries dangerous for an occupancy limit, even if it is only a few per hour?
- It is not dangerous, because errors cancel
- Occupancy is a running sum, so every missed entry stays in it until the next reset and the reported number is too low
- Because the service clamps at zero
- Because dwell times get longer
How does the service in step 4 make sure no personal data reaches the server?
- It encrypts the track ids
- The device sends only counts and durations, and the request model forbids extra fields, so a payload with track ids is rejected with 422; dwell statistics from fewer than 5 visits are suppressed
- It deletes the database every hour
- It blurs the faces in the frames it receives