Simple Algorithm
Artificial Intelligence · Deep Layer · 28 min

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 1−IoU1-\mathrm{IoU} 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

DerivationProof by random hashing
  1. Pr⁡[h(A)=h(B)]=∣A∩B∣∣A∪B∣=J(A,B),Pr⁡[h(A)≠h(B)]=dJ(A,B)\Pr\big[h(A)=h(B)\big]=\frac{|A\cap B|}{|A\cup B|}=J(A,B),\qquad\Pr\big[h(A)\ne h(B)\big]=d_J(A,B)

    Order the pixels by a uniformly random permutation and let h(A)h(A) be the first pixel of AA in that order (MinHash; Broder, 1997). The first pixel of A∪BA\cup B is uniform over A∪BA\cup B, and h(A)=h(B)h(A)=h(B) exactly when it lies in A∩BA\cap B:

  2. dJ(A,C)=Pr⁡[h(A)≠h(C)]≤Pr⁡[h(A)≠h(B)]+Pr⁡[h(B)≠h(C)]=dJ(A,B)+dJ(B,C)d_J(A,C)=\Pr\big[h(A)\ne h(C)\big]\le\Pr\big[h(A)\ne h(B)\big]+\Pr\big[h(B)\ne h(C)\big]=d_J(A,B)+d_J(B,C)

    If h(A)≠h(C)h(A)\ne h(C), then h(A)≠h(B)h(A)\ne h(B) or h(B)≠h(C)h(B)\ne h(C). The union bound gives the triangle inequality:

  3. So overlaps compose. Two detections with IoU at least 0.8 with the same object are within dJ≤0.4d_J\le0.4 of each other, so their mutual IoU is at least 0.6 and NMS at τ=0.5\tau=0.5 suppresses one of them; the bound is tight (boxes [0,8][0,8] and [2,10][2,10] around the object [0,10][0,10]).

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 CC not covered by A∪BA\cup B, GIoU=IoU−∣C∖(A∪B)∣/∣C∣∈(−1,1]\mathrm{GIoU}=\mathrm{IoU}-|C\setminus(A\cup B)|/|C|\in(-1,1], 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 (xa,ya)(x_a,y_a) and size (wa,ha)(w_a,h_a):

tx=x−xawa,ty=y−yaha,tw=log⁡wwa,th=log⁡hhat_x=\frac{x-x_a}{w_a},\qquad t_y=\frac{y-y_a}{h_a},\qquad t_w=\log\frac{w}{w_a},\qquad t_h=\log\frac{h}{h_a}
Shifts are measured in units of the reference box and scale changes on a log scale, so the targets do not depend on the object's size in pixels; they are trained with a smooth-L1L_1 (Huber) loss (Girshick, 2015).

Two stages, one stage, and the focal loss

DetectorYearCandidate boxesKey idea
R-CNN (Girshick et al.)2014about 2,000 selective-search proposals per image, each warped and run through a CNNCNN features, per-class linear SVMs, box regression; one network pass per proposal
Fast R-CNN (Girshick)2015the same proposals, pooled from one shared feature mapRoI pooling to a fixed 7×77\times7 grid; one multi-task loss (softmax plus smooth L1L_1)
Faster R-CNN (Ren et al.)2015a region proposal network on the shared features, with 9 anchors (3 scales × 3 aspect ratios) per positionnearly cost-free proposals, trained end to end
YOLO (Redmon et al.)2016a 7×77\times7 grid; each cell predicts 2 boxes with confidences and 20 class probabilities (7×7×307\times7\times30 outputs)a single pass, in real time
SSD (Liu et al.); RetinaNet (Lin et al.)2016; 2017dense anchors on several feature scales (feature pyramids; Lin et al., 2017)one stage; RetinaNet's focal loss matched the accuracy of two-stage detectors
Years of publication. Two-stage detectors refine a sparse set of candidates; one-stage detectors classify a dense grid of anchors directly, which is faster but meets a severe class imbalance.

A one-stage detector scores on the order of 10510^5 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.

