6. Object Detection

R-CNN family, YOLO, SSD, anchor boxes, FPN, RetinaNet, focal loss, NMS, IoU, mAP

Contents
1. Problem Definition 2. Applications 3. Challenges 4. Bounding Box Regression 5. Two-Stage Detectors 6. Single-Stage Detectors 7. Anchor Boxes 8. Feature Pyramid Network (FPN) 9. RetinaNet and Focal Loss 10. Non-Maximum Suppression 11. Performance Evaluation 12. Detector Comparison Interactive: R-CNN Family Evolution Flashcards

1. Problem Definition

Object detection is one of the core problems in computer vision. Given an input image, the aim is to detect and localize all objects of interest within that image, outputting a list of detections where each detection consists of:

Classification vs. object detection
Image classification (left) assigns a single label to the whole image. Object detection (right) localizes multiple objects with bounding boxes, class labels, and confidence scores.

Two Families of Deep Learning Detectors

FamilyExamplesCharacteristics
Two-stageR-CNN, Fast R-CNN, Faster R-CNNFirst generate region proposals, then classify each. Higher accuracy, slower.
Single-stageSSD, YOLOPredict boxes and class scores in a single pass. Faster, sometimes slightly less accurate.
Key insight
Detection is always performed for a fixed set of target classes (e.g., 20 for PASCAL VOC, 80 for MS COCO). Everything outside these classes is treated as background. Like classifiers, detectors output a confidence score for each detection.

2. Applications of Object Detection

Object detectors can be used alone or combined with other techniques:

3. Challenges in Object Detection

ChallengeDescription
Viewpoint variationsThe same object looks different when viewed from different angles
Object deformationNon-rigid objects change shape (person sitting vs. standing)
OcclusionsObjects may be partially hidden; detector must still recognize them
Varying illuminationChanges in lighting alter object appearance
Background clutterComplex backgrounds can confuse the detector
Scale variationsObjects appear at vastly different sizes (person far vs. near)
Intra-class variationObjects within the same class look very different (dog breeds)
Inter-class similarityDifferent classes can look similar (wolf vs. husky)

4. Object Localization and Bounding Box Regression

Bounding Box Formats

Adding a Regression Head

To predict bounding box coordinates, a CNN classifier is extended with 4 regression outputs in addition to the class scores:

Combined classifier and bounding box regressor
Multi-task network: CNN backbone feeds into both a classification head (softmax, $C$ class scores) and a bounding box regression head (4 coordinate values).
Bounding Box Regression Loss
The network predicts all four bounding box coordinates and minimizes the sum of squared errors against ground-truth coordinates: $$L_{\text{bbox}} = \sum_{i \in \{x_1, y_1, x_2, y_2\}} (i_{\text{pred}} - i_{\text{GT}})^2$$ The overall multi-task loss combines classification and regression: $$L = L_{\text{cls}} + \lambda \cdot L_{\text{reg}}$$
Bounding box regression training
Bounding box regression training: the network predicts 4 coordinate values; L2 loss measures the difference from ground truth coordinates.

5. Two-Stage Object Detectors

Two-stage detectors split detection into two phases: (1) Region Proposal — generate candidate regions that might contain objects, then (2) Classification and Refinement — for each proposed region, classify the object and refine the bounding box.

5.1 R-CNN (2014)

R-CNN (Girshick et al.) was the first successful deep learning object detector.

R-CNN pipeline
R-CNN pipeline: (1) input image, (2) ~2000 region proposals via Selective Search, (3) CNN feature extraction per proposal, (4) SVM classification + bbox regression + NMS.
R-CNN architecture
R-CNN architecture: each proposal is independently warped to fixed size and passed through an ImageNet-pretrained CNN.

Selective Search

Selective Search generates ~2000 region proposals per image:

  1. Over-segment the image based on pixel intensities (watershed).
  2. Iteratively group adjacent segments by similarity (color, texture, size, shape).
  3. At each iteration, add bounding boxes of merged segments to the proposal list.
  4. This creates proposals from small to large in a bottom-up hierarchical approach.
Selective search region merging
Selective search: initial over-segmentation is iteratively merged into larger regions, generating proposals at multiple scales.
R-CNN training details

