Object Detection & Segmentation
From sliding windows to DETR and SAM.
Detection asks a network for an unknown number of objects, each with a class and a box. The field's history is a sequence of answers to two questions, where candidate boxes come from and how duplicates are removed: from thousands of proposals per image, through dense anchors and a loss that tames their imbalance, to a transformer that predicts a set and is trained with an optimal matching.
What you’ll learn
- Prove that is a metric, and parametrize box regression in a scale-invariant way.
- Trace R-CNN to Faster R-CNN and the one-stage detectors, and derive the focal loss from the class imbalance of dense detection.
- Compute average precision and COCO mean average precision exactly, and explain why detection is scored by precision–recall rather than ROC.
- Formulate detection as set prediction with bipartite matching (DETR), and follow dense prediction from FCN and U-Net to Mask R-CNN, panoptic quality and SAM.
Boxes, overlaps and a metric
Order the pixels by a uniformly random permutation and let be the first pixel of in that order (MinHash; Broder, 1997). The first pixel of is uniform over , and exactly when it lies in :
If , then or . The union bound gives the triangle inequality:
So overlaps compose. Two detections with IoU at least 0.8 with the same object are within of each other, so their mutual IoU is at least 0.6 and NMS at suppresses one of them; the bound is tight (boxes and around the object ).
IoU itself is a poor regression loss: its gradient vanishes when boxes do not overlap. GIoU (Rezatofighi et al., 2019) subtracts the fraction of the smallest enclosing box not covered by , , which still pulls disjoint boxes together. Since Fast and Faster R-CNN, detectors regress offsets relative to a reference box (an anchor or proposal) with center and size :
Two stages, one stage, and the focal loss
| Detector | Year | Candidate boxes | Key idea |
|---|---|---|---|
| R-CNN (Girshick et al.) | 2014 | about 2,000 selective-search proposals per image, each warped and run through a CNN | CNN features, per-class linear SVMs, box regression; one network pass per proposal |
| Fast R-CNN (Girshick) | 2015 | the same proposals, pooled from one shared feature map | RoI pooling to a fixed grid; one multi-task loss (softmax plus smooth ) |
| Faster R-CNN (Ren et al.) | 2015 | a region proposal network on the shared features, with 9 anchors (3 scales × 3 aspect ratios) per position | nearly cost-free proposals, trained end to end |
| YOLO (Redmon et al.) | 2016 | a grid; each cell predicts 2 boxes with confidences and 20 class probabilities ( outputs) | a single pass, in real time |
| SSD (Liu et al.); RetinaNet (Lin et al.) | 2016; 2017 | dense anchors on several feature scales (feature pyramids; Lin et al., 2017) | one stage; RetinaNet's focal loss matched the accuracy of two-stage detectors |
A one-stage detector scores on the order of anchors per image, almost all of them easy background. Under cross-entropy each easy negative contributes a small loss, but together they swamp the few hundred hard examples. Two-stage detectors avoid this with a proposal stage and sampling heuristics; the focal loss (Lin et al., 2017) fixes the loss instead.
Write for the predicted probability of the true class. Cross-entropy is ; the focal loss multiplies it by a factor that vanishes for well-classified examples:
An easy negative with has its loss scaled by ; a hard example with only by . For easy negatives:
Hard and misclassified examples now dominate the gradient, without the hard-negative mining or fixed foreground-to-background sampling ratios that earlier detectors needed.
Scoring detectors: average precision
Detections are matched to the ground truth class by class. Sort them by score; a detection is a true positive if its IoU with some still-unmatched ground-truth box reaches the threshold, and a false positive otherwise, duplicates included. Walking down the ranked list gives a precision and a recall at every rank .
With ground-truth objects, recall rises by at each true positive and stays flat at false positives. The area under the step-shaped precision–recall curve is therefore the mean precision at the ranks of the hits:
Benchmarks first make precision monotone, , which can only raise AP. PASCAL VOC 2007 averaged at 11 recall levels; COCO samples 101, averages over its 80 categories (mAP) and over ten IoU thresholds, which rewards precise localization:
Objects that are never detected cap recall below 1, and the missing area counts against AP.
An image has three ground-truth objects of one class, and the ranked detections are TP, FP, TP, FP, TP. What is the (non-interpolated) AP, in percent?
Show the answer
76 %
Precision at the three hits is , and , so AP . Interpolation changes nothing here, because precision at each hit is already the maximum to its right.
Why precision–recall and not ROC? The negatives of detection are all the boxes that contain no object; even after proposals, background candidates outnumber objects by orders of magnitude. ROC curves divide false positives by that huge number of negatives, which hides them; precision counts them directly.
NMS completes the pipeline, and its threshold is a compromise: a low one suppresses true neighbors in crowds, a high one keeps duplicates. Soft-NMS (Bodla et al., 2017) decays overlapping scores, , instead of deleting the boxes. NMS is also a hand-designed, non-differentiable step outside training, which motivated detectors that learn to avoid duplicates.
Detection as set prediction: DETR
DETR (Carion et al., 2020) predicts a fixed-size set of (class, box) pairs from learned object queries, decoded by a transformer that attends to CNN features; most predictions are the extra class "no object", . Training first finds the best one-to-one assignment between the predictions and the ground truth, padded with to size , then applies the loss to the matched pairs:
Let be non-negative with every row and column sum equal to . Any set of rows carries mass , all of it in the columns those rows touch, each of which holds at most ; so the rows of touch at least columns. By Hall's theorem the support of contains a perfect matching, a permutation with matrix :
Subtract that permutation with the largest possible weight, . The remainder is non-negative, has equal row and column sums , and has at least one more zero:
Induction on the number of nonzero entries writes every doubly stochastic matrix as a convex combination of permutation matrices. A linear objective over this polytope attains its minimum at a vertex, which is a permutation, so relaxing the matching to a linear program loses nothing; the Hungarian algorithm is a primal–dual method for exactly this program.
DETR removed anchors and NMS, at a price: it needed about 500 training epochs on COCO and struggled with small objects. Deformable DETR (Zhu et al., 2021) attends to a few sampled points per query across feature scales and trains with ten times fewer epochs. Later DETR-style detectors became competitive with the best convolutional ones, and one-stage designs have adopted one-to-one matching to drop NMS as well.
Why does DETR's loss use an optimal matching instead of a fixed rule such as "query predicts the -th annotated object"?
- The matching makes training faster than a fixed rule
- Objects have no canonical order, so any fixed assignment is arbitrary; matching makes the loss depend only on the two sets
- A fixed rule would require anchors
- The matching replaces the box regression loss
Show the answer
B. Objects have no canonical order, so any fixed assignment is arbitrary; matching makes the loss depend only on the two sets
A set has no order. Under a fixed rule, the same image could demand different outputs from a query depending on how its annotations happened to be listed, and a correct set predicted in a different order would be penalized. Matching first and then scoring makes the loss a function of the predicted and true sets alone.
Dense prediction: from FCN to SAM
Segmentation predicts a label per pixel. Fully convolutional networks (Long, Shelhamer & Darrell, 2015) turn a classifier's fully connected layers into convolutions, so the network outputs a coarse map of class scores for an input of any size, then upsample it with learned transposed convolutions and skip connections from finer layers. U-Net (Ronneberger, Fischer & Brox, 2015) made the decoder mirror the encoder and concatenated encoder features at every scale, which worked with very few training images in biomedical segmentation. Dilated convolutions enlarge receptive fields without downsampling:
Mask R-CNN (He et al., 2017) adds a mask branch to Faster R-CNN: for each region, a small FCN predicts a binary mask per class. Its RoIAlign samples region features by bilinear interpolation instead of rounding region coordinates to the feature grid, which improved mask accuracy by 10 to 50% relative. Panoptic segmentation (Kirillov et al., 2019) unifies "stuff" (sky, road) and "things" (cars, people): every pixel gets a class and, for things, an instance identity. It is scored by panoptic quality, with predicted and true segments matched when their IoU exceeds 0.5:
Segment Anything (Kirillov et al., 2023) turned segmentation into a promptable task: given an image and a prompt (points, a box, a rough mask), output valid masks, several when the prompt is ambiguous. A large MAE-pretrained vision transformer encodes the image once, and a light decoder answers each prompt in milliseconds. Its SA-1B dataset, over a billion masks on 11 million images, was built with the model in the annotation loop. Open-vocabulary detectors go further, replacing fixed class lists with text embeddings from vision–language models (Contrastive Vision–Language Models).
Key takeaways
- is a metric (MinHash proof), so overlaps compose: two detections near the same object are near each other. Box offsets are regressed in scale-invariant units.
- Two-stage detectors refine proposals (R-CNN → Fast → Faster R-CNN with anchors); one-stage detectors classify dense anchors, made accurate by the focal loss .
- AP is the mean precision at the ranks of true positives; COCO averages it over 80 classes and IoU thresholds 0.50–0.95. Extreme imbalance is why detection uses precision–recall, not ROC.
- DETR treats detection as set prediction: Hungarian matching, a linear program with integral optima by Birkhoff–von Neumann, makes the loss permutation-invariant and NMS unnecessary.
- Dense prediction runs from FCN and U-Net to Mask R-CNN, panoptic quality (unique matches above IoU 0.5) and promptable segmentation with SAM.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Detections and each have IoU at least 0.8 with the same ground-truth box. What can you conclude about ?
- Nothing
- It is at least 0.6
- It is at least 0.8
- It is exactly
Show the answer
B. It is at least 0.6
is a metric, so and ; NMS at 0.5 suppresses the weaker one. The bound is attained by boxes covering opposite ends of the object.
With , by what factor does the focal loss down-weight an example with relative to cross-entropy, ignoring ?
Show the answer
A.
: a hundredfold reduction. At the factor is only 4, so hard examples keep most of their weight.
Why is detection evaluated with precision–recall (AP) rather than ROC AUC?
- ROC curves cannot be computed for boxes
- AP is cheaper to compute
- AP ignores false positives
- Background candidates vastly outnumber objects; ROC divides false positives by that huge count and hides them, while precision counts them
Show the answer
D. Background candidates vastly outnumber objects; ROC divides false positives by that huge count and hides them, while precision counts them
A detector that adds a thousand false boxes per image barely moves its false-positive rate over candidates, but its precision collapses. AP reflects what a user of the detections sees.
What removes duplicate detections in DETR?
- Non-maximum suppression after decoding
- Anchors with several aspect ratios
- The one-to-one bipartite matching in the loss, which trains every unmatched query to predict "no object"
- A higher IoU threshold at evaluation
Show the answer
C. The one-to-one bipartite matching in the loss, which trains every unmatched query to predict "no object"
Each ground-truth object is matched to exactly one prediction, so a second prediction on the same object is penalized toward . Attention among the queries lets them coordinate, and NMS becomes unnecessary.
Further reading
- S. Ren, K. He, R. Girshick & J. Sun, "Faster R-CNN: Towards real-time object detection with region proposal networks," NeurIPS (2015).
- T.-Y. Lin, P. Goyal, R. Girshick, K. He & P. Dollár, "Focal loss for dense object detection," ICCV (2017).
- N. Carion, F. Massa, G. Synnaeve, N. Usunier, A. Kirillov & S. Zagoruyko, "End-to-end object detection with transformers," ECCV (2020).
- A. Kirillov et al., "Segment anything," ICCV (2023).
- R. Szeliski, Computer Vision: Algorithms and Applications (Springer, 2nd ed., 2022).