AI Logic

Architectures

Mask R-CNN

Updated:

Architecture of Mask R-CNN. The left side shows the overall flow: the input image passes through the backbone (ResNet-FPN), the RPN generates region proposals from the feature maps, and the features extracted with RoIAlign are passed in parallel to the class and box head (7×7×256) and the mask head (14×14×256). The right side shows the inside of the mask head: four 3×3 convolutions, a 2×2 transposed convolution that upsamples to 28×28, and a 1×1 convolution with a sigmoid that outputs one mask for each of the 80 classes. During training, binary cross-entropy is computed only on the mask of the ground-truth class k.

Background and Overview

Mask R-CNN is an instance segmentation method that adds to Faster R-CNN, in parallel, a branch that predicts the shape (mask) of the object in each region proposal. He et al. at Facebook AI Research proposed it in 2017 (ICCV 2017). It also introduced RoIAlign, which removes misalignment when extracting features from region proposals.

Instance segmentation is the task of finding each object in an image individually and delineating its outline at the pixel level. It is finer-grained than object detection, which only draws boxes, and harder than semantic segmentation, which only assigns a class to each pixel (without distinguishing objects of the same class), because it separates objects one by one. Mask R-CNN solves this task in a simple way: "first find the object, then cut out its shape inside the box."

The main results of the paper are as follows.

  • On COCO instance segmentation, it achieves a mask AP of 37.1 (ResNeXt-101-FPN), outperforming the COCO 2015 and 2016 winners (MNC and FCIS) with a single model.
  • On box detection without masks, it achieves a COCO AP of 39.8, surpassing previous single-model results.
  • The same framework can detect human joint locations (keypoints), outperforming the COCO 2016 winner.
  • With ResNet-101-FPN it runs at 195 ms per image (about 5 fps), adding only a small overhead to Faster R-CNN.

The Problem: Segmenting the Shape of Each Object

Mask R-CNN tackles the problem of distinguishing objects one by one as in object detection while also outputting pixel-level shapes as in segmentation.

Instance segmentation methods at the time fell into two broad groups.

  • Generate shape candidates first, then classify them (DeepMask and others): Shape candidates are generated and then classified with Fast R-CNN. The paper points out that this approach, in which segmentation precedes recognition, is slow and less accurate.
  • Separate objects from per-pixel classification (FCIS and others): Each pixel is assigned a class, and pixels of the same class are then split into objects. In the paper's comparison, FCIS makes systematic errors on overlapping objects and creates spurious edges.

Mask R-CNN takes an "object-first" approach: find the object first, then predict its shape inside the box. Finding and classifying objects is left to the proven Faster R-CNN, and shape prediction becomes a simple problem of labeling each pixel of a small image inside the box as "object or background."

To output pixel-level shapes, however, the features extracted from the region proposal must stay aligned with positions in the original image. Faster R-CNN's RoI pooling rounds coordinates to the feature map grid, and a misalignment small enough not to affect classification still greatly reduces mask accuracy. Mask R-CNN solves this problem with RoIAlign.

Theory: The Mask Branch and the Loss

Mask R-CNN adds a branch that outputs KK class-specific m×mm \times m masks for each region proposal, in parallel with the second stage of Faster R-CNN (classification and box refinement). In the figure at the top of the article, the left side shows the overall flow and the right side shows the inside of the mask head.

Each image is processed in the following steps (for the standard configuration with FPN).

  1. Resize the image so its shorter side is 800 pixels and pass it once through the backbone (ResNet and FPN) to produce feature maps at several resolutions.
  2. The first-stage RPN (the same as in Faster R-CNN) generates region proposals (1000 at test time).
  3. Extract features for each region proposal with RoIAlign. The class and box head receives 7×7 features and the mask head receives 14×14 features.
  4. The class and box head (two fully connected layers, 1024 dimensions) outputs class probabilities and box refinements.
  5. The mask head (a small fully convolutional network, FCN) outputs one 28×28 mask per class (80 for COCO).
    • Stack four 3×3 convolutions (256 channels, ReLU).
    • Upsample 14×14 to 28×28 with a 2×2 transposed convolution (stride 2).
    • Use a 1×1 convolution to produce one mask per class and apply a sigmoid function to each pixel.