Training has three separate stages: (1) Fine-tune the CNN backbone (AlexNet/VGG) using proposals with IoU ≥ 0.5 as positives. (2) Train a linear SVM per class on the CNN features. (3) Train bounding box regressors. This multi-stage training is cumbersome. Speed: ~0.05 fps (20 seconds per image).

R-CNN bottleneck
Each of the ~2000 proposals must be independently forward-passed through the CNN. That is ~2000 CNN runs per image, making R-CNN extremely slow (~20 seconds/image, ~0.05 fps).

5.2 Fast R-CNN (2015)

Fast R-CNN (Girshick) addresses the R-CNN speed bottleneck with one key insight: pass the whole image through the CNN once, then extract features per proposal from the shared feature map.

Fast R-CNN architecture
Fast R-CNN: the full image passes through CNN once to produce a shared feature map. RoI Pooling extracts fixed-size features for each proposal from the shared map.
RoI Pooling
For each proposal, map it onto the shared feature map, divide it into a fixed grid (e.g., $7 \times 7$), and max-pool within each grid cell. This produces a fixed-size feature vector regardless of the proposal's original size, which is required by the subsequent FC layers.
AspectR-CNNFast R-CNN
CNN runs per image~20001
Training3-stageEnd-to-end (single stage)
ClassifierLinear SVMSoftmax (joint)
Speed~0.05 fps~0.5 fps (10x faster)

Remaining bottleneck: Selective Search still runs on CPU and takes ~2 seconds per image, dominating total runtime.

5.3 Faster R-CNN (2015)

Faster R-CNN (Ren et al.) eliminates the Selective Search bottleneck by introducing a learned Region Proposal Network (RPN) that shares the backbone feature maps with the detection head.

Faster R-CNN overview
Faster R-CNN: RPN generates proposals from shared feature maps, eliminating the CPU-bound Selective Search. RPN and detection head share the same backbone.

Region Proposal Network (RPN)

RPN anchor boxes
RPN sliding window: at each position on the feature map, the RPN outputs $2k$ objectness scores and $4k$ bounding box coordinates for $k$ anchors of different shapes.
Faster R-CNN RPN Multi-Task Loss
$$L(\{p_i\}, \{t_i\}) = \frac{1}{N_{\text{cls}}} \sum_i L_{\text{cls}}(p_i, p_i^*) + \lambda \frac{1}{N_{\text{reg}}} \sum_i p_i^* \cdot L_{\text{reg}}(t_i, t_i^*)$$ $p_i$ = predicted objectness probability, $p_i^*$ = ground truth label (1 if positive anchor, 0 if negative), $t_i$ = predicted box offsets, $t_i^*$ = ground truth box targets, $L_{\text{cls}}$ = log loss (classification), $L_{\text{reg}}$ = smooth L1 loss (only for positive anchors via $p_i^*$ multiplier), $\lambda = 10$ balances the two losses.
Faster R-CNN full pipeline
Full Faster R-CNN pipeline: CNN backbone → RPN (proposals) → RoI Pooling on shared feature map → FC layers → classification + bbox regression heads.

Speed: ~7 fps (140 ms/image) — near real-time and ~140x faster than the original R-CNN.

5.4 Mask R-CNN (2017)

Mask R-CNN (He et al.) extends Faster R-CNN to simultaneously perform instance segmentation in addition to object detection.

Mask R-CNN architecture
Mask R-CNN: extends Faster R-CNN with RoI Align (replaces RoI Pooling) and an additional mask prediction branch that outputs per-class binary masks.
RoI Pooling vs. RoI Align
RoI Pooling quantizes (rounds) floating-point proposal coordinates to integer feature map positions, causing spatial misalignment.
RoI Align uses bilinear interpolation to compute exact values at fractional positions, preserving precise spatial alignment. Improves detection mAP by ~3 points even without segmentation.
RoI Pooling quantization problem
RoI Pooling: snapping floating-point coordinates to integer grid positions causes spatial misalignment, which is tolerable for classification but harmful for pixel-level segmentation.
RoI Align with bilinear interpolation
RoI Align: bilinear interpolation computes exact feature values at fractional positions, preserving precise spatial alignment needed for the mask branch.

