Object detection
Where is it, and what is it — IoU, anchors, NMS, mAP and DETR
Detection turns a classifier into something that can count cars, find tumors, read shelves or steer a robot: for every object, a box and a label. It introduces ideas you will reuse everywhere — IoU and non-maximum suppression, multi-scale feature pyramids, the foreground/background imbalance that focal loss fixes, and DETR's set-prediction view that connects vision to transformers (7.1 Attention Is All You Need: the big picture). It is also the task where evaluation (mAP) is subtle enough that computing it by hand once pays off for life.
You'll be able to
- Compute IoU, run non-maximum suppression and compute average precision by hand
- Explain the two-stage lineage (R-CNN → Fast → Faster R-CNN with RPN and anchors) and the one-stage family (YOLO, SSD, RetinaNet)
- Derive why focal loss handles the foreground/background imbalance
- Describe feature pyramid networks and DETR's bipartite-matching set prediction
- Train a detector on a custom dataset with a modern library
Key ideas
- IoU = |A∩B| / |A∪B| decides whether a detection counts (≥ 0.5 in VOC; averaged over 0.5–0.95 in COCO).
- Two-stage: R-CNN (2k proposals, 47 s) → Fast R-CNN (shared features, RoI pooling) → Faster R-CNN (RPN with anchors; box deltas t_x = (x−x_a)/w_a, t_w = log(w/w_a)).
- One-stage: YOLO/SSD predict from a grid in a single pass; focal loss FL = −(1−p_t)^γ log p_t removes the easy-background flood (p_t = 0.99 is down-weighted 10⁴× at γ = 2).
Show 4 more key ideas
- FPN merges top-down semantics with lateral resolution to detect objects at all scales.
- NMS keeps the highest-scoring box and suppresses same-class boxes with IoU above a threshold; DETR avoids it by construction.
- AP is the area under the interpolated precision–recall curve over ranked detections; mAP averages over classes (and IoU thresholds for COCO).
- DETR treats detection as set prediction: object queries + Hungarian matching, no anchors or NMS; its descendants top COCO, YOLO dominates deployment.
Suggested path through this lesson
The task and its vocabulary
Given an image, output a set of triples, with boxes as or corner coordinates. Benchmarks: PASCAL VOC (20 classes) and COCO (80 classes, 118K training images, small/medium/large objects). Two quantities define everything downstream.
Intersection over Union between boxes and :
Worked: spans –, spans –. Areas 100 each; intersection ; union ; . VOC counts a detection as correct if ; COCO averages over thresholds , rewarding tight boxes.
From sliding windows to region proposals: the two-stage family
The naive approach — classify every window at every scale — is hopeless (millions of crops). R-CNN (2014) used selective search for about 2,000 class-agnostic region proposals, ran a CNN on each warped crop and classified with SVMs: 47 s per image. Fast R-CNN (2015) ran the CNN once on the whole image and pooled features for each proposal with RoI pooling, training classification and box regression jointly with a multi-task loss (softmax + smooth-). Faster R-CNN (2015) replaced selective search with a Region Proposal Network: at each position of the feature map, reference anchors (e.g., 3 scales × 3 aspect ratios) each get an objectness score and four box deltas. Boxes are parametrized relative to their anchor so the regression targets are scale-free:
Proposals from the RPN feed the Fast R-CNN head; the whole thing runs at 5–17 fps and remained the accuracy reference for years. Mask R-CNN adds a mask branch (5.6 Segmentation).
One-stage detectors: predict everything at once
YOLO (2016) divides the image into an grid; each cell predicts boxes with confidences and one class distribution, all from a single forward pass — 45 fps, with weaker small-object accuracy. SSD predicts from multiple feature-map resolutions with default boxes (anchors) to handle scale. One-stage detectors face a brutal imbalance: of ~100K anchors per image, perhaps 10 are objects, and the easy background examples swamp the loss. RetinaNet fixed this with focal loss:
where is the predicted probability of the true class. For , an easy background example with is down-weighted by — effectively removed — while a hard example with keeps of its weight. With focal loss (and FPN), one-stage detectors matched two-stage accuracy. The YOLO line continued (v3 multi-scale, v4/v5 training tricks, v8–v11 anchor-free with decoupled heads via Ultralytics) and remains the practical default for real-time detection.
Feature Pyramid Networks
Small objects need high-resolution features, large objects need semantic depth. FPN adds a top-down pathway: upsample the deepest map, add the laterally connected (1×1-projected) shallower map, repeat — producing a pyramid where every level is both high-resolution-ish and semantically strong. Objects are assigned to levels by size. FPN is now a standard component of detectors and segmenters.
Non-maximum suppression
Detectors fire several overlapping boxes per object. NMS: sort detections by score; take the top one; remove all remaining boxes of the same class with (typically 0.5) against it; repeat with the next survivor. Mini-example: boxes with scores 0.9, 0.8, 0.7 where the 0.8 box overlaps the 0.9 box at IoU 0.6 and the 0.7 box at IoU 0.2 → keep 0.9, drop 0.8, keep 0.7. Soft-NMS decays scores instead of deleting. DETR removes the need for NMS altogether.
Mean average precision, by hand
For one class, rank all detections across the dataset by score. Walking down the list, mark each as TP if it matches an unmatched ground-truth box with , else FP; compute cumulative precision and recall after each detection. Average precision is the area under the (interpolated) precision–recall curve; mAP averages AP over classes (and over IoU thresholds for COCO).
Worked example: 3 ground-truth objects, 5 detections ranked by score: TP, FP, TP, TP, FP.
| rank | TP/FP | cum TP | precision | recall |
|---|---|---|---|---|
| 1 | TP | 1 | 1/1 = 1.00 | 1/3 |
| 2 | FP | 1 | 1/2 = 0.50 | 1/3 |
| 3 | TP | 2 | 2/3 = 0.67 | 2/3 |
| 4 | TP | 3 | 3/4 = 0.75 | 3/3 |
| 5 | FP | 3 | 3/5 = 0.60 | 3/3 |
All-point interpolation replaces each precision with the maximum precision at any recall the current one: at recall 1/3 → 1.00; at 2/3 → 0.75; at 1 → 0.75. AP . A detector that produced the same boxes in a different confidence order would get a different AP — ranking quality is part of the score.
DETR: detection as set prediction
DETR (2020) feeds CNN features into a transformer encoder–decoder (7.1 Attention Is All You Need: the big picture); learned object queries each produce one (class, box) prediction, with a "no object" class filling the rest. Training uses bipartite matching: the Hungarian algorithm finds the one-to-one assignment between predictions and ground truths minimizing a cost of class probability plus box and generalized IoU, and the loss is computed on matched pairs only. No anchors, no NMS, no hand-designed priors. The original converged slowly and struggled on small objects; Deformable DETR, DINO-DETR and RT-DETR fixed both, and transformer detectors now top COCO leaderboards, while YOLO-style models dominate deployment for speed.
In practice
Use torchvision.models.detection (Faster R-CNN, RetinaNet, FCOS with pretrained COCO weights) or ultralytics (YOLO: YOLO("yolo11n.pt").train(data="data.yaml", epochs=50)). Label with CVAT, Label Studio or Roboflow; know the COCO JSON and YOLO txt formats; augment boxes consistently (Albumentations handles box transforms). Typical failures: tiny objects (use higher input resolution or FPN levels), crowded scenes (NMS merges neighbors), domain shift, and class confusion among similar categories — evaluate per class and per object size.
Where this shows up later
- Mask R-CNN extends Faster R-CNN to instance segmentation — 5.6 Segmentation.
- DETR's encoder–decoder and Hungarian matching reappear in panoptic and open-vocabulary detectors built on CLIP-style encoders — 7.1 Attention Is All You Need: the big picture, 8.10 Multimodal models.
- Focal loss and class imbalance connect back to 4.3 Loss functions catalog and 3.5 Evaluating models: metrics, validation and the bias–variance trade-off; IoU-style losses to 5.6 Segmentation.
Common pitfalls (4)
- Computing mAP with unsorted detections or allowing one ground-truth box to match several detections — both inflate the score.
- Using NMS thresholds blindly: too low merges neighboring objects in crowds; too high leaves duplicates.
- Training a detector at low resolution and wondering why small objects vanish — resolution and FPN level assignment matter more than the backbone.
- Comparing 'mAP' numbers from different protocols (VOC mAP@0.5 vs COCO mAP@0.5:0.95) as if they were the same metric.
Recap: all 7 key points
- IoU = |A∩B| / |A∪B| decides whether a detection counts (≥ 0.5 in VOC; averaged over 0.5–0.95 in COCO).
- Two-stage: R-CNN (2k proposals, 47 s) → Fast R-CNN (shared features, RoI pooling) → Faster R-CNN (RPN with anchors; box deltas t_x = (x−x_a)/w_a, t_w = log(w/w_a)).
- One-stage: YOLO/SSD predict from a grid in a single pass; focal loss FL = −(1−p_t)^γ log p_t removes the easy-background flood (p_t = 0.99 is down-weighted 10⁴× at γ = 2).
- FPN merges top-down semantics with lateral resolution to detect objects at all scales.
- NMS keeps the highest-scoring box and suppresses same-class boxes with IoU above a threshold; DETR avoids it by construction.
- AP is the area under the interpolated precision–recall curve over ranked detections; mAP averages over classes (and IoU thresholds for COCO).
- DETR treats detection as set prediction: object queries + Hungarian matching, no anchors or NMS; its descendants top COCO, YOLO dominates deployment.
Watch
Semantic segmentation first, then R-CNN → Fast → Faster, YOLO/SSD and Mask R-CNN — the whole lineage in one lecture.
Read
Exercises
- IoU, NMS and AP by hand
Invent 3 ground-truth boxes and 6 scored detections on a canvas. Compute all IoUs, run NMS at , then compute the TP/FP table and all-point interpolated AP. Re-order two detection scores and recompute AP to see how ranking changes the metric.
- Implement mAP in NumPy
Write
average_precision(detections, ground_truths, iou_thr)following the algorithm in the notes (greedy matching by score, one GT per detection). Validate againsttorchmetrics.detection.MeanAveragePrecisionon random synthetic data — they should agree at AP@0.5. - Train a detector in an hour
Label 100–200 images of something around you (or use a small public dataset) in YOLO format and fine-tune a nano YOLO model for 50 epochs on a free GPU. Report mAP@0.5 and mAP@0.5:0.95, inspect per-class results and the worst images. Expected: usable detections after one hour; small objects will be the weak spot.
Quiz
Flashcards
These cards are now in your spaced-repetition queue. Review all due cards →