AI Logic

Architectures

R-CNN

Updated:

Architecture of R-CNN. Left: the flow at test time, which extracts about 2,000 candidate regions from the input image with Selective Search, warps each candidate to 227×227 and passes it through a CNN (AlexNet), scores the 4096-dimensional feature with per-class linear SVMs, and produces detections with non-maximum suppression. Right: the four training stages, namely pretraining on ImageNet, fine-tuning on candidate regions, per-class linear SVMs, and bounding-box regression from pool5 features

Background and overview

R-CNN (Regions with CNN features) is an object detection method that extracts about 2,000 candidate regions likely to contain objects from an image, passes each through a CNN to compute features, and uses per-class classifiers to decide what is in each region. It was introduced in 2013 by Girshick et al. at UC Berkeley (CVPR 2014) and became one of the first methods to greatly improve object detection accuracy by using CNNs.

Object detection is the task of finding objects in an image and reporting their class and location (bounding box). In 2012, AlexNet achieved a major success in image classification on ImageNet, but it was unclear whether the strength of classification, which assigns one label to a whole image, would carry over to detection, which must also report object locations. R-CNN answered this with the approach of "cut out candidate regions, then classify them with a CNN".

The main results of the paper are as follows.

  • On the PASCAL VOC 2012 test set, it reached an mAP of 53.3%, more than 30% relative above the previous best result.
  • On PASCAL VOC 2010, it reached 53.7%, compared with 35.1% for a previous method using the same candidate regions.
  • On the 200-class ILSVRC2013 detection task, it reached 31.4%, beating OverFeat (24.3%), which uses a CNN in a sliding-window fashion.

R-CNN's pipeline of "candidate regions → per-region CNN features → classification and box refinement" was inherited by Fast R-CNN, Faster R-CNN, and Mask R-CNN, and became the starting point of the family known as "two-stage detectors".

The problem: using classification CNNs for object detection

R-CNN tackled two problems: how to localize objects with a CNN and how to train a large CNN with little detection data.

Localization: Unlike classification, detection must report the locations of (usually several) objects in an image. The paper points out the difficulties of two approaches considered at the time.

  • Regressing locations directly: Concurrent work by Szegedy et al. reached only 30.5% mAP on PASCAL VOC 2007 (R-CNN: 58.5%).
  • Sliding windows (scanning the whole image while shifting a window): In the five-convolutional-layer CNN used by R-CNN, a single unit in the top layer sees 195×195 pixels of the input, with a stride of 32 pixels. The paper states that obtaining precise locations at this coarseness is difficult.

R-CNN took neither approach and instead adopted the idea of "recognition using regions". Regions likely to contain objects are selected beforehand by a separate method, and the CNN only has to say what each region is.

Scarce data: Data labeled with detection boxes is far scarcer than classification data and is not enough to train a large CNN from scratch. R-CNN trained the CNN on ImageNet classification, which has many labels, and then fine-tuned it on the detection data. Fine-tuning raised mAP by 8 points.

Theory: the detection procedure and bounding-box regression

R-CNN consists of three components: a part that produces candidate regions, a CNN that extracts features from regions, and per-class linear SVMs (support vector machines). In the figure at the top of the article, the left side shows the flow at test time and the right side shows the training stages.

At test time, each image is processed as follows.

  1. Extract about 2,000 class-agnostic candidate regions with Selective Search (a training-free method that successively merges small regions with similar color and texture).
  2. Warp each candidate region to 227×227 pixels, ignoring its aspect ratio. Before cropping, the box is enlarged slightly so that the warped image includes 16 pixels of surrounding context.
  3. Pass the warped image through the CNN (nearly the same as AlexNet, with 5 convolutional layers and 2 fully connected layers) and extract a 4096-dimensional feature vector.
  4. Score the feature vector with linear SVMs trained for each class.
  5. Apply non-maximum suppression (NMS) per class. Boxes are kept in descending order of score, and boxes whose IoU (the ratio of overlap between two boxes) with a kept box exceeds a threshold are removed, merging duplicate detections of the same object into one.