The loss for each sampled region proposal during training is the sum of three terms.

L=Lcls+Lbox+LmaskL = L_{cls} + L_{box} + L_{mask}

LclsL_{cls} and LboxL_{box} are the same as in Fast R-CNN (class cross-entropy and Smooth L1 loss for boxes). LmaskL_{mask} is the average per-pixel binary cross-entropy computed only on the kk-th mask for a proposal whose ground-truth class is kk.

Lmask=−1m2∑i,j[yijlog⁡y^ijk+(1−yij)log⁡(1−y^ijk)]L_{mask} = -\frac{1}{m^2} \sum_{i,j} \left[ y_{ij} \log \hat{y}^{k}_{ij} + (1 - y_{ij}) \log (1 - \hat{y}^{k}_{ij}) \right]

y^ijk\hat{y}^{k}_{ij} is the sigmoid output at pixel (i,j)(i, j) of the kk-th mask, and yijy_{ij} is the value (0 or 1) of the ground-truth mask (the part overlapping the proposal box). Masks of other classes do not contribute to the loss. The mask loss is computed only on positive proposals whose IoU with a ground-truth box is 0.5 or higher.

At test time, the mask computation is changed slightly from training to reduce cost.

  1. Apply the class and box head to the proposals, then apply non-maximum suppression.
  2. Apply the mask head only to the boxes of the top 100 scoring detections.
  3. Use the single mask for the class kk predicted by the class head, resize it to the box size, and binarize it at a threshold of 0.5.

A key design choice in Mask R-CNN is to output only "object or background" with an independent sigmoid per class, rather than applying a per-pixel softmax that makes classes compete for each pixel. Because the class and box head decides the class, the mask head only needs to learn the shape. With a softmax, the mask AP drops from 30.3 to 24.8.

RoIAlign: Removing Misalignment

RoIAlign is an operation that, when dividing a region proposal into a fixed number of bins, does not round coordinates to integers but computes the values at several points in each bin by bilinear interpolation and aggregates them. See the RoIAlign article for details.

RoI pooling uses [x/16][x/16] (rounding) to fit an image coordinate xx to the feature map grid, and rounds again when dividing into bins. Since one feature map cell covers 16 image pixels, a single rounding can cause a misalignment of up to several pixels. RoIAlign uses x/16x/16 as is, places four points in each bin, computes their values from the four surrounding grid points by bilinear interpolation, and takes the average (or maximum).

In the paper's comparison, the effect of RoIAlign is as follows (COCO validation data, mask AP).

MethodAlignmentBilinear interpolationAPAP75_{75}
RoI poolingNoNo26.926.4
RoIWarpNoYes27.227.1
RoIAlignYesYes30.331.5

Even with bilinear interpolation, RoIWarp, which still rounds RoI coordinates, performs almost the same as RoI pooling. The difference comes not from interpolation but from removing rounding and aligning positions. In particular, AP75_{75}, which uses a strict IoU threshold, rises by 5 points.

Why Accuracy Improves

The paper's analysis suggests four reasons why Mask R-CNN achieves high accuracy with a simple design.

  • Decoupling classification and shape prediction: The class and box head decides the class, and the mask head outputs only the shape for that class. Even with a class-agnostic variant that outputs a single mask regardless of class, AP only drops from 30.3 to 29.7, showing that the mask head is mostly separating object from background.
  • Predicting masks with convolutions to preserve spatial layout: Compressing into a short vector with fully connected layers, as for classes and boxes, loses shape information. The mask head consists only of convolutions, so every layer preserves the m×mm \times m layout. Compared with outputting masks from fully connected layers (MLP), AP is 2.1 points higher with fewer parameters.
  • Removing misalignment: RoIAlign aligns the extracted features with image positions. The effect is even larger on coarse feature maps (stride of 32 image pixels), where mask AP rises by 7.3 points, from 23.6 to 30.9.
  • Mask learning also helps box detection: Compared with "Faster R-CNN with RoIAlign," trained without the mask branch, Mask R-CNN's box AP is 0.9 points higher. The paper attributes this gain to multi-task training.