Mask R-CNN outputs three predictions per RoI: class label, refined bounding box, and a binary segmentation mask ($14 \times 14 \times C$ for $C$ classes).

Mask R-CNN head detail
Mask R-CNN head: RoI features branch into (1) classification + box regression head via average pooling, and (2) mask head via upsampling with a 1×1 conv producing one mask per class.

5.5 R-FCN (2016)

R-FCN addresses the per-RoI FC layer computation bottleneck of Faster R-CNN using position-sensitive RoI Pooling.

Position-Sensitive Score Maps
The last conv layer produces $k^2 \times (C+1)$ channels: for $k=3$, $C=10$, that is $9 \times 11 = 99$ channels. Each group of 9 channels per class learns to detect a specific spatial position (top-left, top-center, ..., bottom-right) of that object class.
R-FCN position-sensitive RoI pooling
R-FCN: 90 position-sensitive score maps (10 classes × 9 spatial positions) encode where object parts appear. For each RoI, each grid cell pools from its corresponding position-specific map.

Advantage: all heavy computation is shared in conv layers. Per-RoI computation is just lightweight pooling and voting — making R-FCN faster than Faster R-CNN for large numbers of proposals.

6. Single-Stage Object Detectors

Single-stage detectors skip the separate region proposal step entirely. They predict bounding boxes and class scores directly from feature maps in a single forward pass, enabling real-time detection.

6.1 SSD (Single Shot MultiBox Detector, 2016)

SSD (Liu et al.) uses multi-scale feature maps and predefined anchor boxes to detect objects at different sizes in a single forward pass.

SSD multi-scale concept
SSD multi-scale concept: smaller feature maps (deeper layers, larger receptive field) detect larger objects; larger feature maps (earlier layers, smaller receptive field) detect smaller objects.

Architecture:

  1. Base network: VGG-16 (up to conv5_3), FC layers replaced by extra conv layers.
  2. 6 prediction layers at different spatial resolutions (multi-scale).
  3. At each scale, for every spatial position, two $3 \times 3$ conv layers predict class scores and box offsets for each anchor.
  4. All predictions across scales go through NMS to produce final detections.
SSD architecture
SSD architecture: VGG-16 base network followed by extra feature layers, with predictions made at 6 different spatial scales.

Performance: 74.3 mAP on VOC2007 at 59 FPS (17 ms/image).

6.2 YOLO (You Only Look Once, 2016)

YOLO (Redmon et al.) frames object detection as a single regression problem: directly predict bounding boxes and class probabilities from the full image in one evaluation.

YOLO grid diagram
YOLO divides the image into an $S \times S$ grid. Each cell predicts $B$ bounding boxes with confidence scores and $C$ class probabilities.
YOLO Output Structure
Grid: $S = 7$, boxes: $B = 2$, classes: $C = 20$ (PASCAL VOC).
Per cell: $B \times 4$ box coordinates + $B$ confidence scores + $C$ class probabilities = $2 \times 4 + 2 + 20 = \mathbf{30}$ values.
Total output: $7 \times 7 \times 30 = \mathbf{1470}$ values.
Confidence = $P(\text{Object}) \times \text{IoU}(\text{pred}, \text{GT})$.
YOLO full architecture
YOLO architecture: 24 conv layers (GoogLeNet-inspired, alternating 1×1 and 3×3) progressively reduce spatial resolution, followed by 2 FC layers producing the $7 \times 7 \times 30$ output tensor.
AspectSSDYOLO v1
Feature maps used6 scalesSingle final map
Output headConv layers at each scaleFC layers on single map
Multi-scale handlingExcellent (natural)Limited (coarse 7×7 grid)
mAP (VOC2007)74.363.4–69.0
Speed59 fps45 fps

7. Anchor Boxes

Anchor boxes (also called "priors" or "default boxes") are a fundamental concept used in both two-stage (Faster R-CNN) and single-stage (SSD, RetinaNet) detectors.

Anchor Boxes
Predefined bounding boxes of fixed shapes and sizes placed at every spatial position on a feature map. The network predicts offsets relative to each anchor — not absolute coordinates from scratch.
Anchor boxes illustration
Anchor boxes: predefined boxes of various aspect ratios and scales are tiled across the image at each spatial position. The detector predicts offsets to transform these templates into accurate bounding boxes.