The SVM in step 4 just takes the inner product of the feature vector with the class weights. For one image, the scores for all classes come from a single product of the 2000×4096 feature matrix and the 4096×NN weight matrix (NN is the number of classes).

Bounding-box regression: Candidate regions are often offset from the object, so detected boxes are refined by per-class linear regression. Given a candidate box P=(Px,Py,Pw,Ph)P = (P_x, P_y, P_w, P_h) (center coordinates, width, and height), the refined box G^\hat{G} is computed as follows.

G^x=Pw dx(P)+Px,G^y=Ph dy(P)+Py\hat{G}_x = P_w\, d_x(P) + P_x, \quad \hat{G}_y = P_h\, d_y(P) + P_y G^w=Pwexp⁡(dw(P)),G^h=Phexp⁡(dh(P))\hat{G}_w = P_w \exp(d_w(P)), \quad \hat{G}_h = P_h \exp(d_h(P))

d⋆(P)d_\star(P) (where ⋆\star is one of x,y,w,hx, y, w, h) is a linear function d⋆(P)=w⋆⊤ϕ5(P)d_\star(P) = \mathbf{w}_\star^\top \phi_5(P) of the feature ϕ5(P)\phi_5(P) from the output of the CNN's last max pooling layer (pool5, 6×6×256). The center is shifted in units of the box's width and height, and the width and height are shifted in log space, so large and small boxes can be refined with the same weights. The regression targets for a ground-truth box GG are as follows.

tx=Gx−PxPw,ty=Gy−PyPh,tw=log⁡GwPw,th=log⁡GhPht_x = \frac{G_x - P_x}{P_w}, \quad t_y = \frac{G_y - P_y}{P_h}, \quad t_w = \log\frac{G_w}{P_w}, \quad t_h = \log\frac{G_h}{P_h}

The weights w⋆\mathbf{w}_\star are found by regularized least squares (ridge regression).

w⋆=argmin⁡w^⋆∑iN(t⋆i−w^⋆⊤ϕ5(Pi))2+λ∥w^⋆∥2\mathbf{w}_\star = \underset{\hat{\mathbf{w}}_\star}{\operatorname{argmin}} \sum_{i}^{N} \left(t_\star^i - \hat{\mathbf{w}}_\star^\top \phi_5(P^i)\right)^2 + \lambda \left\lVert \hat{\mathbf{w}}_\star \right\rVert^2

The paper chooses λ=1000\lambda = 1000 on validation data. This box parameterization (tx,ty,tw,tht_x, t_y, t_w, t_h) is used as is in later detectors, such as the RPN of Faster R-CNN.

Bounding-box regression is trained only on candidates whose IoU with some ground-truth box exceeds 0.6. Transforming a candidate far from every object into a ground-truth box is an ill-posed problem that would hinder training.

Training procedure: four stages

R-CNN training runs CNN pretraining, CNN fine-tuning, SVM training, and bounding-box regression training as separate stages in sequence.

  1. Pretraining: Train the CNN on ILSVRC2012 image classification (1,000 classes). No box labels are used, only image-level labels.
  2. Fine-tuning: Replace the final 1,000-class classification layer with a randomly initialized layer for N+1N+1 classes (NN object classes plus background), and continue training with SGD on warped candidate regions only.
    • Candidates with IoU of 0.5 or more with a ground-truth box are positives for that class. All others are background.
    • The learning rate starts at 0.001, 1/10 of the initial pretraining rate, so that the pretrained weights are adjusted without being destroyed.
    • Each mini-batch has 128 samples, uniformly drawing 32 positives and 96 background regions. Since background is far more common, positives are oversampled.
  3. SVM training: Freeze the CNN, extract features from the last fully connected layer (fc7), and train a linear SVM per class.
    • Positives are only the ground-truth boxes, and negatives are candidates with IoU below 0.3 with every ground truth of that class. Candidates in between are not used.
    • Because there are too many features to fit in memory, a method that trains while reselecting hard-to-classify negatives (hard negative mining) is used. mAP stops improving after a single pass over all images.
  4. Bounding-box regression training: Using the equations in the previous section, learn box refinement from pool5 features for each class.