As an everyday analogy, Faster R-CNN marks "what is where" with sticky notes, and Mask R-CNN's mask head is simply the worker who traces, for each sticky note, "which pixels inside are the object." Since it does not have to figure out what the object is, it can focus on tracing.

Experimental Results

Instance segmentation on COCO test-dev (mask AP, all single models)

MethodBackboneAPAP50_{50}AP75_{75}
MNC (COCO 2015 winner)ResNet-101-C424.644.324.8
FCIS (COCO 2016 winner)ResNet-101-C5 (dilated convolution)29.249.5―
FCIS+++ (with multi-scale and other enhancements)ResNet-101-C5 (dilated convolution)33.654.5―
Mask R-CNNResNet-101-C433.154.934.8
Mask R-CNNResNet-101-FPN35.758.037.8
Mask R-CNNResNeXt-101-FPN37.160.039.4

C4 uses the feature map from the fourth stage of ResNet directly, and FPN uses a feature pyramid.

Backbone comparison (COCO validation data, mask AP)

BackboneAP
ResNet-50-C430.3
ResNet-101-C432.7
ResNet-50-FPN33.6
ResNet-101-FPN35.4
ResNeXt-101-FPN36.7

Mask head design (COCO validation data, mask AP)

ComparisonSettingAP
Mask output (ResNet-50-C4)Per-pixel softmax (classes compete)24.8
Per-class sigmoid (default)30.3
Mask head layers (ResNet-50-FPN)Fully connected layers (MLP)31.5
Convolutions (FCN, default)33.6

Box detection on COCO test-dev (box AP, single models)

MethodBackboneAP
Faster R-CNN + FPNResNet-101-FPN36.2
Faster R-CNN (with RoIAlign)ResNet-101-FPN37.3
Mask R-CNNResNet-101-FPN38.2
Mask R-CNNResNeXt-101-FPN39.8

The gap between mask AP (37.1) and box AP (39.8) is 2.7 points, considerably narrowing the gap between detection and instance segmentation.

Keypoint detection: Simply by predicting, for each keypoint type such as a human joint, "a mask in which only one pixel is 1," it achieves a keypoint AP of 62.7 on COCO test-dev (ResNet-50-FPN), outperforming the COCO 2016 winner (61.8).

Practical Considerations

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

  • Mask resolution is 28×28: However large the object, a 28×28 mask is resized to the box size, so fine outlines of large objects become coarse.
  • C4 backbones are slow: According to the paper, ResNet-101-FPN takes 195 ms per image, while ResNet-101-C4 takes about 400 ms because of its heavy class and box head; the paper does not recommend C4 in practice.
  • Test-time masks only for the top 100 detections: In images with more than 100 objects, some objects get no mask. In torchvision this can be changed with box_detections_per_img (default 100).
  • Training cost: In the paper, training ResNet-50-FPN on COCO takes 32 hours on 8 GPUs. With little data, it is common to fine-tune from COCO-pretrained weights.

The masks output by torchvision's maskrcnn_resnet50_fpn are not 0/1 masks but probabilities (0 to 1) with shape [N, 1, H, W]. To match the paper, binarize them at a threshold of 0.5. For training, pass the ground-truth masks as per-object 0/1 tensors of shape [N, H, W], and pass the number of classes including background as num_classes.

Comparison with Other Methods

Mask R-CNN adds an object-shape branch to the line of two-stage detectors that began with R-CNN. Comparing them from the same perspectives gives the following (times are the values from each paper and are only rough guides, since GPU types differ).

MethodRegion proposalsHow proposal features are extractedOutputDetection time per image (paper value)
R-CNNSelective Search (about 2000)Crop the image for each proposal and pass it through a CNNClass and box13 s (AlexNet-based), 47 s (VGG-16)
SPP-netSelective SearchSpatial pyramid pooling from the feature map of the whole imageClass and box10 to 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 region proposals (VGG-16)
Faster R-CNNRPN (shared feature map, 300)RoI poolingClass and box0.198 s (VGG-16)
Faster R-CNN + FPNRPN at 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)