Offset parameterization:

Typical configurations:

8. Feature Pyramid Network (FPN)

CNNs naturally produce feature maps at multiple scales. Deeper layers have smaller spatial resolution but richer semantics; earlier layers have higher spatial resolution but weaker semantics. FPN combines the best of both.

FPN approach comparison
Comparison of feature pyramid approaches: (a) image pyramid — accurate but extremely slow; (b) single feature map — fast but misses small objects; (c) pyramidal hierarchy — inconsistent semantic strength; (d) FPN — best of both worlds.

FPN Architecture

  1. Bottom-up pathway: Standard CNN forward pass. Feature maps at each stage: $C_2, C_3, C_4, C_5$ (high to low resolution).
  2. Top-down pathway: Starting from deepest $C_5$: 2× upsample → element-wise add with lateral $1 \times 1$ conv of corresponding $C_k$ → produces $P_2, P_3, P_4, P_5$.
  3. Predictions are made independently at each pyramid level $P_k$.
FPN architecture detail
FPN detail: bottom-up encoder (left) with top-down decoder using 2× upsampling and 1×1 lateral connections. Element-wise addition merges semantic richness (from deep) with spatial precision (from shallow).
FPN Pyramid Level Selection
For a given RoI of width $w$ and height $h$: $$k = \lfloor k_0 + \log_2(\sqrt{wh} / 224) \rfloor$$ where $k_0 = 4$ (reference level for a $224 \times 224$ RoI). Small objects use high-resolution levels ($P_2, P_3$); large objects use low-resolution levels ($P_4, P_5$).
FPN with RPN
FPN with Faster R-CNN: RPN is run on all pyramid levels $P_2, \ldots, P_5$. Only one anchor scale is needed per level since different levels naturally handle different object sizes.

9. RetinaNet and Focal Loss

RetinaNet (Lin et al., 2017) is a single-stage detector that matches or exceeds two-stage detector accuracy through two innovations: an FPN-based architecture and focal loss.

The Class Imbalance Problem

Single-stage detectors evaluate 10,000–100,000 candidate locations per image. The vast majority are background (easy negatives), creating severe class imbalance that causes easy examples to dominate training gradients, preventing the network from learning to detect hard examples.

Focal Loss
Standard cross-entropy: $$CE(p_t) = -\log(p_t)$$ Focal loss adds a modulating factor $(1-p_t)^\gamma$: $$FL(p_t) = -(1-p_t)^\gamma \cdot \log(p_t)$$ where $\gamma = 2$ in the RetinaNet paper. For well-classified examples ($p_t$ near 1), the factor is near 0, drastically reducing their loss contribution. For hard examples ($p_t$ near 0), the factor is near 1, keeping the loss unchanged.
Focal loss curves
Focal loss curves for different values of $\gamma$. As $\gamma$ increases, the contribution of well-classified easy examples is progressively down-weighted, allowing the network to focus on hard, misclassified examples.
Focal loss intuition
When $\gamma = 0$: focal loss = standard cross-entropy. As $\gamma$ increases, easy examples matter less. At $\gamma = 2$, a well-classified example with $p_t = 0.9$ has its loss reduced by $(1-0.9)^2 = 0.01$ compared to CE — 100× less contribution. Hard examples with $p_t = 0.1$ are unaffected.

RetinaNet Architecture

FPN backbone + two shared subnets applied at every pyramid level:

10. Non-Maximum Suppression (NMS)

NMS is a post-processing algorithm used by virtually all object detectors to remove redundant overlapping detections of the same object.

NMS Algorithm
  1. Sort all detections by confidence score (highest first).
  2. Select the highest-confidence detection; add to the output list.
  3. Compute IoU of this detection with all remaining detections.
  4. Delete all detections whose IoU with the selected detection exceeds a threshold (e.g., 0.5).
  5. Repeat from step 2 with the remaining detections.
NMS is applied independently for each class.

Key parameters:

11. Performance Evaluation

11.1 Intersection over Union (IoU)