According to the paper, the different definitions of positives for fine-tuning and for the SVMs are historical. Initially, SVMs were trained on features from the CNN with pretraining only, and the best definition there was IoU 0.3. Using the same definition for fine-tuning gave much worse results, so positives were defined as IoU 0.5 or more, increasing them by about 30 times. The paper believes this many positives were needed to train the whole CNN with little data.

The IoU threshold that defines SVM negatives has a large effect on results. The paper compared values from 0 to 0.5 on validation data and chose 0.3; setting it to 0.5 lowered mAP by 5 points, and setting it to 0 lowered it by 4 points. When the data or classes change, the threshold must be reselected on validation data.

Using the final softmax (21 classes) of the fine-tuned CNN directly as the classifier lowered mAP on PASCAL VOC 2007 from 54.2% to 50.9%. The paper attributes this to the fine-tuning positives not emphasizing precise localization and to softmax training not selecting hard negatives. The later Fast R-CNN closed this gap without using SVMs.

Why accuracy improves

Based on the paper's analysis, the reasons R-CNN greatly outperformed previous methods can be summarized in three points.

  • Features learned by a CNN are stronger than hand-designed features: Detectors at the time used features such as SIFT and HOG, which are distributions (histograms) of edge orientations in small cells of the image. CNN features, built by stacking many convolutions, capture more abstract shapes and object parts. The paper examined pool5 units one by one and showed that some units respond to faces, text, dot patterns, and so on.
  • Features learned for classification are adapted to detection: The effect of fine-tuning was large in the fully connected layers (fc6, fc7) and small at pool5. The paper suggests that convolutional features learned on ImageNet are general, and that adaptation to detection mainly happens in the fully connected layers.
  • Selecting regions first keeps the CNN's coarseness from being a problem: The CNN only answers "what this region is", and locations are determined by candidate regions and bounding-box regression. Most offsets can be corrected by bounding-box regression. In the paper's error analysis, localization errors were the most common, and bounding-box regression raised mAP by 3 to 4 points.

As an everyday analogy, when looking for people in a photo, instead of scanning the whole photo bit by bit, you first put sticky notes on "places where something seems to be" and then check each note with a magnifying glass.

The paper also compares ways of cropping regions. Warping while ignoring the aspect ratio and including 16 pixels of surrounding context beat cropping squares that preserve the aspect ratio by 3 to 5 points of mAP.

Experimental results

PASCAL VOC 2007 test: which layer's features to use, and the effects of fine-tuning and bounding-box regression (mAP %, AlexNet-style CNN)

SettingFine-tuningBox regressionmAP
pool5 featuresNoNo44.2
fc6 featuresNoNo46.2
fc7 featuresNoNo44.7
pool5 featuresYesNo47.3
fc6 featuresYesNo53.1
fc7 featuresYesNo54.2
fc7 featuresYesYes58.5
(Reference) DPM v5 (HOG features)――33.7

Fine-tuning raised mAP by 8 points, from 46.2% to 54.2%, and bounding-box regression added another 4.3 points. Compared with DPM v5, the representative HOG-based detector of the time, the gap is more than 20 points.

PASCAL VOC 2007 test: comparison of CNNs (mAP %)

CNNWithout box regressionWith box regression
AlexNet-style (T-Net in the paper)54.258.5
VGG-16 (O-Net in the paper)62.266.0

Switching to VGG-16 raised mAP to 66.0%, but the CNN forward pass took about 7 times longer.

PASCAL VOC 2010 test (mAP %. UVA and Regionlets use the same Selective Search candidates as R-CNN)

