Fast R-CNN

Fast R-CNN is an advanced object detection framework that builds upon the original R-CNN architecture. It is designed to improve the speed and efficiency of object detection by processing regions of interest (RoIs) in a more streamlined manner. Fast R-CNN is a crucial component of the Faster R-CNN architecture, which is widely used in computer vision tasks.

Overview

Fast R-CNN enhances the R-CNN model by introducing Region of Interest (RoI) pooling, which allows for the extraction of features for all region proposals in a single pass. This significantly speeds up the detection process compared to the original R-CNN, which required separate passes for each region proposal. Fast R-CNN eliminates the need for Support Vector Machines (SVMs) by employing a multitask loss function that handles both classification and bounding-box regression, resulting in a more end-to-end architecture.

The architecture processes RoIs to generate class probabilities and bounding-box coordinates. It uses RoI pooling to extract fixed-size feature vectors from the feature map, which are then used for classification and regression to detect objects.

Fast R-CNN Architecture

The core of the Fast R-CNN architecture is the RoI head, which is responsible for processing the RoIs and generating the necessary outputs for object detection. Below is a PyTorch implementation of the Fast R-CNN RoI head:

Listing 11.23 PyTorch code for the Fast R-CNN RoI head

class Fast_RCNN_ROI_Head(nn.Module):
    def __init__(self, num_classes, H, W, subsample=16, embedding_size=512):

        super(Fast_RCNN_ROI_Head, self).__init__()

        self.num_classes = num_classes
        self.H = H
        self.W = W
        self.embedding_size = embedding_size
        self.subsample = 16

        self.roi_head_classifier = nn.Sequential(
            nn.Linear(H*W*embedding_size, 4096),
            nn.ReLU(True),
            nn.Linear(4096, 4096),
            nn.ReLU(True),
        )
        self.cls = torch.nn.Linear(4096, num_classes+1) #1
        self.reg = torch.nn.Linear(4096, (num_classes+1)*4)

    def forward(self, x, rois):                         #2
        assert x.shape[0] == 1 # This code only supports batch size of 1
        roi_pooled_features = torchvision.ops.roi_pool(
            x, [rois], output_size=(self.H, self.W), spatial_scale=1/subsample)
        roi_pooled_features = roi_pooled_features.view(
            -1, self.H*self.W*self.embedding_size)
        fc_out = self.roi_head_classifier(roi_pooled_features)
        roi_cls_scores = self.cls(fc_out)
        roi_loc = self.reg(fc_out)

        return roi_cls_scores, roi_loc                  #3
#1 num_classes + background
#2 x : (1, c, h, w) tensor representing the conv feature map. rois: (n, 4) tensor representing bounding boxes of RoIs
#3 roi_cls_scores: (n, num_classes+1) tensor representing classification scores for each RoI. roi_loc: (n, (num_classes + 1) * 4) tensor representing the regression scores for each RoI

Training Fast R-CNN

Training Fast R-CNN involves sampling a subset of RoIs and maintaining a balanced ratio of object and background RoIs. The loss function used in Fast R-CNN includes both a classification loss for class prediction and a regression loss for bounding-box prediction. The following is a PyTorch implementation of the Fast R-CNN loss function:

Listing 11.24 PyTorch code for the Fast R-CNN loss function

def rcnn_loss(
    roi_cls_scores,                              #1
    roi_loc,                                     #2
    roi_labels,                                  #3
    rcnn_loc_targets,                            #4
    lambda_ = 1):

    classification_criterion = nn.CrossEntropyLoss()
    reg_criterion = nn.SmoothL1Loss(reduction="sum")

    cls_loss = classification_criterion(roi_cls_scores, roi_labels)

    pos_roi_idxes = torch.where(roi_labels>0)[0] #5
    pred_all_offsets = roi_loc[pos_roi_idxes]

    num_pos_rois = len(pos_roi_idxes)
    pred_all_offsets = pred_all_offsets.view(    #6
        num_pos_rois, -1, 4)

    pred_cls_offsets = pred_all_offsets[
        torch.arange(num_pos_rois) , roi_labels[pos_roi_idxes]]

    gt_offsets = rcnn_loc_targets[pos_roi_idxes]

    reg_loss = reg_criterion(pred_cls_offsets, gt_offsets) / num_pos_rois
    return {
        "rcnn_cls_loss": cls_loss,
        "rcnn_reg_loss": reg_loss,
        "rcnn_total_loss": cls_loss + lambda_* reg_loss

    }
#1 (128, num_classes) tensor: RCNN classifier scores for each RoI
#2 (128, num_classes*4) tensor: RCNN regressor predictions for each class, RoI
#3 (128,) tensor: true class for each RoI
#4 (128, 4) tensor: RoI regressor targets for each RoI
#5 Finds the positive RoIs
#6 (n, num_classes*4) to n, num_classes, 4)

Fast R-CNN's design and implementation make it a powerful tool for object detection, providing a balance between speed and accuracy. Its integration into the Faster R-CNN framework further enhances its capabilities, making it a popular choice for various computer vision applications.