IoU (Jaccard Index)
$$\text{IoU} = \frac{\text{Area of Intersection}}{\text{Area of Union}} = \frac{|B_{\text{pred}} \cap B_{\text{GT}}|}{|B_{\text{pred}} \cup B_{\text{GT}}|}$$ Range: $[0, 1]$. IoU = 1 means perfect overlap. IoU ≥ 0.5 is commonly used as the threshold for a True Positive.

Example: Predicted box area = 100, GT box area = 150, intersection = 80. Union = 100 + 150 − 80 = 170. IoU = 80/170 ≈ 0.47. Since 0.47 < 0.5, this would be a False Positive at IoU threshold 0.5.

IoU is used in three contexts:

11.2 Mean Average Precision (mAP)

mAP is the most widely used metric for evaluating object detectors, based on the Area Under the Precision-Recall Curve.

mAP Computation
For each class independently:
  1. Sort all detections by confidence (highest first).
  2. For each detection: check if it matches any remaining GT box with IoU > threshold. If yes: True Positive (TP), mark that GT used. If no: False Positive (FP).
  3. After each detection: Precision = TP/(TP+FP), Recall = TP/total GT.
  4. Average Precision (AP) = area under the Precision-Recall curve.
$\text{mAP} = \frac{1}{C} \sum_{c=1}^{C} \text{AP}_c$

Worked Example

5 detections for class "cat" (sorted by confidence: 0.98, 0.96, 0.90, 0.30, 0.10), 4 ground truths:

Detection (conf.)Match?Cumul. TPCumul. FPPrecisionRecall
0.98Yes101/1 = 1.001/4 = 0.25
0.96No111/2 = 0.501/4 = 0.25
0.90Yes212/3 = 0.672/4 = 0.50
0.30Yes313/4 = 0.753/4 = 0.75
0.10Yes414/5 = 0.804/4 = 1.00

AP for "cat" = area under the curve formed by these (Recall, Precision) points.

MetricIoU ThresholdUsed InDifficulty
mAP@0.50.5PASCAL VOCStandard
mAP@0.750.75COCOStricter
mAP@[0.5:0.95]0.5 to 0.95 step 0.05MS COCOMost challenging

12. Detector Comparison

MethodTypeVOC2007 mAPSpeed (FPS)Speed (ms/img)
DPM v5Traditional33.70.0714,000
R-CNNTwo-stage66.00.0520,000
Fast R-CNNTwo-stage70.00.52,000
Faster R-CNNTwo-stage73.27140
YOLOSingle-stage63.4–69.04522
SSDSingle-stage74.35917
Detector performance comparison scatter
mAP vs. GPU time scatter plot for various detectors and backbones. The accuracy-speed trade-off is clear: two-stage detectors (upper-left) are slower but accurate; single-stage (lower-right) are faster.
Detector performance timeline
COCO test-dev mAP progression 2015–2024. Continuous improvement from Fast R-CNN (~20 mAP) to modern transformer-based models (~63–65 mAP).

Two-Stage vs. Single-Stage Trade-offs

AspectTwo-StageSingle-Stage
SpeedSlower (140+ ms)Faster (17–22 ms, real-time)
AccuracyGenerally higherHistorically lower, now competitive
Pipeline complexityMulti-componentSimpler, single pass
Class imbalanceHandled by RPN filteringMajor issue (addressed by focal loss)
Use caseWhen accuracy is paramountWhen speed is critical (real-time)
Supplementary: Sliding Window Approach (pre-deep-learning)

Before deep learning detectors, a common approach was to slide a fixed-size window across the image and classify each patch. Problems: (1) fixed window size forces use of image pyramids for scale variation; (2) localization ambiguity requires NMS; (3) enormous number of windows makes it computationally prohibitive. These problems motivated Selective Search (for R-CNN) and eventually end-to-end learned detectors.

Supplementary: Watershed Over-Segmentation (used in Selective Search)

Watershed produces the initial over-segmentation used by Selective Search in R-CNN/Fast R-CNN: (1) compute gradient image; (2) find local minima as region seeds; (3) simulate "flooding" from each minimum; (4) pixels at watershed boundaries (touching two+ regions) become boundaries. Camera noise produces many local minima, causing over-segmentation — which is desired, as Selective Search then merges these small segments bottom-up.

Flashcards