DerivationFocal loss
  1. FL(pt)=−αt (1−pt)γlog⁡pt,γ=2,  α=0.25  in RetinaNet\mathrm{FL}(p_t)=-\alpha_t\,(1-p_t)^\gamma\log p_t,\qquad\gamma=2,\ \ \alpha=0.25\ \text{ in RetinaNet}

    Write ptp_t for the predicted probability of the true class. Cross-entropy is −log⁡pt-\log p_t; the focal loss multiplies it by a factor that vanishes for well-classified examples:

  2. 105×0.01005⏟cross-entropy≈1005⟶105×10−4×0.01005⏟focal, before α≈0.1\underbrace{10^5\times0.01005}_{\text{cross-entropy}}\approx1005\qquad\longrightarrow\qquad\underbrace{10^5\times10^{-4}\times0.01005}_{\text{focal, before }\alpha}\approx0.1

    An easy negative with pt=0.99p_t=0.99 has its loss scaled by (1−0.99)2=10−4(1-0.99)^2=10^{-4}; a hard example with pt=0.5p_t=0.5 only by 0.250.25. For 10510^5 easy negatives:

  3. 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 P(k)P(k) and a recall r(k)r(k) at every rank kk.

DerivationAverage precision
  1. AP=∑kP(k) Δr(k)=1R∑k: detection k is a true positiveP(k)\mathrm{AP}=\sum_kP(k)\,\Delta r(k)=\frac1R\sum_{k:\ \text{detection }k\text{ is a true positive}}P(k)

    With RR ground-truth objects, recall rises by 1/R1/R 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:

  2. APCOCO=110∑τ∈{0.50, 0.55, …, 0.95} 180∑c=180APc(τ)\mathrm{AP}^{\text{COCO}}=\frac1{10}\sum_{\tau\in\{0.50,\,0.55,\,\dots,\,0.95\}}\ \frac1{80}\sum_{c=1}^{80}\mathrm{AP}_c(\tau)

    Benchmarks first make precision monotone, Pinterp(r)=max⁡r′≥rP(r′)P_{\text{interp}}(r)=\max_{r'\ge r}P(r'), which can only raise AP. PASCAL VOC 2007 averaged PinterpP_{\text{interp}} at 11 recall levels; COCO samples 101, averages over its 80 categories (mAP) and over ten IoU thresholds, which rewards precise localization:

  3. Objects that are never detected cap recall below 1, and the missing area counts against AP.

Predict before you look

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 1/11/1, 2/32/3 and 3/53/5, so AP =13(1+0.667+0.6)≈0.756=\frac13(1+0.667+0.6)\approx0.756. 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, si←si e−IoU(b,bi)2/σs_i\leftarrow s_i\,e^{-\mathrm{IoU}(b,b_i)^2/\sigma}, 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 N=100N=100 (class, box) pairs from NN learned object queries, decoded by a transformer that attends to CNN features; most predictions are the extra class "no object", ∅\varnothing. Training first finds the best one-to-one assignment σ^\hat\sigma between the predictions and the ground truth, padded with ∅\varnothing to size NN, then applies the loss to the matched pairs:

σ^=arg min⁡σ∈SN∑i=1NLmatch(yi,y^σ(i)),Lmatch=1[ci≠∅](−p^σ(i)(ci)+Lbox(bi,b^σ(i)))\hat\sigma=\argmin_{\sigma\in S_N}\sum_{i=1}^{N}\mathcal L_{\text{match}}\big(y_i,\hat y_{\sigma(i)}\big),\qquad\mathcal L_{\text{match}}=\mathbf 1[c_i\ne\varnothing]\Big(-\hat p_{\sigma(i)}(c_i)+\mathcal L_{\text{box}}\big(b_i,\hat b_{\sigma(i)}\big)\Big)
Lbox\mathcal L_{\text{box}} combines an L1L_1 distance and the GIoU loss. Each object is matched to exactly one prediction, so a second prediction on the same object is trained toward ∅\varnothing: duplicates are suppressed by learning, and NMS is unnecessary.
DerivationProof sketch
  1. s ∣I∣=∑i∈I∑jXij ≤ s ∣{j: Xij>0 for some i∈I}∣s\,|I|=\sum_{i\in I}\sum_jX_{ij}\ \le\ s\,\big|\{j:\ X_{ij}>0\text{ for some }i\in I\}\big|

    Let X≠0X\ne0 be non-negative with every row and column sum equal to s>0s>0. Any set II of rows carries mass s∣I∣s|I|, all of it in the columns those rows touch, each of which holds at most ss; so the rows of II touch at least ∣I∣|I| columns. By Hall's theorem the support of XX contains a perfect matching, a permutation σ\sigma with matrix PP:

  2. X=λP+(X−λP)X=\lambda P+\big(X-\lambda P\big)

    Subtract that permutation with the largest possible weight, λ=min⁡iXiσ(i)>0\lambda=\min_iX_{i\sigma(i)}>0. The remainder is non-negative, has equal row and column sums s−λs-\lambda, and has at least one more zero:

  3. 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.

