Object Detection: Cars, Pedestrians and Lights
Find every car, pedestrian and traffic light in the camera image with one network: grid-based detection in the style of YOLO, building targets from your labelled boxes, a loss with four parts, non-maximum suppression, precision and recall per class, and running your trained detector live in the simulator.
Softmaxima Simulator StudioTry this topic's code in the Studio: it opens with the camera and trained networks project, ready to run.OpenIn plain words
A detector draws a box around every car, person and traffic light in the picture and says what each one is. Ours splits the image into a grid of small squares and asks each square one question: "is the middle of an object in me, and if so, what is it and how big?"
By the end of this topic you will be able to explain how a detector finds objects, and judge one by how many objects it finds and how often it is wrong.
Start with: the demo Try it: your detector, live: move the threshold slider.
You do not need to train anything to follow this topic. Every demo comes with an example network that already works. Training your own in Google Colab (the Code sections) is an optional level-up you can do now or later.
From "what is it?" to "what and where?"
The traffic-light classifier answered one question about a crop that someone else had cut out. A detector must look at the whole image and answer two questions for every object: what is it, and where is it (a box). It must also cope with a varying number of objects: none on an empty road, a dozen at a busy crossing.
There are two big families:
- Two-stage detectors (Faster R-CNN): first propose regions that might hold an object, then classify each one. Accurate but slower.
- One-stage detectors (YOLO, SSD, RetinaNet, and modern ones like DETR): predict boxes and classes for the whole image in one pass. Fast enough for a car, which needs answers 10–30 times a second.
You will build a one-stage detector from scratch, in the spirit of the original YOLO. It is small enough to train in a few minutes on Colab and to run in your browser.
Going deeper
The sections marked Intermediate · Maths, Code or Advanced go deeper: the equations, the code and the finer details. They are worth it when you are ready, but you can follow the whole idea without them. To hide them, press those buttons next to Show at the top of the page; the Beginner explanations and Try it demos stay.
The grid idea
The network shrinks the 120 × 240 image by 8 in each direction, to a 15 × 30 grid of cells. Each cell sees an 8 × 8-pixel patch (and, through its layers, the area around it). For every cell the network outputs 8 numbers:
- Objectness (1 number): is the centre of an object inside this cell?
- Class scores (3 numbers): car, pedestrian or traffic light.
- Position (2 numbers): where in the cell the centre is, from 0 to 1, after a sigmoid.
- Size (2 numbers): the box's width and height, as logarithms measured in cells. Logs let one output cover a 3-pixel light far away and a 100-pixel car close up.
Only the cell that holds an object's centre is responsible for it. That makes the targets simple to build, and it is why the network is "fully convolutional": the same small set of weights slides over every cell.
Building the targets and the loss
From each labelled box, the code finds the cell that holds its centre and writes the target there: objectness 1, the class, the centre's position inside the cell and the log size. Every other cell gets objectness 0. Boxes too small to learn from (under 4 pixels tall) get −1, "ignore": punishing the network for spotting a 2-pixel car would teach it to ignore real ones.
The loss has four parts, added together:
- Objectness: binary cross-entropy in every cell. Cells with an object are rare (a few out of 450), so they count 4 times.
- Class: cross-entropy, only in cells with an object.
- Position: binary cross-entropy between the sigmoid output and the target position, only in cells with an object.
- Size: L1 (absolute) error of the log width and height, only in cells with an object.
Mirroring the image is a free way to double the data, but the targets must be mirrored too: the grid flips, and each centre's position inside its cell becomes 1 − x.
Non-maximum suppression and how to score a detector
Neighbouring cells often both claim the same car. Non-maximum suppression (NMS) keeps the most confident box and drops any other box of the same class that overlaps it by more than a set intersection over union (IoU):
A prediction is a true positive if it overlaps a real object of the same class with IoU ≥ 0.5. Then, per class:
Precision asks "when it says car, is there a car?"; recall asks "of all the cars, how many did it find?". The confidence threshold trades one for the other. For a car, a missed pedestrian (low recall) is far worse than braking for a shadow (low precision), so the threshold per class should be set by the cost of each mistake. Research papers summarise the whole trade-off curve as mean average precision (mAP).
Code: build the grid targets
Record at least three datasets (at 120 × 240, with cars and pedestrians on, in mixed weather) in Recording a labelled dataset. Then run these blocks in order in one Colab notebook with a GPU.
# In Google Colab. Upload two or more recordings at 120 × 240 (the last is kept for testing).
from google.colab import files
import numpy as np
names = list(files.upload())
assert len(names) >= 2, "Upload at least two recordings: the last one is kept for testing."
STRIDE, GH, GW = 8, 15, 30 # the network outputs one prediction per 8 × 8-pixel cell: a 15 × 30 grid
CLASSES = ["car", "pedestrian", "traffic light"]
def grid_targets(boxes, n):
"""For every image, a (6, 15, 30) target. Channel 0: 1 if a box's centre is in the cell, 0 if not,
-1 to ignore (a box too small to learn from). Then the class, the centre's position inside the cell (0–1),
and the box's log width and height, measured in cells."""
T = np.zeros((n, 6, GH, GW), np.float32)
for frame, cls, x1, y1, x2, y2, _ in boxes:
w, h = x2 - x1, y2 - y1
cx, cy = (x1 + x2) / 2, (y1 + y2) / 2
j, i = min(GW - 1, int(cx // STRIDE)), min(GH - 1, int(cy // STRIDE))
if h < 4 or w < 2:
if T[frame, 0, i, j] == 0:
T[frame, 0, i, j] = -1
continue
if T[frame, 0, i, j] == 1 and np.exp(T[frame, 4, i, j] + T[frame, 5, i, j]) * STRIDE ** 2 >= w * h:
continue # two centres in one cell: keep the bigger box
T[frame, :, i, j] = [1, cls, cx / STRIDE - j, cy / STRIDE - i, np.log(w / STRIDE), np.log(h / STRIDE)]
return T
data = [np.load(n) for n in names]
X_train = np.concatenate([d["images"] for d in data[:-1]])
T_train = np.concatenate([grid_targets(d["boxes"], len(d["images"])) for d in data[:-1]])
X_test, boxes_test = data[-1]["images"], data[-1]["boxes"]
print("training images:", len(X_train), "| boxes to learn:", int((T_train[:, 0] == 1).sum()),
"per class", np.bincount(T_train[:, 1][T_train[:, 0] == 1].astype(int), minlength=3).tolist())Code: the network and training
Five convolution blocks and a 1 × 1 convolution that makes the 8 outputs per cell. About 60,000 weights: tiny next to YOLO, and enough for our simulator.
import torch
import torch.nn as nn
import torch.nn.functional as F
device = "cuda" if torch.cuda.is_available() else "cpu"
mean = X_train.reshape(-1, 3).mean(0) / 255
std = X_train.reshape(-1, 3).std(0) / 255
m = torch.tensor(mean, dtype=torch.float32, device=device).view(1, 3, 1, 1)
s = torch.tensor(std, dtype=torch.float32, device=device).view(1, 3, 1, 1)
raw = lambda X: torch.tensor(X, dtype=torch.float32, device=device).permute(0, 3, 1, 2) / 255
def block(i, o, stride=1):
return [nn.Conv2d(i, o, 3, stride, 1), nn.BatchNorm2d(o), nn.ReLU()]
model = nn.Sequential(
*block(3, 16, 2), *block(16, 32, 2), *block(32, 48, 2), # 120×240 -> 15×30: each output cell sees 8×8 pixels
*block(48, 48), *block(48, 48), # more context for big, close objects
nn.Conv2d(48, 8, 1), # per cell: objectness, 3 class scores, x, y, w, h
).to(device)
def detection_loss(out, T):
pos, keep = T[:, 0] == 1, (T[:, 0] != -1).float()
weight = (pos.float() * 3 + 1) * keep # centres are rare: each counts 4 times
loss = (F.binary_cross_entropy_with_logits(out[:, 0], pos.float(), reduction="none") * weight).sum()
if pos.any():
o, t = out.permute(0, 2, 3, 1)[pos], T.permute(0, 2, 3, 1)[pos]
loss = loss + F.cross_entropy(o[:, 1:4], t[:, 1].long(), reduction="sum") # which class
loss = loss + F.binary_cross_entropy_with_logits(o[:, 4:6], t[:, 2:4], reduction="sum") # where in the cell
loss = loss + F.l1_loss(o[:, 6:8], t[:, 4:6], reduction="sum") # how big
return loss / len(out)
opt = torch.optim.AdamW(model.parameters(), lr=2e-3, weight_decay=1e-4)
sched = torch.optim.lr_scheduler.StepLR(opt, step_size=6, gamma=0.5)
for epoch in range(15):
model.train()
perm = torch.randperm(len(X_train)).numpy()
total = 0
for i in range(0, len(perm), 16):
b = perm[i:i + 16]
r = (raw(X_train[b]) * torch.empty(len(b), 1, 1, 1, device=device).uniform_(0.7, 1.3)).clamp(0, 1)
t = torch.tensor(T_train[b], device=device)
if torch.rand(1).item() < 0.5: # mirror the image and its targets
r, t = r.flip(3), t.flip(3)
t[:, 2] = torch.where(t[:, 0] == 1, 1 - t[:, 2], t[:, 2])
loss = detection_loss(model((r - m) / s), t)
opt.zero_grad()
loss.backward()
opt.step()
total += loss.item()
sched.step()
print(f"epoch {epoch + 1}: loss {total / (len(perm) / 16):.3f}")Code: decode, NMS, precision and recall
Turn the grid back into boxes, remove duplicates, and score each class on the recording you kept back.
import numpy as np
import torch
def decode(out, thr=0.5, nms_iou=0.45):
"""Grid output (8, 15, 30) -> boxes [score, class, x1, y1, x2, y2] after non-maximum suppression."""
sig = lambda z: 1 / (1 + np.exp(-z))
found = []
for i in range(GH):
for j in range(GW):
p = sig(out[0, i, j])
if p < thr:
continue
c = int(np.argmax(out[1:4, i, j]))
cx, cy = (j + sig(out[4, i, j])) * STRIDE, (i + sig(out[5, i, j])) * STRIDE
w, h = STRIDE * np.exp(out[6, i, j]), STRIDE * np.exp(out[7, i, j])
found.append([p, c, cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2])
found.sort(key=lambda r: -r[0])
keep = []
for r in found: # drop boxes that overlap a better box of the same class
if all(k[1] != r[1] or iou(k[2:], r[2:]) < nms_iou for k in keep):
keep.append(r)
return keep
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 + 1e-9)
model.eval()
with torch.no_grad():
outs = np.concatenate([model((raw(X_test[i:i + 50]) - m) / s).cpu().numpy() for i in range(0, len(X_test), 50)])
tp, fp, fn = np.zeros(3), np.zeros(3), np.zeros(3)
for f in range(len(X_test)):
frame_boxes = boxes_test[boxes_test[:, 0] == f]
truth = [list(r[2:6]) + [r[1]] for r in frame_boxes if r[5] - r[3] >= 6] # objects at least 6 px tall
used = set()
for p in decode(outs[f]):
hit = [k for k, g in enumerate(truth) if g[4] == p[1] and k not in used and iou(p[2:], g[:4]) >= 0.5]
if hit:
used.add(hit[0]); tp[p[1]] += 1
elif not any(iou(p[2:], r[2:6]) > 0.3 for r in frame_boxes): # not just a tiny far object
fp[p[1]] += 1
for k, g in enumerate(truth):
if k not in used:
fn[g[4]] += 1
for c, name in enumerate(CLASSES):
print(f"{name:>13}: precision {tp[c] / max(1, tp[c] + fp[c]):.0%}, recall {tp[c] / max(1, tp[c] + fn[c]):.0%} "
f"({int(tp[c] + fn[c])} objects)")On simulator data, the example detector reaches roughly 94% precision and 85% recall for cars, but only about 18% recall for pedestrians and 51% for traffic lights. Pedestrians are rare in the data and lights are tiny. That is the real-world pattern too: the rare, small objects are the hard ones. More recordings with pedestrians, or weighting rare classes, helps.
Code: export for the simulator
The first block turns PyTorch layers into the simulator's format, folding each batch-norm into the convolution before it. You will reuse it in every topic that follows. The second saves your detector.
import json
import base64
import torch
import torch.nn as nn
def f32(t):
return base64.b64encode(t.detach().cpu().numpy().astype("<f4").tobytes()).decode()
def layers_of(module):
"""The layer list the simulator runs, for Conv2d, BatchNorm2d, ReLU, Sigmoid, MaxPool2d, Upsample, Flatten,
Linear and Dropout layers (in that kind of sequence). Batch norm is folded into the convolution before it."""
mods = [m for m in module.modules() if not isinstance(m, nn.Sequential)]
layers, i = [], 0
while i < len(mods):
m = mods[i]
if isinstance(m, nn.Conv2d):
w = m.weight.detach().clone()
b = m.bias.detach().clone() if m.bias is not None else torch.zeros(m.out_channels)
if i + 1 < len(mods) and isinstance(mods[i + 1], nn.BatchNorm2d):
bn = mods[i + 1]
i += 1
scale = bn.weight.detach() / torch.sqrt(bn.running_var + bn.eps)
w = w * scale[:, None, None, None]
b = (b - bn.running_mean) * scale + bn.bias.detach()
layers.append(dict(type="conv", inC=m.in_channels, outC=m.out_channels, k=m.kernel_size[0],
stride=m.stride[0], pad=m.padding[0], w=f32(w), b=f32(b)))
elif isinstance(m, nn.ReLU):
layers.append(dict(type="relu"))
elif isinstance(m, nn.Sigmoid):
layers.append(dict(type="sigmoid"))
elif isinstance(m, nn.MaxPool2d):
k = m.kernel_size if isinstance(m.kernel_size, int) else m.kernel_size[0]
st = m.stride if isinstance(m.stride, int) else m.stride[0]
layers.append(dict(type="maxpool", k=k, s=st))
elif isinstance(m, nn.Upsample):
layers.append(dict(type="upsample", f=int(m.scale_factor)))
elif isinstance(m, nn.AdaptiveAvgPool2d):
layers.append(dict(type="gap"))
elif isinstance(m, nn.Flatten):
layers.append(dict(type="flatten"))
elif isinstance(m, nn.Linear):
layers.append(dict(type="linear", inF=m.in_features, outF=m.out_features, w=f32(m.weight), b=f32(m.bias)))
elif isinstance(m, nn.Dropout):
pass # does nothing once training is over
else:
raise ValueError(f"The simulator cannot run {type(m).__name__} layers yet")
i += 1
return layers
def save_model(layers, path, task, classes, h, w, mean, std, **extra):
spec = dict(format="softmaxima-v1", task=task, classes=classes,
input=dict(h=h, w=w, mean=[float(v) for v in mean], std=[float(v) for v in std]), layers=layers, **extra)
with open(path, "w") as fh:
json.dump(spec, fh)
print(f"saved {path} with {len(layers)} layers")from google.colab import files
model = model.eval().cpu()
save_model(layers_of(model), "detector.json", "detector", CLASSES, 120, 240, mean, std, stride=STRIDE)
files.download("detector.json")Try it: your detector, live
The simulator runs the detector on every camera frame in your browser. It starts with an example detector of the same design; press Load your model to use yours. Move the threshold and watch precision and recall change. Tick Show the true boxes to see what it misses, and try night and rain.
Interactive: this part runs in your browser.
What would change in a real car
- Many more classes (cyclists, trucks, buses, cones, animals) and many objects that fit no class at all.
- Anchor-free, multi-scale heads: modern detectors predict from several grid sizes so that tiny far objects and large near ones both get the right resolution.
- 3D boxes: planning needs where an object is on the road, not in the image, so production systems predict 3D boxes, often from several cameras and lidar together.
- The long tail: a person in a costume, a mattress on the road. Fleets search their recordings for rare cases and add them to the training data.
Quiz
1. In a grid detector, which cell is responsible for an object?
2. Why does the network predict the log of the box size?
3. What does non-maximum suppression remove?
4. Raising the confidence threshold usually…
5. When you mirror an image for augmentation, what must happen to each box centre's position inside its cell?
📚 Further reading
Trusted, mostly free sources: official documentation, well-known textbooks and courses. When you want to confirm or go deeper on anything here, start with these.
- Redmon et al. (2016): You Only Look Once: Unified, Real-Time Object Detection ↗ the paper behind grid-based one-stage detection