Sub topic 11
Mask R-CNN: Detect, Then Segment
This chapter assumes you know how two-stage object detectors such as Faster R-CNN work, including bounding boxes, confidence scores, and non-maximum suppression (NMS). It also assumes you can read PyTorch and NumPy code. Mask R-CNN is the standard example of a detect-then-segment instance segmentation model, and it supplies the instance half of many panoptic systems.
The core idea
Instance segmentation needs a separate mask for each object. Mask R-CNN solves this in two steps:
- Find objects with a detector, which gives a box, a class, and a score for each one.
- Predict a binary mask inside each box.
Each mask only has to separate one object from its local background, because the box has already isolated it. The model never has to decide which of two touching people a pixel belongs to. Each detection gets its own mask, so instances stay separate.
Mask R-CNN is Faster R-CNN with a third branch added. The two existing branches classify boxes and refine their coordinates. The new branch predicts a mask for each region of interest (RoI), meaning a candidate box.
Components
Backbone and feature pyramid
A convolutional backbone, often ResNet-50 or ResNet-101, extracts features. A feature pyramid network (FPN) combines them into several scales. Small objects use high-resolution levels and large objects use coarse ones. This is the same multi-scale idea you saw in encoder-decoder networks.
Region proposal network
The region proposal network (RPN) slides over the feature maps and proposes boxes that probably contain an object. It scores each one and keeps roughly a thousand after NMS. The RPN does not know about classes. It only separates object from not-object.
RoIAlign
Each proposal has a different size, but the heads need fixed-size input. Faster R-CNN used RoIPool, which rounds box coordinates to whole feature-map cells. That rounding shifts features by up to a few pixels. A box detector tolerates this. A mask does not, because it is judged at the pixel level.
RoIAlign removes the rounding. It keeps coordinates as floating-point values and samples the feature map with bilinear interpolation at regular points inside each output cell. This is the main reason Mask R-CNN produces well-aligned masks.
The mask head
The mask head is a small fully convolutional network. It takes a 14×14 RoI feature, applies a few convolutions and one transposed convolution, and outputs K masks of 28×28, one per class. K is the number of foreground classes.
Two design choices matter:
- Per-pixel sigmoid, not softmax. Each class channel is an independent binary mask. Classes do not compete across pixels.
- Class-specific masks. The model predicts a mask for every class, but only the channel for the predicted class is used. The box head decides what the object is. The mask head only decides which pixels belong to it.
| Branch | Input | Output | Loss |
|---|---|---|---|
| RPN | Feature maps | Objectness and box offsets | Binary cross-entropy and box regression |
| Box head | RoIAlign features | Class scores and class-specific box offsets | Cross-entropy and smooth L1 |
| Mask head | RoIAlign features | K masks of 28×28 | Per-pixel binary cross-entropy |
Training loss
The total loss for each RoI is the sum of three terms:
L = Lcls + Lbox + L_mask
L_mask is the average binary cross-entropy over the 28×28 pixels. It is computed only on the channel of the ground-truth class. Masks for other classes add no loss, so the classes do not compete. Only RoIs that overlap a ground-truth object enough (IoU of at least 0.5 in the standard setup) contribute to the mask loss. Ground-truth masks are cropped to the RoI and resized to 28×28 for comparison.
Inference
At test time the steps run in this order:
- The RPN proposes boxes.
- The box head scores them, refines them, and applies NMS.
- The mask head runs only on the surviving detections.
- Each 28×28 probability mask is resized to its box size, thresholded (usually at 0.5), and pasted into a full-image canvas.
Running the mask head after NMS saves computation. It also explains the typical failure mode: if the box is wrong, the mask is wrong too.
Running a pretrained model
The torchvision implementation returns boxes, labels, scores, and soft masks. This example runs on a random tensor so it works without any files. Replace it with a real image.
import torch
from torchvision.models.detection import maskrcnn_resnet50_fpn
model = maskrcnn_resnet50_fpn(weights="DEFAULT")
model.eval()
image = torch.rand(3, 480, 640) # replace with a real image: float tensor in [0, 1], shape (3, H, W)
with torch.no_grad():
output = model([image])[0]
keep = output["scores"] > 0.5
masks = output["masks"][keep, 0] > 0.5 # (N, H, W) boolean mask per detected instance
labels = output["labels"][keep]
boxes = output["boxes"][keep]
print(masks.shape, labels.tolist())Some details in this code are easy to miss:
- The model takes a list of images, so each image can have a different size. It returns a list of dictionaries, which is why the code takes
[0]. - The images must be float tensors in [0, 1]. The model applies normalization internally.
output["masks"]has shape (N, 1, H, W) and holds probabilities. The code selects channel 0 and thresholds it. These masks are already resized and pasted at full image resolution.- A random tensor usually produces zero detections above 0.5, so
masks.shapemay printtorch.Size([0, 480, 640]). That output is valid. - The labels are COCO category IDs, not indices from 0 to 79. Class 0 is background.
Limitations and edge cases
- Coarse boundaries. A 28×28 mask stretched over a large box is blurry at the edges. Thin structures such as bicycle spokes or animal legs are lost. Later work such as PointRend refines boundaries at selected points.
- Overlapping masks. Each instance mask is predicted on its own, so two masks can claim the same pixel. The output is not a non-overlapping label map. To get one, you have to resolve the conflicts yourself, as in the merging step of panoptic segmentation.
- Things only. The model detects countable objects. It does not segment stuff classes such as sky or road, so it needs a semantic model alongside it for panoptic output.
- Threshold sensitivity. Both the score threshold (0.5 above) and the mask threshold change results. Choose them on a validation set. Evaluation with mask AP sweeps over scores, so it does not depend on one cutoff.
- Duplicates and occlusion. NMS removes duplicate boxes, but heavily overlapping real objects can be suppressed too. A crowd of people may lose some members.
- Cost. Two stages plus per-instance mask heads are slower than a single-pass semantic network. Inference time grows with the number of detections.
Exercise
A Mask R-CNN detects a "person" with a score of 0.9, but its mask is shifted a few pixels from the true outline. The box is accurate. Name two likely causes and one way to check each.
Show answer
First, a coordinate or resizing bug when pasting the 28×28 mask into the image, or when preparing ground truth. Check by overlaying the mask on the image at several object sizes and seeing whether the shift grows with box size. Second, a feature misalignment such as using RoIPool-style rounding instead of RoIAlign in a custom implementation. Check by confirming the RoI operator interpolates instead of rounding. A blurry boundary from the low 28×28 resolution is a third, separate cause, and it shows up as smoothing rather than a shift.