Compared with other methods that produce pixel-level outputs:

MethodDistinguishes individual objectsHow it outputsSuitable use cases
Semantic segmentation such as FCN and U-NetNoAssign a class to each pixelLabeling uncountable regions such as roads and sky
"Pixel-first" methods such as FCISYesSeparate objects from per-pixel classification―
Mask R-CNN ("object-first")YesFind the object box first, then output the shape inside the boxTasks that require counting objects and the shape of each one

Rough guidelines for choosing are as follows.

  • Per-object outlines are needed (counting cells one by one, cutting out people, and so on): Mask R-CNN is the standard starting point.
  • Boxes are enough: Faster R-CNN (with FPN) without the mask branch suffices. However, if the training data has masks, training with Mask R-CNN also slightly improves box accuracy.
  • Only labeling regions, without distinguishing objects: Semantic segmentation methods such as FCN and U-Net are a better fit.
  • Human pose: The keypoint head in the same framework can be used.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision.models.detection import maskrcnn_resnet50_fpn, MaskRCNN_ResNet50_FPN_Weights
from torchvision.models.detection.faster_rcnn import FastRCNNPredictor
from torchvision.models.detection.mask_rcnn import MaskRCNNPredictor
from torch.utils.data import Dataset, DataLoader
from tqdm import tqdm

'''
(1) The mask head from Figure 4 (right) of the paper and the loss computed only on the ground-truth class mask, written as in the formulas
(2) Fine-tuning torchvision's Mask R-CNN (ResNet-50-FPN, pretrained on COCO) on your own data
'''

device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'


# (1) Mask head: 14×14×256 → 3×3 conv × 4 → 2×2 transposed conv → 28×28×256 → 1×1 conv to K masks
class MaskHead(nn.Module):
  def __init__(self, in_channels=256, num_classes=80):
    super().__init__()
    layers = []
    for _ in range(4):
      layers += [nn.Conv2d(in_channels, 256, 3, padding=1), nn.ReLU(inplace=True)]
      in_channels = 256
    self.convs = nn.Sequential(*layers)
    self.deconv = nn.ConvTranspose2d(256, 256, 2, stride=2)
    self.predictor = nn.Conv2d(256, num_classes, 1)    # one mask per class

  def forward(self, x):                                # x: RoIAlign output [R, 256, 14, 14]
    x = F.relu(self.deconv(self.convs(x)))
    return self.predictor(x)                           # [R, K, 28, 28] (values before the sigmoid)


def mask_loss(mask_logits, gt_classes, gt_masks):
  """Average per-pixel binary cross-entropy using only the mask of the ground-truth class k (L_mask in Section 3 of the paper)
  mask_logits: [R, K, 28, 28], gt_classes: [R] (0-based class indices), gt_masks: [R, 28, 28] (0 or 1)"""
  idx = torch.arange(len(gt_classes), device=mask_logits.device)
  logits_k = mask_logits[idx, gt_classes]             # [R, 28, 28]: masks of other classes are not used
  return F.binary_cross_entropy_with_logits(logits_k, gt_masks.float())  # sigmoid + binary cross-entropy


head = MaskHead()
logits = head(torch.randn(8, 256, 14, 14))
print(logits.shape, mask_loss(logits, torch.randint(0, 80, (8,)), torch.randint(0, 2, (8, 28, 28))).item())


