Project 3: Vehicle Detection
A city traffic department has a fixed camera above a three-lane road and wants two numbers: where the vehicles are in every frame (for a later speed and queue analysis), and how many vehicles pass per lane and direction. In this project you build that system without any deep learning, with background subtraction and blob analysis from video and motion, evaluate it honestly with detection metrics, find out why it fails with an error analysis, fix it, confirm the fix on a video you did not tune on, and finally see what a pretrained YOLO detector does with a real vehicle photo and with the synthetic road.
Goal and success criteria
Decide what "good" means before writing code, and write it down:
| Requirement | Metric | Target |
|---|---|---|
| Vehicles found in each frame | recall at IoU 0.5, all frames after warm-up | at least 0.95 |
| Few false alarms | precision at IoU 0.5 | at least 0.95 |
| Ranking quality of the scores | AP@0.5 (detection metrics) | report it |
| Counts per lane and direction | absolute count error over the clip | 0 |
| Cost | runs in real time on one CPU core | no GPU |
A fixed camera makes background subtraction a serious candidate: it needs no labelled training data at all, which is its biggest advantage. Labels are needed only to evaluate.
The data
make_traffic is this project's variant of the course's make_video: 80 frames of a 160 x 90 road with sensor noise and a lighting gradient across the image, three lanes at fixed heights (lanes 0 and 2 drive to the right, lane 1 to the left), and vehicles that enter at random times. Within a lane all vehicles travel at about the lane's speed (), as real traffic does, so a faster vehicle may close up on a slower one. Ground truth is a box, a vehicle id and a lane for every vehicle in every frame. The first 30 frames serve as warm-up for the background models and are never scored; scoring uses frames 30 to 79.
Two seeds give two independent videos: seed 0 is the development video on which every decision is made, seed 1 is the held-out test video, used once at the end. This is the video version of a train/test split (split strategies): tuning thresholds on the clip you report would make the numbers optimistic.
Step 1: baselines
Three background models, all with the same blob detector: threshold the absolute difference at 30 grey levels (five noise standard deviations), clean the mask with an opening and a closing, keep connected components of at least 30 pixels as boxes, and give each box a score, the mean absolute difference inside the blob (a strong contrast is more likely a vehicle). Matching and AP follow the detection-metrics lesson: per frame, highest score first, IoU at least 0.5, each vehicle matched once.
import numpy as np, cv2
cv2.setLogLevel(0)
def make_traffic(rng, n_frames=80, h=90, w=160):
"""Project variant of make_video: three lanes (y = 12, 40, 68), lanes 0 and 2 drive right, lane 1 left;
vehicles enter at random times with their own speed, so a faster vehicle can catch up with a slower one.
Returns frames (T, h, w) uint8, gt per frame: list of (vehicle_id, lane, [x1, y1, x2, y2])."""
lanes = [(12, 1), (40, -1), (68, 1)]
vehicles = []
for lane, (ly, d) in enumerate(lanes):
v_lane = float(rng.uniform(2.0, 3.5)) # traffic in a lane flows at about one speed
t0 = -int(rng.integers(0, 20))
while t0 < n_frames:
bw, bh = int(rng.integers(14, 24)), int(rng.integers(8, 12))
v = v_lane * float(rng.uniform(0.85, 1.15))
vehicles.append(dict(lane=lane, t0=t0, x0=-bw if d > 0 else w, y=ly + int(rng.integers(-2, 3)),
bw=bw, bh=bh, v=d * v, g=int(rng.integers(150, 250))))
t0 += int(rng.integers(8, 30))
frames, gt = [], []
for t in range(n_frames):
f = rng.normal(60, 6, (h, w))
f[:, :] += np.linspace(-8, 8, w)[None, :] # uneven lighting across the road
boxes = []
for k, c in enumerate(vehicles):
x1 = int(round(c["x0"] + c["v"] * (t - c["t0"])))
if t < c["t0"] or x1 + c["bw"] <= 0 or x1 >= w:
continue
y1 = c["y"]
f[y1:y1 + c["bh"], max(x1, 0):x1 + c["bw"]] = c["g"]
boxes.append((k, c["lane"], [max(x1, 0), y1, min(x1 + c["bw"], w), y1 + c["bh"]]))
frames.append(f.clip(0, 255).astype(np.uint8)); gt.append(boxes)
return np.array(frames), gt
def blob_detector(fg, diff, min_area=30):
"""Foreground mask -> boxes [x1, y1, x2, y2] with a score = mean |frame - background| inside the blob."""
m = cv2.morphologyEx(fg.astype(np.uint8), cv2.MORPH_OPEN, np.ones((3, 3), np.uint8))
m = cv2.morphologyEx(m, cv2.MORPH_CLOSE, np.ones((5, 5), np.uint8))
n, lab, stats, _ = cv2.connectedComponentsWithStats(m)
out = []
for k in range(1, n):
x, y, w, h, a = stats[k]
if a >= min_area:
out.append(([int(x), int(y), int(x + w), int(y + h)], float(diff[lab == k].mean())))
return out
def iou(a, b):
ix = max(0, min(a[2], b[2]) - max(a[0], b[0])); iy = max(0, min(a[3], b[3]) - max(a[1], b[1]))
inter = ix * iy
return inter / ((a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter)
def evaluate(dets, gt, frames_used, thr=0.5):
"""Per-frame matching (highest score first), then precision, recall and VOC-style AP over all frames."""
records, n_gt = [], 0
for t in frames_used:
g = [b for _, _, b in gt[t]]; n_gt += len(g); used = set()
for box, s in sorted(dets[t], key=lambda d: -d[1]):
j = max(range(len(g)), key=lambda j: iou(box, g[j]), default=None)
hit = j is not None and j not in used and iou(box, g[j]) >= thr
if hit:
used.add(j)
records.append((s, hit))
records.sort(key=lambda r: -r[0])
tp = np.cumsum([h for _, h in records]); k = np.arange(1, len(records) + 1)
prec, rec = tp / k, tp / n_gt
env = np.maximum.accumulate(prec[::-1])[::-1]
ap = float(np.sum(np.diff(np.r_[0, rec]) * env))
return int(tp[-1]), len(records) - int(tp[-1]), n_gt - int(tp[-1]), ap
frames, gt = make_traffic(np.random.default_rng(0))
T = len(frames); F = frames.astype(np.float32)
print(f"video {frames.shape}, {len({k for g in gt for k, _, _ in g})} vehicles, {sum(len(g) for g in gt)} vehicle boxes")
print("frame 40 truth:", [(k, lane, b) for k, lane, b in gt[40]])
detectors = {"frame difference": [[]], "MOG2 rate 0.01": [], "median of last 30": []}
mog = cv2.createBackgroundSubtractorMOG2(history=30, varThreshold=16, detectShadows=False)
for t in range(T):
if t:
D = np.abs(F[t] - F[t - 1])
detectors["frame difference"].append(blob_detector(D > 30, D))
fg = mog.apply(frames[t], learningRate=0.01) > 0
detectors["MOG2 rate 0.01"].append(blob_detector(fg, np.abs(F[t] - mog.getBackgroundImage())))
B = np.median(F[max(0, t - 30):t], axis=0) if t else F[0]
detectors["median of last 30"].append(blob_detector(np.abs(F[t] - B) > 30, np.abs(F[t] - B)))
print("scored on frames 30-79 (the first 30 frames are the background models' warm-up)")
for name, dets in detectors.items():
tp, fp, fn, ap = evaluate(dets, gt, range(30, T))
print(f"{name:18s} TP {tp:3d} FP {fp:3d} FN {fn:3d} precision {tp / (tp + fp):.3f} recall {tp / (tp + fn):.3f} AP@0.5 {ap:.3f}")video (80, 90, 160), 15 vehicles, 603 vehicle boxes
frame 40 truth: [(0, 0, [110, 10, 126, 19]), (1, 0, [56, 14, 76, 25]), (2, 0, [0, 14, 13, 24]), (5, 1, [27, 38, 41, 46]), (6, 1, [94, 40, 110, 50]), (7, 1, [157, 41, 160, 50]), (9, 2, [120, 66, 138, 75]), (10, 2, [55, 68, 72, 78]), (11, 2, [5, 67, 24, 76])]
scored on frames 30-79 (the first 30 frames are the background models' warm-up)
frame difference TP 5 FP 299 FN 459 precision 0.016 recall 0.011 AP@0.5 0.000
MOG2 rate 0.01 TP 333 FP 74 FN 131 precision 0.818 recall 0.718 AP@0.5 0.610
median of last 30 TP 433 FP 21 FN 31 precision 0.954 recall 0.933 AP@0.5 0.929
Frame differencing is useless here (precision 0.016): uniform vehicles produce only their leading and trailing edges, the failure explained in the video lesson. MOG2 at a learning rate of 0.01 finds 72 % of the vehicles with many false alarms (AP 0.610). The median of the last 30 frames as background is far better: precision 0.954, recall 0.933, AP 0.929. It is the baseline to improve. It still misses both targets of 0.95 on recall, so the next step is to look at its errors one by one.
Step 2: error analysis
Aggregate metrics say how much is wrong; an error analysis says what. Sort every false negative and false positive into a few categories that point to different fixes, and count them (error analysis).
import numpy as np, cv2
cv2.setLogLevel(0)
def make_traffic(rng, n_frames=80, h=90, w=160):
"""Project variant of make_video: three lanes (y = 12, 40, 68), lanes 0 and 2 drive right, lane 1 left;
vehicles enter at random times with their own speed, so a faster vehicle can catch up with a slower one.
Returns frames (T, h, w) uint8, gt per frame: list of (vehicle_id, lane, [x1, y1, x2, y2])."""
lanes = [(12, 1), (40, -1), (68, 1)]
vehicles = []
for lane, (ly, d) in enumerate(lanes):
v_lane = float(rng.uniform(2.0, 3.5)) # traffic in a lane flows at about one speed
t0 = -int(rng.integers(0, 20))
while t0 < n_frames:
bw, bh = int(rng.integers(14, 24)), int(rng.integers(8, 12))
v = v_lane * float(rng.uniform(0.85, 1.15))
vehicles.append(dict(lane=lane, t0=t0, x0=-bw if d > 0 else w, y=ly + int(rng.integers(-2, 3)),
bw=bw, bh=bh, v=d * v, g=int(rng.integers(150, 250))))
t0 += int(rng.integers(8, 30))
frames, gt = [], []
for t in range(n_frames):
f = rng.normal(60, 6, (h, w))
f[:, :] += np.linspace(-8, 8, w)[None, :] # uneven lighting across the road
boxes = []
for k, c in enumerate(vehicles):
x1 = int(round(c["x0"] + c["v"] * (t - c["t0"])))
if t < c["t0"] or x1 + c["bw"] <= 0 or x1 >= w:
continue
y1 = c["y"]
f[y1:y1 + c["bh"], max(x1, 0):x1 + c["bw"]] = c["g"]
boxes.append((k, c["lane"], [max(x1, 0), y1, min(x1 + c["bw"], w), y1 + c["bh"]]))
frames.append(f.clip(0, 255).astype(np.uint8)); gt.append(boxes)
return np.array(frames), gt
def blob_detector(fg, diff, min_area=30):
"""Foreground mask -> boxes [x1, y1, x2, y2] with a score = mean |frame - background| inside the blob."""
m = cv2.morphologyEx(fg.astype(np.uint8), cv2.MORPH_OPEN, np.ones((3, 3), np.uint8))
m = cv2.morphologyEx(m, cv2.MORPH_CLOSE, np.ones((5, 5), np.uint8))
n, lab, stats, _ = cv2.connectedComponentsWithStats(m)
out = []
for k in range(1, n):
x, y, w, h, a = stats[k]
if a >= min_area:
out.append(([int(x), int(y), int(x + w), int(y + h)], float(diff[lab == k].mean())))
return out
def iou(a, b):
ix = max(0, min(a[2], b[2]) - max(a[0], b[0])); iy = max(0, min(a[3], b[3]) - max(a[1], b[1]))
inter = ix * iy
return inter / ((a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter)
def evaluate(dets, gt, frames_used, thr=0.5):
"""Per-frame matching (highest score first), then precision, recall and VOC-style AP over all frames."""
records, n_gt = [], 0
for t in frames_used:
g = [b for _, _, b in gt[t]]; n_gt += len(g); used = set()
for box, s in sorted(dets[t], key=lambda d: -d[1]):
j = max(range(len(g)), key=lambda j: iou(box, g[j]), default=None)
hit = j is not None and j not in used and iou(box, g[j]) >= thr
if hit:
used.add(j)
records.append((s, hit))
records.sort(key=lambda r: -r[0])
tp = np.cumsum([h for _, h in records]); k = np.arange(1, len(records) + 1)
prec, rec = tp / k, tp / n_gt
env = np.maximum.accumulate(prec[::-1])[::-1]
ap = float(np.sum(np.diff(np.r_[0, rec]) * env))
return int(tp[-1]), len(records) - int(tp[-1]), n_gt - int(tp[-1]), ap
frames, gt = make_traffic(np.random.default_rng(0))
T = len(frames); F = frames.astype(np.float32)
dets = []
for t in range(T): # the "median of last 30" detector
B = np.median(F[max(0, t - 30):t], axis=0) if t else F[0]
dets.append(blob_detector(np.abs(F[t] - B) > 30, np.abs(F[t] - B)))
errors, examples = {}, {}
def note(kind, t, info):
errors[kind] = errors.get(kind, 0) + 1
examples.setdefault(kind, (t, info))
for t in range(30, T):
g = [b for _, _, b in gt[t]]
boxes = [d for d, _ in dets[t]]
for b in g: # false negatives
best = max([iou(d, b) for d in boxes], default=0.0)
if best >= 0.5:
continue
if any(iou(d, b) > 0 and sum(iou(d, b2) > 0 for b2 in g) > 1 for d in boxes):
note("FN: merged with another vehicle", t, b)
elif b[0] == 0 or b[2] == frames.shape[2]:
note("FN: cut by the frame border", t, b)
elif best > 0:
note("FN: box found but too loose (IoU < 0.5)", t, (b, [d for d in boxes if iou(d, b) > 0][0]))
else:
note("FN: not found at all", t, b)
for d in boxes: # false positives
ious = [iou(d, b) for b in g]
if max(ious, default=0.0) >= 0.5:
continue
note("FP: overlaps a vehicle (loose or merged box)" if max(ious, default=0.0) > 0 else "FP: no vehicle (ghost or noise)", t, d)
for kind, n in sorted(errors.items()):
print(f"{n:3d} {kind:45s} first at frame {examples[kind][0]}: {examples[kind][1]}") 21 FN: box found but too loose (IoU < 0.5) first at frame 59: ([19, 69, 35, 79], [0, 69, 35, 79])
9 FN: cut by the frame border first at frame 31: [0, 67, 2, 76]
1 FN: merged with another vehicle first at frame 79: [0, 67, 2, 77]
21 FP: overlaps a vehicle (loose or merged box) first at frame 59: [0, 69, 35, 79]
One category dominates. From frame 59 on, the detector finds a vehicle in lane 2 but its box is far too long, [0, 69, 35, 79] for a vehicle at [19, 69, 35, 79]: the extra 19 pixels behind the vehicle are flagged as foreground. Each such frame costs one false negative and one false positive (21 of each). The cause is the background model: in a dense lane, a pixel near the left edge was covered by vehicles in more than half of the last 30 frames, so the median there is a vehicle, and the empty road now looks like an object. The other errors are expected and mostly harmless: 9 vehicles cut by the frame border into slivers below the 30-pixel minimum area (entering or leaving), and 1 more such sliver merged with a neighbour.
That diagnosis suggests two fixes: a longer median window, so that no pixel is covered more than half the time, or a selective update: start from a median, then update the background (a running average) only where no vehicle is found, so traffic never leaks into it.
Step 3: the improved detector, then the test video
import numpy as np, cv2
cv2.setLogLevel(0)
def make_traffic(rng, n_frames=80, h=90, w=160):
"""Project variant of make_video: three lanes (y = 12, 40, 68), lanes 0 and 2 drive right, lane 1 left;
vehicles enter at random times with their own speed, so a faster vehicle can catch up with a slower one.
Returns frames (T, h, w) uint8, gt per frame: list of (vehicle_id, lane, [x1, y1, x2, y2])."""
lanes = [(12, 1), (40, -1), (68, 1)]
vehicles = []
for lane, (ly, d) in enumerate(lanes):
v_lane = float(rng.uniform(2.0, 3.5)) # traffic in a lane flows at about one speed
t0 = -int(rng.integers(0, 20))
while t0 < n_frames:
bw, bh = int(rng.integers(14, 24)), int(rng.integers(8, 12))
v = v_lane * float(rng.uniform(0.85, 1.15))
vehicles.append(dict(lane=lane, t0=t0, x0=-bw if d > 0 else w, y=ly + int(rng.integers(-2, 3)),
bw=bw, bh=bh, v=d * v, g=int(rng.integers(150, 250))))
t0 += int(rng.integers(8, 30))
frames, gt = [], []
for t in range(n_frames):
f = rng.normal(60, 6, (h, w))
f[:, :] += np.linspace(-8, 8, w)[None, :] # uneven lighting across the road
boxes = []
for k, c in enumerate(vehicles):
x1 = int(round(c["x0"] + c["v"] * (t - c["t0"])))
if t < c["t0"] or x1 + c["bw"] <= 0 or x1 >= w:
continue
y1 = c["y"]
f[y1:y1 + c["bh"], max(x1, 0):x1 + c["bw"]] = c["g"]
boxes.append((k, c["lane"], [max(x1, 0), y1, min(x1 + c["bw"], w), y1 + c["bh"]]))
frames.append(f.clip(0, 255).astype(np.uint8)); gt.append(boxes)
return np.array(frames), gt
def blob_detector(fg, diff, min_area=30):
"""Foreground mask -> boxes [x1, y1, x2, y2] with a score = mean |frame - background| inside the blob."""
m = cv2.morphologyEx(fg.astype(np.uint8), cv2.MORPH_OPEN, np.ones((3, 3), np.uint8))
m = cv2.morphologyEx(m, cv2.MORPH_CLOSE, np.ones((5, 5), np.uint8))
n, lab, stats, _ = cv2.connectedComponentsWithStats(m)
out = []
for k in range(1, n):
x, y, w, h, a = stats[k]
if a >= min_area:
out.append(([int(x), int(y), int(x + w), int(y + h)], float(diff[lab == k].mean())))
return out
def iou(a, b):
ix = max(0, min(a[2], b[2]) - max(a[0], b[0])); iy = max(0, min(a[3], b[3]) - max(a[1], b[1]))
inter = ix * iy
return inter / ((a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter)
def evaluate(dets, gt, frames_used, thr=0.5):
"""Per-frame matching (highest score first), then precision, recall and VOC-style AP over all frames."""
records, n_gt = [], 0
for t in frames_used:
g = [b for _, _, b in gt[t]]; n_gt += len(g); used = set()
for box, s in sorted(dets[t], key=lambda d: -d[1]):
j = max(range(len(g)), key=lambda j: iou(box, g[j]), default=None)
hit = j is not None and j not in used and iou(box, g[j]) >= thr
if hit:
used.add(j)
records.append((s, hit))
records.sort(key=lambda r: -r[0])
tp = np.cumsum([h for _, h in records]); k = np.arange(1, len(records) + 1)
prec, rec = tp / k, tp / n_gt
env = np.maximum.accumulate(prec[::-1])[::-1]
ap = float(np.sum(np.diff(np.r_[0, rec]) * env))
return int(tp[-1]), len(records) - int(tp[-1]), n_gt - int(tp[-1]), ap
def selective_detections(frames, warmup=30, alpha=0.1, tau=30):
"""Background = median of the first `warmup` frames, then a running average updated only
where no vehicle was found (dilated foreground), so passing traffic never leaks into it."""
F = frames.astype(np.float32)
B = np.median(F[:warmup], axis=0)
dets = [[] for _ in range(warmup)]
for t in range(warmup, len(F)):
D = np.abs(F[t] - B); fg = D > tau
dets.append(blob_detector(fg, D))
near_fg = cv2.dilate(fg.astype(np.uint8), np.ones((7, 7), np.uint8)) > 0
B = np.where(near_fg, B, (1 - alpha) * B + alpha * F[t])
return dets
for seed, role in [(0, "development video"), (1, "held-out test video")]:
frames, gt = make_traffic(np.random.default_rng(seed))
T = len(frames); F = frames.astype(np.float32)
results = {}
for win in [30, 60]:
dets = []
for t in range(T):
B = np.median(F[max(0, t - win):t], axis=0) if t else F[0]
dets.append(blob_detector(np.abs(F[t] - B) > 30, np.abs(F[t] - B)))
results[f"median of last {win}"] = dets
results["selective update"] = selective_detections(frames)
print(f"seed {seed} ({role}), frames 30-79:")
for name, dets in results.items():
tp, fp, fn, ap = evaluate(dets, gt, range(30, T))
print(f" {name:18s} TP {tp:3d} FP {fp:2d} FN {fn:2d} precision {tp / (tp + fp):.3f} recall {tp / (tp + fn):.3f} AP@0.5 {ap:.3f}")seed 0 (development video), frames 30-79:
median of last 30 TP 433 FP 21 FN 31 precision 0.954 recall 0.933 AP@0.5 0.929
median of last 60 TP 454 FP 0 FN 10 precision 1.000 recall 0.978 AP@0.5 0.978
selective update TP 454 FP 0 FN 10 precision 1.000 recall 0.978 AP@0.5 0.978
seed 1 (held-out test video), frames 30-79:
median of last 30 TP 409 FP 13 FN 21 precision 0.969 recall 0.951 AP@0.5 0.943
median of last 60 TP 421 FP 0 FN 9 precision 1.000 recall 0.979 AP@0.5 0.979
selective update TP 421 FP 0 FN 9 precision 1.000 recall 0.979 AP@0.5 0.979
On the development video both fixes remove every false positive and leave only the 10 border slivers as misses: precision 1.000, recall 0.978, AP 0.978. On the held-out video, scored once, the numbers hold: precision 1.000, recall 0.979, AP 0.979 with either fix, against 0.943 AP for the 30-frame median. Both requirements of 0.95 are met on data that played no part in the decisions.
Which fix to deploy? They tie on these clips, but they fail differently. A 60-frame median still breaks when a queue stands still for more than 30 frames (1 second at 30 fps); the selective update keeps a stopped vehicle as foreground forever, which is right for a queue but wrong for a car that parks for the day (it should become background eventually). Real systems combine the two with a slow forgetting rate, and in practice they also reset after camera shake and lighting changes.
Step 4: counting vehicles per lane
Counting needs a little tracking: the same vehicle appears in 30 or more frames and must be counted once. A virtual counting line at does it with the simplest possible association: link each detection to the nearest detection of the previous frame in the same lane (centres less than 8 pixels apart, about three frames of motion), and count a vehicle when a link crosses the line, by direction. The lane of a box is the band its centre lies in. Ground-truth counts come from the true boxes with the same rule.
import numpy as np, cv2
cv2.setLogLevel(0)
def make_traffic(rng, n_frames=80, h=90, w=160):
"""Project variant of make_video: three lanes (y = 12, 40, 68), lanes 0 and 2 drive right, lane 1 left;
vehicles enter at random times with their own speed, so a faster vehicle can catch up with a slower one.
Returns frames (T, h, w) uint8, gt per frame: list of (vehicle_id, lane, [x1, y1, x2, y2])."""
lanes = [(12, 1), (40, -1), (68, 1)]
vehicles = []
for lane, (ly, d) in enumerate(lanes):
v_lane = float(rng.uniform(2.0, 3.5)) # traffic in a lane flows at about one speed
t0 = -int(rng.integers(0, 20))
while t0 < n_frames:
bw, bh = int(rng.integers(14, 24)), int(rng.integers(8, 12))
v = v_lane * float(rng.uniform(0.85, 1.15))
vehicles.append(dict(lane=lane, t0=t0, x0=-bw if d > 0 else w, y=ly + int(rng.integers(-2, 3)),
bw=bw, bh=bh, v=d * v, g=int(rng.integers(150, 250))))
t0 += int(rng.integers(8, 30))
frames, gt = [], []
for t in range(n_frames):
f = rng.normal(60, 6, (h, w))
f[:, :] += np.linspace(-8, 8, w)[None, :] # uneven lighting across the road
boxes = []
for k, c in enumerate(vehicles):
x1 = int(round(c["x0"] + c["v"] * (t - c["t0"])))
if t < c["t0"] or x1 + c["bw"] <= 0 or x1 >= w:
continue
y1 = c["y"]
f[y1:y1 + c["bh"], max(x1, 0):x1 + c["bw"]] = c["g"]
boxes.append((k, c["lane"], [max(x1, 0), y1, min(x1 + c["bw"], w), y1 + c["bh"]]))
frames.append(f.clip(0, 255).astype(np.uint8)); gt.append(boxes)
return np.array(frames), gt
def blob_detector(fg, diff, min_area=30):
"""Foreground mask -> boxes [x1, y1, x2, y2] with a score = mean |frame - background| inside the blob."""
m = cv2.morphologyEx(fg.astype(np.uint8), cv2.MORPH_OPEN, np.ones((3, 3), np.uint8))
m = cv2.morphologyEx(m, cv2.MORPH_CLOSE, np.ones((5, 5), np.uint8))
n, lab, stats, _ = cv2.connectedComponentsWithStats(m)
out = []
for k in range(1, n):
x, y, w, h, a = stats[k]
if a >= min_area:
out.append(([int(x), int(y), int(x + w), int(y + h)], float(diff[lab == k].mean())))
return out
def iou(a, b):
ix = max(0, min(a[2], b[2]) - max(a[0], b[0])); iy = max(0, min(a[3], b[3]) - max(a[1], b[1]))
inter = ix * iy
return inter / ((a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter)
def evaluate(dets, gt, frames_used, thr=0.5):
"""Per-frame matching (highest score first), then precision, recall and VOC-style AP over all frames."""
records, n_gt = [], 0
for t in frames_used:
g = [b for _, _, b in gt[t]]; n_gt += len(g); used = set()
for box, s in sorted(dets[t], key=lambda d: -d[1]):
j = max(range(len(g)), key=lambda j: iou(box, g[j]), default=None)
hit = j is not None and j not in used and iou(box, g[j]) >= thr
if hit:
used.add(j)
records.append((s, hit))
records.sort(key=lambda r: -r[0])
tp = np.cumsum([h for _, h in records]); k = np.arange(1, len(records) + 1)
prec, rec = tp / k, tp / n_gt
env = np.maximum.accumulate(prec[::-1])[::-1]
ap = float(np.sum(np.diff(np.r_[0, rec]) * env))
return int(tp[-1]), len(records) - int(tp[-1]), n_gt - int(tp[-1]), ap
def selective_detections(frames, warmup=30, alpha=0.1, tau=30):
"""Background = median of the first `warmup` frames, then a running average updated only
where no vehicle was found (dilated foreground), so passing traffic never leaks into it."""
F = frames.astype(np.float32)
B = np.median(F[:warmup], axis=0)
dets = [[] for _ in range(warmup)]
for t in range(warmup, len(F)):
D = np.abs(F[t] - B); fg = D > tau
dets.append(blob_detector(fg, D))
near_fg = cv2.dilate(fg.astype(np.uint8), np.ones((7, 7), np.uint8)) > 0
B = np.where(near_fg, B, (1 - alpha) * B + alpha * F[t])
return dets
LANES = [(0, 30), (30, 58), (58, 90)] # y ranges of the three lanes
LINE = 80 # virtual counting line at x = 80
def lane_of(box):
cy = (box[1] + box[3]) / 2
return next(i for i, (a, b) in enumerate(LANES) if a <= cy < b)
def count_crossings(dets, start, max_jump=8):
"""Link each detection to the nearest detection of the previous frame in the same lane
(centre distance < max_jump px), and count links whose centres cross the line."""
counts = [[0, 0] for _ in LANES] # per lane: [left to right, right to left]
prev = []
for t in range(start, len(dets)):
cur = [((b[0] + b[2]) / 2, lane_of(b)) for b, _ in dets[t]]
for cx, lane in cur:
cands = [px for px, pl in prev if pl == lane and abs(px - cx) < max_jump]
if cands:
px = min(cands, key=lambda p: abs(p - cx))
if px < LINE <= cx: counts[lane][0] += 1
if cx < LINE <= px: counts[lane][1] += 1
prev = cur
return counts
def true_crossings(gt, start):
counts = [[0, 0] for _ in LANES]
for t in range(start + 1, len(gt)):
before = {k: (b[0] + b[2]) / 2 for k, _, b in gt[t - 1]}
for k, lane, b in gt[t]:
cx = (b[0] + b[2]) / 2
if k in before:
if before[k] < LINE <= cx: counts[lane][0] += 1
if cx < LINE <= before[k]: counts[lane][1] += 1
return counts
frames, gt = make_traffic(np.random.default_rng(1)) # the held-out video
dets = selective_detections(frames)
found, true = count_crossings(dets, 30), true_crossings(gt, 30)
for lane in range(3):
print(f"lane {lane}: counted {found[lane][0]} left-to-right, {found[lane][1]} right-to-left | truth {true[lane][0]}, {true[lane][1]}")
print("total counted:", sum(map(sum, found)), "| true:", sum(map(sum, true)))lane 0: counted 2 left-to-right, 0 right-to-left | truth 2, 0
lane 1: counted 0 left-to-right, 2 right-to-left | truth 0, 2
lane 2: counted 2 left-to-right, 0 right-to-left | truth 2, 0
total counted: 6 | true: 6
On the held-out video every count is right: two vehicles to the right in lanes 0 and 2, two to the left in lane 1. Nearest-neighbour linking works here because vehicles in one lane are well separated and each crossing is seen in consecutive frames. When detections drop out near the line or vehicles cross the line side by side, the counter needs a real tracker with memory (object tracking, Project 5), and production counters usually count a track once when its whole trajectory has crossed, not a single link.
Step 5: what a pretrained detector sees
Background subtraction needs a fixed camera and knows nothing about vehicle types. A detector trained on COCO knows eight vehicle classes, six of them land vehicles (the code lists them; airplane and boat are the other two), and works from a moving camera. The cached YOLOv8n and YOLO11n models are run below on the two photographs of skimage.data.stereo_motorcycle() (a motorcycle in a garage, from the Middlebury stereo data set) and on a frame like this project's synthetic road:
import numpy as np, cv2
from ultralytics import YOLO
from skimage import data
cv2.setLogLevel(0)
def road_frame(rng, h=90, w=160):
"""One frame in the style of make_traffic: noisy grey road, uneven light, three bright vehicles."""
f = rng.normal(60, 6, (h, w)) + np.linspace(-8, 8, w)[None, :]
for y, x, bw, bh, g in [(12, 30, 20, 10, 200), (40, 90, 18, 9, 170), (68, 120, 22, 11, 240)]:
f[y:y + bh, x:x + bw] = g
return f.clip(0, 255).astype(np.uint8)
for name in ["yolov8n.pt", "yolo11n.pt"]:
model = YOLO(name)
left, right = data.stereo_motorcycle()[:2] # two RGB 741 x 500 photos of a motorcycle
for label, img in [("stereo left", left), ("stereo right", right)]:
r = model.predict(img[:, :, ::-1].copy(), conf=0.25, verbose=False)[0] # RGB -> BGR
print(name, label, [(r.names[int(c)], round(float(s), 2), [int(v) for v in b]) for c, s, b in zip(r.boxes.cls, r.boxes.conf, r.boxes.xyxy.tolist())])
synthetic = cv2.cvtColor(cv2.resize(road_frame(np.random.default_rng(0)), (640, 360), interpolation=cv2.INTER_NEAREST), cv2.COLOR_GRAY2BGR)
r = model.predict(synthetic, conf=0.05, verbose=False)[0]
print(name, "synthetic road, conf 0.05:", len(r.boxes), "boxes")
vehicles = {k: v for k, v in model.names.items() if v in ("bicycle", "car", "motorcycle", "bus", "train", "truck")}
print("COCO vehicle classes:", vehicles)yolov8n.pt stereo left [('motorcycle', 0.86, [108, 62, 678, 441])]
yolov8n.pt stereo right [('motorcycle', 0.84, [61, 64, 629, 441])]
yolov8n.pt synthetic road, conf 0.05: 0 boxes
yolo11n.pt stereo left [('motorcycle', 0.87, [104, 25, 690, 451]), ('bicycle', 0.27, [0, 126, 49, 230])]
yolo11n.pt stereo right [('motorcycle', 0.86, [59, 29, 630, 451])]
yolo11n.pt synthetic road, conf 0.05: 0 boxes
COCO vehicle classes: {1: 'bicycle', 2: 'car', 3: 'motorcycle', 5: 'bus', 6: 'train', 7: 'truck'}
On the photographs both models find the motorcycle with confidence around 0.85; YOLO11n also reports a low-score bicycle (0.27) at the left edge of the left image, and there really is part of a bicycle wheel there. On the synthetic road, even at a confidence threshold of 0.05, neither model reports anything: bright rectangles on grey are not vehicles in any sense COCO knows. This is the domain gap in its most extreme form. The two approaches are complementary: the background model needs no training data but only works for this camera; the detector would need fine-tuning on frames from this camera, with labels (transfer learning, Ultralytics YOLO), and in return handles stopped vehicles, camera shake and vehicle types.
Your turn
- Change the threshold
taufrom 30 to 15 in the selective detector and rerun step 3. Predict first: what happens to precision and recall, and why?
Hint and answer
The noise has a standard deviation of 6 grey levels, so a threshold of 15 is only 2.5 standard deviations: about 1 % of road pixels exceed it in every frame. Most of them are isolated pixels that the opening removes, but clusters survive more often, so expect some new false positives; recall cannot improve much because it is already limited by the border slivers. Measure it before believing the prediction, and evaluate on the development video, not the test video.
- The 9 or 10 remaining misses are slivers at the frame border. Should they count as errors? Propose an evaluation rule and a detector change.
Answer
Many benchmarks have "ignore" annotations: neither a miss if not found, nor a false positive if found (KITTI's DontCare regions, and its difficulty levels that leave heavily truncated objects out of the easier rankings; COCO's iscrowd regions work the same way for crowds; see annotation tasks). A rule such as "ignore boxes less than 5 pixels wide" is defensible if it is written down before testing and applied to every method. On the detector side, lowering min_area near the borders would find slivers but also admit noise; for counting it does not matter, since slivers never cross the middle line.
- Add a speed estimate per lane: the camera sees 0.2 m per pixel and runs at 25 fps. From the linked detections, compute the median speed per lane in km/h.
Hint
For each link, the displacement in pixels per frame converts to km/h. Take the median over all links in a lane (robust to a few bad links). Check it against the ground truth from consecutive true boxes of the same vehicle id.
- Make the task harder: add a slow camera shake (shift every frame by a random 0 to 2 pixels with
np.roll) and rerun steps 1 to 3. Which method breaks first, and how would you fix it?
Hint
Every background model breaks at strong edges (lane borders, vehicles), because a shifted frame differs from the background along every edge. A fix is to register each frame to the background first: estimate the shift by phase correlation (cv2.phaseCorrelate) or from tracked corners (video and motion), shift it back, then subtract.
Write-up template
| Section | Content |
|---|---|
| Task and success criteria | per-frame detection (P, R at IoU 0.5 0.95), counts per lane and direction |
| Data | generator, resolution, frames, lanes, seeds: development 0, test 1; warm-up frames excluded from scoring |
| Baseline | median of last 30 frames + blobs: P 0.954, R 0.933, AP 0.929 (development) |
| Error analysis | 21 loose boxes from a contaminated background in a dense lane; 10 border slivers |
| Improvement | selective background update (or 60-frame median) |
| Final result (test video, once) | P 1.000, R 0.979, AP 0.979; counts 6 of 6 correct |
| Limits | fixed camera only; synthetic vehicles; no stopped traffic, shadows, night, rain, camera shake |
| Next steps | fine-tuned detector on real frames, tracker for counting, ignore rule for truncated vehicles |
| Privacy | a traffic camera also films people and number plates: purpose limitation, retention, blurring (privacy, consent and licensing) |
Test yourself
The 30-frame median background produced boxes far longer than the vehicles in one dense lane. What was the cause?
- The threshold was too low
- In that lane some pixels were covered by vehicles in more than half of the last 30 frames, so the median background contained a vehicle and the empty road looked like foreground
- The opening removed too much
- The lighting gradient
Why are the thresholds tuned on the seed-0 video and the final numbers reported on the seed-1 video?
- Seed 1 is easier
- So that the reported numbers come from data that played no part in the design decisions, like a test set
- Because seed 0 has no ground truth
- To double the data
YOLOv8n found the motorcycle in the photograph but nothing on the synthetic road even at confidence 0.05. What does this show?
- YOLO is broken
- A domain gap: bright rectangles on grey are nothing like the COCO training images, so a pretrained detector needs fine-tuning on labelled frames from the target camera
- The confidence threshold was too high
- Grey images cannot be processed