MethodmAP
DPM v533.4
UVA35.1
Regionlets39.7
SegDPM40.4
R-CNN50.2
R-CNN (with box regression)53.7

On the ILSVRC2013 detection test (200 classes), R-CNN (with box regression) reached an mAP of 31.4%, beating the previous best, OverFeat, at 24.3%.

Caveats in practice

Keep the following points in mind when using or reproducing R-CNN.

  • Slow, because every candidate region passes through the CNN: With the paper's AlexNet-style CNN, computing candidate regions and features takes 13 seconds per image on a GPU (53 seconds on a CPU). In measurements in the Fast R-CNN paper, VGG-16 took 47 seconds per image on a GPU. This is because convolutions over the same pixels are computed again and again for about 2,000 overlapping regions.
  • Multi-stage training consumes lots of disk space and time: To train the SVMs and box regressors, the features of all candidates are extracted and saved to disk. According to the Fast R-CNN paper, with VGG-16, extracting features for the PASCAL VOC 2007 training data (about 5,000 images) took 2.5 GPU-days and required hundreds of gigabytes of storage.
  • Each stage has its own objective, so the whole pipeline cannot be optimized jointly: The CNN is trained with softmax, classification with SVMs, and boxes with a separate regression. The CNN features are not adjusted based on the errors of the SVMs or the box regressors.
  • The quality of candidate regions sets an upper bound: Objects that Selective Search does not propose cannot be found in later stages.

If you are building a new object detection model today, it is more practical to use implementations of Faster R-CNN or Mask R-CNN (available in torchvision and elsewhere), which follow the same idea but share computation, rather than R-CNN itself. R-CNN is best read to understand the mechanism or to reproduce the paper's results.

Comparison with other methods

After R-CNN came methods that kept the same "candidate regions → per-region features → classification and box refinement" structure while replacing the slow parts one by one. Lined up along the same axes, they look like this (times are from each paper and are only rough guides, since the GPUs differ).

MethodCandidate regionsHow candidate features are extractedOutputDetection time per image (paper values)
R-CNNSelective Search (about 2,000)Crop the image for each candidate and pass it through the CNNClass and box13 s (AlexNet-style), 47 s (VGG-16)
SPP-netSelective SearchSpatial pyramid pooling from the feature map of the whole imageClass and box10–100 times faster than R-CNN
Fast R-CNNSelective SearchRoI pooling from the feature map of the whole imageClass and box0.32 s + about 1.5 s for candidate regions (VGG-16)
Faster R-CNNRPN (shares the feature map, 300 regions)RoI poolingClass and box0.198 s (VGG-16)
Faster R-CNN + FPNRPN on each level of the feature pyramidSelect a level by RoI size, then RoI poolingClass and box0.148 s (ResNet-50)
Mask R-CNNRPN (with FPN)RoIAlignClass, box, and mask0.195 s (ResNet-101-FPN)

The sequence of replacements is as follows.

  • SPP-net and Fast R-CNN: Removed R-CNN's heaviest part (per-region CNNs) by computing convolutions over the whole image only once and cropping per-region features on the feature map. Fast R-CNN also merged the SVMs and box regression into the outputs of a single network, enabling single-stage training.
  • Faster R-CNN: Replaced the remaining Selective Search (about 1.5 seconds per image on a CPU) with a network that shares the feature map (RPN).
  • FPN and Mask R-CNN: Added handling of objects of different sizes (FPN) and prediction of object shape masks (Mask R-CNN).

Rough guidelines for choosing a method:

  • To learn the ideas behind two-stage detectors: Reading in order from R-CNN makes it easier to see what each method solved.
  • To actually use box detection: Faster R-CNN (with FPN) is the standard choice with a good balance of accuracy and speed.
  • When object outlines are needed: Use Mask R-CNN.
  • When speed is the top priority: One-stage detectors without a candidate region stage (such as YOLO and SSD) are also candidates.

PyTorch example

Show code
python
import torch
import torch.nn as nn
from torchvision.models import alexnet, AlexNet_Weights
from torchvision.ops import roi_align, batched_nms, box_iou