Check your understanding

Why does DETR's loss use an optimal matching instead of a fixed rule such as "query ii predicts the ii-th annotated object"?

  1. The matching makes training faster than a fixed rule
  2. Objects have no canonical order, so any fixed assignment is arbitrary; matching makes the loss depend only on the two sets
  3. A fixed rule would require anchors
  4. 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 1×11\times1 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:

rL=1+∑l=1L(k−1) δl  =k=3, δl=2l−1  2L+1−1r_L=1+\sum_{l=1}^{L}(k-1)\,\delta_l\ \ \overset{k=3,\ \delta_l=2^{l-1}}{=}\ \ 2^{L+1}-1
A stack of stride-1 3×33\times3 convolutions with dilations δl=1,2,4,…\delta_l=1,2,4,\dots sees 2L+1−12^{L+1}-1 pixels across after LL layers, exponential rather than linear growth, at full resolution (Yu & Koltun, 2016).

Mask R-CNN (He et al., 2017) adds a mask branch to Faster R-CNN: for each region, a small FCN predicts a 28×2828\times28 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:

PQ=∑(p,g)∈TPIoU(p,g)∣TP∣+12∣FP∣+12∣FN∣=∑TPIoU∣TP∣⏟segmentation quality×∣TP∣∣TP∣+12∣FP∣+12∣FN∣⏟recognition quality\mathrm{PQ}=\frac{\sum_{(p,g)\in\mathrm{TP}}\mathrm{IoU}(p,g)}{|\mathrm{TP}|+\frac12|\mathrm{FP}|+\frac12|\mathrm{FN}|}=\underbrace{\frac{\sum_{\mathrm{TP}}\mathrm{IoU}}{|\mathrm{TP}|}}_{\text{segmentation quality}}\times\underbrace{\frac{|\mathrm{TP}|}{|\mathrm{TP}|+\frac12|\mathrm{FP}|+\frac12|\mathrm{FN}|}}_{\text{recognition quality}}

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

  • 1−IoU1-\mathrm{IoU} 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 −(1−pt)γlog⁡pt-(1-p_t)^\gamma\log p_t.
  • 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.

Question 1

Detections D1D_1 and D2D_2 each have IoU at least 0.8 with the same ground-truth box. What can you conclude about IoU(D1,D2)\mathrm{IoU}(D_1,D_2)?

  1. Nothing
  2. It is at least 0.6
  3. It is at least 0.8
  4. It is exactly 0.82=0.640.8^2=0.64
Show the answer

B. It is at least 0.6

dJ=1−IoUd_J=1-\mathrm{IoU} is a metric, so dJ(D1,D2)≤0.2+0.2=0.4d_J(D_1,D_2)\le0.2+0.2=0.4 and IoU(D1,D2)≥0.6\mathrm{IoU}(D_1,D_2)\ge0.6; NMS at 0.5 suppresses the weaker one. The bound is attained by boxes covering opposite ends of the object.

Question 2

With γ=2\gamma=2, by what factor does the focal loss down-weight an example with pt=0.9p_t=0.9 relative to cross-entropy, ignoring α\alpha?

  1. 100100
  2. 1010
  3. 22
  4. 1,0001{,}000
Show the answer

A. 100100

(1−0.9)2=0.01(1-0.9)^2=0.01: a hundredfold reduction. At pt=0.5p_t=0.5 the factor is only 4, so hard examples keep most of their weight.

Question 3

Why is detection evaluated with precision–recall (AP) rather than ROC AUC?

  1. ROC curves cannot be computed for boxes
  2. AP is cheaper to compute
  3. AP ignores false positives
  4. 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 10510^5 candidates, but its precision collapses. AP reflects what a user of the detections sees.

Question 4

What removes duplicate detections in DETR?

  1. Non-maximum suppression after decoding
  2. Anchors with several aspect ratios
  3. The one-to-one bipartite matching in the loss, which trains every unmatched query to predict "no object"
  4. 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 ∅\varnothing. 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).