Sub topic 6
Two-stage detection: from R-CNN to Faster R-CNN
This chapter assumes you know how a CNN backbone produces a feature map, how anchors and box offsets work (the previous two chapters), and the basics of classification versus regression losses. It builds on those ideas to show how two-stage detectors work.
The two-stage idea
A two-stage detector splits detection into two questions:
- Where might an object be? The first stage proposes a few hundred or thousand class-agnostic boxes called region proposals.
- What is in each proposal, and how should the box be corrected? The second stage classifies each proposal and refines its coordinates.
The split lets the second stage focus on a small, filtered set of candidates. The cost is a more complex pipeline and a per-proposal computation that single-stage detectors skip. The R-CNN family is the history of removing that cost, one bottleneck at a time.
R-CNN: a CNN on every crop
R-CNN (2014) worked in four steps:
- Run selective search, a classical segmentation-based algorithm, to get about 2000 proposals per image.
- Crop each proposal and warp it to a fixed size, such as 227×227.
- Pass each crop through a CNN to get a feature vector.
- Classify the vector with per-class SVMs, and regress a box correction with a separate linear model.
This was accurate for its time but slow. Every proposal needed its own forward pass, so overlapping proposals recomputed the same pixels thousands of times. With a VGG-16 backbone, one image took roughly 47 seconds. Training was also awkward. The CNN, the SVMs, and the box regressors were trained in separate stages, and features were cached to disk.
Fast R-CNN: share the backbone
Fast R-CNN made one change that mattered most. It runs the backbone once on the whole image, then reads each proposal's features out of the shared feature map.
Proposals have different sizes, but the classifier head needs a fixed-size input. RoI pooling solves this. It maps the proposal onto the feature map by dividing its coordinates by the backbone stride, splits that region into a fixed grid such as 7×7, and max-pools each cell. Every proposal then becomes a 7×7×C tensor.
Fast R-CNN also replaced the SVMs and separate regressors with one head trained end to end. The head has two outputs, a softmax over K+1 classes (K object classes plus background) and four box offsets per class. The loss adds a classification term and a smooth-L1 box term. The box term applies only to proposals labeled as objects. Inference dropped to about 0.3 seconds per image, excluding proposals.
The remaining bottleneck was selective search. It ran on the CPU and took about two seconds per image, which was now much longer than the network itself.
Faster R-CNN: learn the proposals
Faster R-CNN replaces selective search with a small network, the Region Proposal Network (RPN), that sits on the same feature map as the detection head.
The RPN slides a 3×3 convolution over the backbone's feature map. At each position it uses k anchors. The original paper used 3 scales × 3 aspect ratios, so k = 9. Two sibling 1×1 convolutions then predict:
- an objectness score for each anchor (object or not), giving 2k outputs, or k with a sigmoid
- four box offsets for each anchor, giving 4k outputs, in the same encoding you saw in the previous chapter
Because the convolution is shared across positions, the RPN is cheap, and nearly all the compute stays in the backbone that both stages share.
Building the anchor grid
The code below generates the anchors for a 608×800 image with a stride-16 feature map (38×50 positions). Aspect ratio is height divided by width, and each anchor keeps area s².
import numpy as np
def base_anchors(scales=(128, 256, 512), ratios=(0.5, 1.0, 2.0)):
"""Anchors centered at the origin as (x1, y1, x2, y2)."""
out = []
for s in scales:
for r in ratios:
w = s / np.sqrt(r)
h = s * np.sqrt(r)
out.append((-w / 2, -h / 2, w / 2, h / 2))
return np.array(out)
def grid_anchors(base, fh, fw, stride):
"""Copy the base anchors to every feature-map cell center."""
xs = (np.arange(fw) + 0.5) * stride
ys = (np.arange(fh) + 0.5) * stride
cx, cy = np.meshgrid(xs, ys)
shifts = np.stack([cx, cy, cx, cy], axis=-1).reshape(-1, 1, 4)
return (shifts + base[None]).reshape(-1, 4)
anchors = grid_anchors(base_anchors(), fh=38, fw=50, stride=16)
print(anchors.shape) # (17100, 4)That is 38 × 50 × 9 = 17,100 anchors for one image.
Training and filtering the RPN
Each anchor gets a label from its IoU with the ground-truth boxes. An anchor with IoU above 0.7 with some ground-truth box, or the anchor with the highest IoU for a given box, is positive. An anchor with IoU below 0.3 with every box is negative. The rest are ignored. The assignment chapter covers these rules in detail. Two points matter here:
- Negatives far outnumber positives, so the RPN loss samples 256 anchors per image, with at most half of them positive.
- The RPN loss is a binary objectness term plus smooth-L1 regression on positive anchors only.
At inference the RPN proposals are cleaned up before the second stage:
- Decode every anchor with its predicted offsets and clip the boxes to the image.
- Discard tiny boxes.
- Keep the top-N by objectness, with N around 6000 in the original setup. Torchvision's default is 1000 per feature level at test time.
- Apply NMS, covered in its own chapter, to remove duplicates.
- Keep the top 300 to 2000 survivors as the final proposals.
The second stage
The surviving proposals go through RoI pooling on the shared feature map and then a small head with fully connected layers. The head classifies each proposal into K+1 classes and predicts class-specific box offsets that refine the box a second time. During training, the head samples about 128 proposals per image. It treats proposals with IoU ≥ 0.5 against a ground-truth box as foreground, up to 25% of the sample, and proposals with lower IoU as background.
The RPN is not a detector by itself, because its only classes are "object" and "not object". The second stage supplies the class label and a finer box. That two-step refinement is one reason two-stage detectors localize well.
RoIAlign
RoI pooling rounds the proposal to whole feature-map cells, and then rounds again when it splits the region into bins. At stride 16, one cell of rounding error is 16 pixels in the input image. This hurts small objects and masks. RoIAlign, introduced with Mask R-CNN, skips both roundings. It keeps fractional coordinates and samples each bin with bilinear interpolation. Modern implementations use it by default.
import torch
from torchvision.ops import roi_align
feat = torch.randn(1, 256, 38, 50) # (batch, channels, H, W), stride 16
# Each row: (batch_index, x1, y1, x2, y2) in input-image pixels.
rois = torch.tensor([[0, 64.0, 48.0, 320.0, 240.0]])
out = roi_align(feat, rois, output_size=(7, 7),
spatial_scale=1 / 16, sampling_ratio=2, aligned=True)
print(out.shape) # torch.Size([1, 256, 7, 7])spatial_scale converts image pixels to feature-map coordinates, and aligned=True applies the half-pixel correction that makes the sampling consistent.
Comparing the three
| Property | R-CNN | Fast R-CNN | Faster R-CNN |
|---|---|---|---|
| Proposal source | Selective search | Selective search | Learned RPN |
| Backbone passes per image | About 2000 | 1 | 1 |
| Feature extraction per proposal | Warped crop | RoI pooling | RoI pooling or RoIAlign |
| Training | Separate stages | End to end except proposals | RPN and head, shared backbone |
| Approximate time per image (VGG-16, GPU) | 47 s | 0.3 s plus proposals | about 0.2 s total |
Common errors and gotchas
- Coordinate units. RoI operations expect image-pixel boxes plus the correct
spatial_scale. Passing feature-map coordinates and also a scale shrinks the boxes twice. - Background in the head. The head has K+1 outputs. Dropping the background class makes every proposal look like an object.
- Regression on background. Box loss should be computed only for foreground samples. Including background proposals adds meaningless targets.
- Training the RPN and the head with different proposals. Gradients do not usually flow through the proposal coordinates. Treat the decoded proposals as constants for the second stage.
- Duplicate detections. Two-stage detectors still need NMS, both on the proposals and on the final per-class outputs.
Why two-stage detectors matter
Two-stage designs set the accuracy bar for years, and variants such as Mask R-CNN and Cascade R-CNN still serve as strong baselines. Their weakness is speed and complexity. The per-proposal head and the two NMS steps make them slower than single-stage detectors, which the next chapters cover.
Exercise
A 640×640 image goes through a backbone with stride 32, and the RPN uses 3 scales and 3 aspect ratios at each location. How many anchors does the RPN place, and why does Fast R-CNN run faster than R-CNN even though it classifies the same number of proposals?
Show answer
The feature map is 640/32 = 20 by 20, so there are 400 locations. With 9 anchors each, that gives 3600 anchors. Fast R-CNN is faster because it runs the backbone once on the whole image and extracts each proposal's features from the shared feature map with RoI pooling. R-CNN runs the full CNN separately on each of the roughly 2000 warped crops, so it repeats the same computation on overlapping regions.
Exercise
A proposal has coordinates (64, 48, 320, 240) in image pixels, and the backbone stride is 16. Which region of the feature map does RoI pooling or RoIAlign read, and why can RoIAlign be more accurate?
Show answer
Dividing each coordinate by 16 gives (4, 3, 20, 15) on the feature map. This example happens to land on whole cells. In general the result is fractional. RoI pooling rounds the region to whole cells, which can shift the box by up to one stride, 16 pixels in the image. RoIAlign keeps the fractional coordinates and samples with bilinear interpolation, so it avoids that quantization error.