Foundations to Frontier
Tests
E. Deep Learning › E10 Segmentation Architectures

Mask R-CNN

Mask R-CNN (He, Gkioxari, Dollár and Girshick, ICCV 2017) extends Faster R-CNN to instance segmentation by adding a small fully convolutional branch that predicts a 28 × 28 binary mask for each detected box, in parallel with classification and box regression. Two details made it work: RoIAlign, which samples features at exact box coordinates instead of rounding them, and per-class sigmoid masks decoupled from classification. This page covers the mask branch, RoIAlign and the loss. In the exercises you implement RoIAlign and RoIPool to match torchvision, then show that rounding box coordinates cuts mask IoU from 0.94 to 0.68 at stride 16 and that quantisation, not max pooling, is the cause.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

A detector that also draws outlines

A detector finds boxes: “a person here, a dog there”. Mask R-CNN also colours in exactly which pixels belong to each one, so two people standing together get separate outlines. It adds a small extra branch to the Faster R-CNN detector: for each box, look at the features inside it and paint a little 28 × 28 mask, then stretch the mask to fit the box. The trick is to read the features at exactly the box’s position, without snapping to a coarse grid.

Detection lab
RoIPool moves a box edge by up to 6.0 pixels here (at most half the stride, 8), and its bins are rounded again. RoIAlign keeps the exact box and averages bilinear samples (dots), so masks stay aligned with the object.
Why engineers care

Instance masks let robots grasp individual objects, cars track each pedestrian separately, and satellite analysts count individual buildings.

📝 Quick check (Level 0)
0/3 answered
  1. 1. Mask R-CNN adds to Faster R-CNN…
  2. 2. Instance segmentation separates…
  3. 3. RoIAlign avoids…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • Heads per RoI:
    • class scores (K + 1);
    • box offsets;
    • a mask of K × 28 × 28 logits (80 COCO classes give 62,720 values). Only the ground-truth class’s mask is used in the loss.
  • Loss: L = L_cls + L_box + L_mask.
    • L_mask is the mean per-pixel binary cross-entropy of the sigmoid mask for the true class, on positive RoIs only.
    • For logits [0, 0] and targets [1, 0] it is log 2 = 0.693.
  • RoIPool’s rounding:
    • at stride 16, a box edge at x = 100 becomes 6.25 → 6 on the grid, which is 96 in the image, a 4-pixel shift;
    • edges can shift by up to half the stride, and the bins are rounded again.
  • RoIAlign:
    • divide the exact box into bins (14 × 14 for the mask head, 7 × 7 for the box head);
    • in each bin, take 2 × 2 bilinear samples and average them;
    • for f = [[0, 10], [20, 30]], the sample at (0.5, 0.5) is 15.
  • Mask head (torchvision):
    • four 3 × 3 convolutions with 256 channels;
    • a 2 × 2 transposed convolution doubles 14 × 14 to 28 × 28;
    • a 1 × 1 convolution gives the class masks.
    • At inference the mask of the predicted class is resized to the box and thresholded at 0.5.
📝 Quick check (Level 1)
0/3 answered
  1. 1. Mask outputs per RoI with 80 classes:
  2. 2. Edge shift of RoIPool for x = 100 at stride 16:
  3. 3. The mask loss uses…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

Mask R-CNN in code

Exercise 1.

  • RoIAlign (aligned = True, 2 samples per bin side) and RoIPool on an 8 × 8 ramp with box (1.3, 0.7, 5.6, 4.2) reproduced torchvision exactly: [[10.475, 12.625], [24.475, 26.625]] and [[19, 22], [35, 38]].

Practice.

  • torchvision’s maskrcnn_resnet50_fpn uses an FPN backbone. RoIAlign outputs 14 × 14 for masks and 7 × 7 for boxes; RoIs are assigned to pyramid levels by size.
  • The mask head has 2,360,320 parameters in its convolutions plus 285,787 in the predictor (91 COCO category slots).
  • aligned=True subtracts half a pixel so the sampling grid lines up with pixel centres. The original paper’s RoIAlign lacked this shift.
  • Masks are predicted at 28 × 28 and pasted into boxes, so thin structures and fine boundaries are limited. PointRend later refined boundaries adaptively.
  • The same framework predicts human keypoints by replacing masks with one-hot keypoint heat maps.