'''
A small PyTorch example of R-CNN's detection procedure (Sections 2.1-2.2 of the paper) and bounding-box regression (Eqs. (1)-(9) in Appendix C).
Candidate regions (Selective Search) are not in PyTorch, so it takes ones created with, e.g., OpenCV's ximgproc.
'''

device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'
num_classes = 20             # number of PASCAL VOC object classes N (excluding background)
input_size, context = 227, 16  # CNN input size and number of context pixels p to include around


def warp_regions(image, boxes):
  """Warp candidate regions to 227×227 with p pixels of surrounding context (aspect ratio not preserved).
  image: mean-subtracted image [3, H, W]. boxes: [R, 4] (x1, y1, x2, y2)"""
  scale = input_size / (input_size - 2 * context)   # enlarge the box so that 16 pixels of margin remain after warping
  cx, cy = (boxes[:, 0] + boxes[:, 2]) / 2, (boxes[:, 1] + boxes[:, 3]) / 2
  w, h = (boxes[:, 2] - boxes[:, 0]) * scale, (boxes[:, 3] - boxes[:, 1]) * scale
  grown = torch.stack([cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2], dim=1)
  # outside the image is 0 (same as the paper's "fill with the image mean", since the mean is subtracted)
  rois = torch.cat([torch.zeros(len(grown), 1, device=grown.device), grown], dim=1)
  return roi_align(image[None], rois, output_size=(input_size, input_size), sampling_ratio=1, aligned=True)


class RCNNFeatures(nn.Module):
  """Extract pool5 (for box regression) and fc7 (for SVMs, 4096-dim) features with AlexNet"""
  def __init__(self):
    super().__init__()
    net = alexnet(weights=AlexNet_Weights.IMAGENET1K_V1)   # weights pretrained on ImageNet
    self.conv = net.features                               # 5 conv layers (max pooling at the end)
    self.pool = net.avgpool                                # resize to 6×6
    self.fc = net.classifier[:-1]                          # fc6, fc7 (drop the final 1000-class layer)

  def forward(self, x):
    pool5 = torch.flatten(self.pool(self.conv(x)), 1)      # [R, 9216]
    return pool5, self.fc(pool5)                           # fc7: [R, 4096]


def encode(proposals, gt):
  """Regression targets t (Eqs. (6)-(9)). Boxes are (x1, y1, x2, y2)"""
  pw, ph = proposals[:, 2] - proposals[:, 0], proposals[:, 3] - proposals[:, 1]
  px, py = proposals[:, 0] + pw / 2, proposals[:, 1] + ph / 2
  gw, gh = gt[:, 2] - gt[:, 0], gt[:, 3] - gt[:, 1]
  gx, gy = gt[:, 0] + gw / 2, gt[:, 1] + gh / 2
  return torch.stack([(gx - px) / pw, (gy - py) / ph, torch.log(gw / pw), torch.log(gh / ph)], dim=1)


def decode(proposals, d):
  """Refined boxes (Eqs. (1)-(4)). d: [R, 4] (d_x, d_y, d_w, d_h)"""
  pw, ph = proposals[:, 2] - proposals[:, 0], proposals[:, 3] - proposals[:, 1]
  px, py = proposals[:, 0] + pw / 2, proposals[:, 1] + ph / 2
  gx, gy = pw * d[:, 0] + px, ph * d[:, 1] + py
  gw, gh = pw * torch.exp(d[:, 2]), ph * torch.exp(d[:, 3])
  return torch.stack([gx - gw / 2, gy - gh / 2, gx + gw / 2, gy + gh / 2], dim=1)