# (2) Fine-tuning. As an example, a dataset that generates images of squares and circles (replace with your own data)
class ShapesDataset(Dataset):
  def __len__(self):
    return 200

  def __getitem__(self, i):
    g = torch.Generator().manual_seed(i)
    image = torch.rand(3, 256, 256, generator=g) * 0.2
    yy, xx = torch.meshgrid(torch.arange(256), torch.arange(256), indexing='ij')
    masks, boxes, labels = [], [], []
    for _ in range(int(torch.randint(1, 4, (1,), generator=g))):
      cx, cy, r = (int(v) for v in torch.randint(40, 216, (3,), generator=g))
      r = r % 30 + 15
      label = int(torch.randint(1, 3, (1,), generator=g))            # 1: square, 2: circle (0 is background)
      if label == 1:
        m = ((xx - cx).abs() <= r) & ((yy - cy).abs() <= r)
      else:
        m = (xx - cx) ** 2 + (yy - cy) ** 2 <= r ** 2
      image[:, m] = torch.rand(3, 1, generator=g)
      ys, xs = torch.where(m)
      boxes.append([xs.min(), ys.min(), xs.max() + 1, ys.max() + 1])
      masks.append(m)
      labels.append(label)
    target = {'boxes': torch.tensor(boxes, dtype=torch.float32), 'labels': torch.tensor(labels),
              'masks': torch.stack(masks).to(torch.uint8)}                 # per-object 0/1 masks of shape [N, H, W]
    return image, target


num_classes = 3                                        # background + square + circle
model = maskrcnn_resnet50_fpn(weights=MaskRCNN_ResNet50_FPN_Weights.COCO_V1)
# replace the last layers of the box head and the mask head to match your number of classes
in_features = model.roi_heads.box_predictor.cls_score.in_features
model.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes)
model.roi_heads.mask_predictor = MaskRCNNPredictor(256, 256, num_classes)
model.to(device)

loader = DataLoader(ShapesDataset(), batch_size=2, shuffle=True, collate_fn=lambda b: tuple(zip(*b)))
params = [p for p in model.parameters() if p.requires_grad]
optimizer = torch.optim.SGD(params, lr=0.005, momentum=0.9, weight_decay=0.0001)

for epoch in tqdm(range(5)):
  model.train()                                        # in training mode, returns a dict of losses (including loss_mask)
  for images, targets in loader:
    images = [img.to(device) for img in images]
    targets = [{k: v.to(device) for k, v in t.items()} for t in targets]
    losses = model(images, targets)
    loss = sum(losses.values())                        # L = L_cls + L_box + L_mask (+ RPN losses)
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

model.eval()                                           # in eval mode, returns detections
with torch.no_grad():
  image, _ = ShapesDataset()[0]
  out = model([image.to(device)])[0]
  binary_masks = out['masks'][:, 0] > 0.5             # binarize the probabilities [N, 1, H, W] at 0.5
  print(out['labels'].tolist(), out['scores'].tolist(), binary_masks.shape)

FAQ

Q. How does Mask R-CNN differ from Faster R-CNN?
A.

There are two differences. First, it adds a branch that outputs the object shape (a 28×28 mask) for each region proposal, alongside the class and box head. Second, it replaces RoI pooling, which extracts features from region proposals, with RoIAlign, which does not round coordinates. Everything else, including the RPN, is the same as Faster R-CNN.

Q. Isn't it wasteful to output masks for every class?
A.

The number of outputs increases, but only the channel count of the last 1×1 convolution in the mask head grows, so the extra computation is small. Making the masks independent per class means classes do not compete, and the mask head can learn only shapes. In the paper, this gives a mask AP 5.5 points higher than a per-pixel softmax that makes classes compete.

Q. Can it be used for semantic segmentation?
A.

Mask R-CNN finds objects one by one and then outputs their shapes, so it is not suited to labeling uncountable regions such as sky or roads. For such tasks, use methods that assign a class to each pixel, such as FCN or U-Net.

References

  1. He, K., Gkioxari, G., Dollár, P., & Girshick, R. (2017). Mask R-CNN. Proceedings of the IEEE International Conference on Computer Vision (ICCV), 2961–2969. arXiv:1703.06870.
  2. Ren, S., He, K., Girshick, R., & Sun, J. (2015). Faster R-CNN: Towards Real-Time Object Detection with Region Proposal Networks. NeurIPS 2015. arXiv:1506.01497.
  3. Lin, T.-Y., Dollár, P., Girshick, R., He, K., Hariharan, B., & Belongie, S. (2017). Feature Pyramid Networks for Object Detection. CVPR 2017. arXiv:1612.03144.
  4. PyTorch. torchvision.models.detection.maskrcnn_resnet50_fpn.