from torchvision.ops import roi_align
feats = roi_align(fpn_level, boxes, output_size=14, spatial_scale=1/16, sampling_ratio=2, aligned=True)
masks = mask_predictor(mask_head(feats))        # (N, K, 28, 28) logits
loss = F.binary_cross_entropy_with_logits(masks[torch.arange(N), gt_cls], gt_masks_28)
🐍 Exercise 1: RoIAlign and RoIPool
Implement torchvision's bilinear sampling, RoIAlign (aligned) and RoIPool, and match their outputs on a fractional box.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Mask head RoIAlign output size:
  2. 2. aligned=True shifts sampling by…
  3. 3. The keypoint variant predicts…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Why quantisation hurts masks more than boxes.

  • Classification is robust to small shifts: a box moved 4 pixels still contains the object.
  • A mask is a pixel-level prediction. If the features come from a region shifted by up to half the stride, the predicted mask is shifted too.
  • At stride 16 a misalignment of 8 pixels is large for a 50-pixel object.
  • The Mask R-CNN paper found RoIAlign improved mask AP by 7.3 points at stride 32 (ResNet-50-C5). Exercise 2 shows the same trend.

Why decouple masks and classes.

  • A softmax over classes per pixel makes classes compete for pixels.
  • Mask R-CNN predicts an independent binary mask for every class and lets the classification branch choose which one to use.
  • The paper found per-class sigmoid masks beat a per-pixel softmax by 5.5 mask AP.

Fully convolutional masks. The mask branch keeps the m × m spatial layout instead of flattening to a vector, so it needs few parameters and preserves geometry.

📝 Quick check (Level 3)
0/3 answered
  1. 1. Quantisation errors matter most for…
  2. 2. Per-class sigmoid masks beat a per-pixel softmax by…
  3. 3. The mask branch is…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

Does rounding the box matter?

History.

  • K. He, G. Gkioxari, P. Dollár and R. Girshick introduced Mask R-CNN (ICCV 2017, Marr Prize). It built on Faster R-CNN (E9-4) and FPN (E9-5).
  • It led COCO instance segmentation, box detection and keypoints in 2016–17 and became the standard instance segmentation baseline.
  • Successors include PANet (2018), Cascade Mask R-CNN, PointRend (2020) and query-based models (E10-9).

Exercise 2. The objects are 40 ellipses in 256 × 256 images. The feature map at stride s is the mask averaged over s × s cells, a “perfect” feature. For each object’s exact box we extract 14 × 14 features three ways:

  • RoIAlign (bilinear, exact box);
  • quantised average (RoIPool’s rounding with averaging);
  • RoIPool (rounding with max).

Each result is pasted back into the box and thresholded at 0.5, and we measure mask IoU (seed 0):

stride RoIAlign quantised average RoIPool (quantised max)
4 0.973 0.874 0.895
8 0.968 0.772 0.834
16 0.935 0.611 0.675
32 0.760 0.419 0.470
  • Rounding costs much of the mask, more as the stride grows. At stride 16 IoU falls from 0.94 to 0.68.
  • The cause is quantisation, not max pooling. Averaging with rounding is even worse than RoIPool’s max, while exact bilinear sampling stays near the feature map’s own limit.
  • Coarse features limit every method. At stride 32 even RoIAlign falls to 0.76, which is one reason Mask R-CNN uses FPN levels with strides 4–32 assigned by box size.
  • These are perfect features, so the numbers isolate geometry. Learned features add their own errors.
🐍 Exercise 2 (research): does rounding the box matter?
Extract mask features with RoIAlign, quantised averaging and RoIPool at several strides, paste them back and measure mask IoU.

Mask R-CNN in AI, robotics and aerospace

  • Robotic grasping: instance masks separate touching objects in bins for pick-and-place.
  • Autonomous driving: instance masks of pedestrians and vehicles feed tracking and prediction.
  • Remote sensing: building footprints and ship masks in satellite imagery are classic Mask R-CNN applications.

References

  1. K. He, G. Gkioxari, P. Dollár, R. Girshick (2017). “Mask R-CNN.” Proc. ICCV.
  2. S. Ren, K. He, R. Girshick, J. Sun (2015). “Faster R-CNN: towards real-time object detection with region proposal networks.” Proc. NeurIPS.
  3. A. Kirillov, Y. Wu, K. He, R. Girshick (2020). “PointRend: image segmentation as rendering.” Proc. CVPR.