def fit_box_regressor(pool5, proposals, gt_boxes, lam=1000.0, iou_thresh=0.6):
  """Solve box regression for one class in closed form via ridge regression (Eq. (5)). Uses only candidates with IoU > 0.6"""
  iou, idx = box_iou(proposals, gt_boxes).max(dim=1)
  keep = iou > iou_thresh
  X, T = pool5[keep], encode(proposals[keep], gt_boxes[idx[keep]])
  A = X.T @ X + lam * torch.eye(X.shape[1], device=X.device)
  return torch.linalg.solve(A, X.T @ T)                    # W: [9216, 4]


@torch.no_grad()
def detect(image, proposals, features, svm, box_weights, nms_thresh=0.3, score_thresh=0.0):
  """Test procedure. svm: nn.Linear(4096, N) (per-class linear SVMs stacked together)
  box_weights: [N, 9216, 4] (per-class box regression weights). In the paper, nms_thresh is chosen on validation data"""
  features.eval()                                          # disable dropout (use model.train() during training)
  pool5, fc7 = features(warp_regions(image, proposals))
  scores = svm(fc7)                                        # [R, N]: product of 2000×4096 and 4096×N matrices
  boxes, labels, keep_scores = [], [], []
  for c in range(scores.shape[1]):
    s = scores[:, c]
    m = s > score_thresh
    if m.any():
      d = pool5[m] @ box_weights[c]                        # d_*(P) = w_*^T φ5(P)
      boxes.append(decode(proposals[m], d))
      labels.append(torch.full((int(m.sum()),), c, device=s.device))
      keep_scores.append(s[m])
  if not boxes:
    return torch.zeros(0, 4), torch.zeros(0), torch.zeros(0, dtype=torch.long)
  boxes, keep_scores, labels = torch.cat(boxes), torch.cat(keep_scores), torch.cat(labels)
  keep = batched_nms(boxes, keep_scores, labels, nms_thresh)   # per-class non-maximum suppression
  return boxes[keep], keep_scores[keep], labels[keep]


# Usage (image is mean-subtracted [3, H, W]; proposals are Selective Search output [about 2000, 4])
features = RCNNFeatures().to(device)
svm = nn.Linear(4096, num_classes).to(device)              # load and use trained SVM weights
box_weights = torch.zeros(num_classes, 9216, 4, device=device)
image = torch.randn(3, 375, 500, device=device)
proposals = torch.tensor([[50., 60., 200., 300.], [120., 40., 400., 330.]], device=device)
boxes, scores, labels = detect(image, proposals, features, svm, box_weights)
print(boxes.shape, scores.shape, labels.shape)

FAQ

Q. What does the "R" in R-CNN stand for?
A.

It stands for Regions, from the paper's phrase "Regions with CNN features". The name directly describes the method: computing CNN features for each candidate region.

Q. Why is R-CNN slow?
A.

Because it crops about 2,000 candidate regions one by one and passes each through the entire CNN. The candidates overlap heavily, so convolutions over the same pixels are computed many times. The later Fast R-CNN computes convolutions over the whole image only once and crops regions on the feature map (RoI pooling), reducing test time with VGG-16 to 1/146 to 1/213.

Q. Why train separate SVMs when there is already a fine-tuned CNN?
A.

Because it was more accurate in the paper's experiments. Using the CNN's final softmax directly lowered mAP on PASCAL VOC 2007 from 54.2% to 50.9%. The reasons are thought to be that fine-tuning also treats slightly offset candidates with IoU of 0.5 or more as positives and so does not emphasize precise localization, and that it does not train on selected hard negatives.

References

  1. Girshick, R., Donahue, J., Darrell, T., & Malik, J. (2014). Rich feature hierarchies for accurate object detection and semantic segmentation. Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 580–587. arXiv:1311.2524.
  2. Girshick, R. (2015). Fast R-CNN. Proceedings of the IEEE International Conference on Computer Vision (ICCV), 1440–1448. arXiv:1504.08083.
  3. Ren, S., He, K., Girshick, R., & Sun, J. (2015). Faster R-CNN: Towards Real-Time Object Detection with Region Proposal Networks. Advances in Neural Information Processing Systems (NeurIPS) 28. arXiv:1506.01497.