Mask R-CNN
A detector that also outlines each object: Faster R-CNN plus a small network that predicts a 28 × 28 mask inside every detected box.
Mask R-CNN adds a convolutional mask branch beside the box head of Faster R-CNN, grades each region only on its own class with per-pixel sigmoids, and replaces rounded region-of-interest (RoI) pooling with exact bilinear sampling (RoIAlign).
Explaining the paperMask R-CNNIn 2016 a detector could draw a box around every person in a crowded photo, and a segmentation network could paint every person pixel blue. Giving each person their own separate outline was much harder: existing systems chained multiple hand-engineered stages and still broke where two people overlapped.
Kaiming He, Georgia Gkioxari, Piotr Dollár, and Ross Girshick at Facebook AI Research (FAIR) published Mask R-CNN in March 2017 to solve that task as a compact extension of Faster R-CNN. Keeping the detector's two-stage design, they added a small convolutional branch that outputs a pixel grid of foreground probabilities for each candidate box. Without test-time tricks or model ensembles, a single Mask R-CNN model beat every single-model entry from the 2016 COCO challenges across instance segmentation, bounding-box detection, and human pose estimation, running at about 5 frames per second on a GPU. The authors released the reference code in Facebook's Detectron library.
Instance segmentation and mask AP
Computer vision splits scene parsing into three tasks of increasing detail. Object detection finds every object and draws a tight rectangle around it, paired with a class label and confidence score. Semantic segmentation, performed by networks like FCN (Fully Convolutional Network) and U-Net, assigns a class label to every pixel in the image without distinguishing individuals: two people standing side by side merge into one connected "person" region. Instance segmentation combines both: every object gets its own class label, confidence score, and binary pixel mask (1 on that object's pixels, 0 everywhere else). Two overlapping people produce two separate masks, and where one stands in front of the other, the foreground mask covers the overlap cleanly.
Mask R-CNN is benchmarked on COCO (Common Objects in Context), a dataset of everyday photographs with 80 object categories and polygon outlines for every instance. Following standard practice, the authors train on trainval35k (80,000 training images plus a 35,000-image validation subset, 115,000 images in total), run controlled design comparisons (ablations) on the remaining 5,000 validation images (minival), and report final headline numbers on the held-out test-dev server.
To grade a predicted mask against a ground-truth mask, COCO computes their intersection over union (IoU): the number of pixels where both masks are 1 divided by the number of pixels where at least one mask is 1. IoU lies between 0 (no overlap) and 1 (exact match), so higher is better. For a given IoU threshold and object class, sorting all predictions from highest confidence to lowest and tracing precision (fraction of predicted masks that match a true object) against recall (fraction of true objects found) gives a precision-recall curve; the area under that curve is the class's average precision (AP, reported on a 0 to 100 scale, where higher is better). COCO's headline score, written as AP, averages that area over all 80 classes and across ten IoU thresholds: 0.50, 0.55, 0.60, and so on up to 0.95 (evaluated at 101 recall points and capped at 100 detections per image). The paper also reports single-threshold scores and , plus size breakdowns for small objects (, area under 32 × 32 pixels), medium objects (, 32 × 32 to 96 × 96 pixels), and large objects (, over 96 × 96 pixels). When AP is computed using bounding-box IoU instead of pixel-wise mask IoU, the paper writes .
Pixel-wise IoU drops steeply under small shifts. Imagine a 30 × 30 square object (900 pixels) whose predicted mask has the exact right shape but is shifted 3 pixels to the right. The overlap is 27 × 30 = 810 pixels, and the combined union is 900 + 900 − 810 = 990 pixels, giving an IoU of 810 / 990 = 0.818. That prediction counts as a hit at thresholds 0.50 through 0.80, and as a complete miss at 0.85, 0.90, and 0.95. Half of COCO's ten thresholds sit at 0.75 or higher, so a misalignment of just a few pixels drags AP down directly.
Feature maps and Faster R-CNN
A convolutional neural network (CNN) backbone reads an input image and passes it through layers of learned filters and downsampling steps. Downsampling shrinks the height and width while increasing the number of channels (numbers stored per spatial position). If an 800 × 1,200 photo passes through four downsampling stages of factor 2 each, the output has stride 16: a 50 × 75 grid where each cell summarizes roughly a 16 × 16 pixel patch of the original image as a vector of 1,024 learned features. Moving one cell right on this feature map corresponds to jumping 16 pixels right in the photo.
Unlike single-stage detectors such as YOLO, which predict boxes directly from a dense grid in one pass, Faster R-CNN splits detection into two stages that share the backbone's feature map. In Stage 1, a small sliding network called the Region Proposal Network (RPN) scans every cell of the feature map using reference boxes (anchors) of several sizes and aspect ratios, proposing a few hundred to a few thousand candidate rectangles that probably contain an object. Each candidate rectangle is a Region of Interest (RoI).
Stage 2 has to classify each RoI into one of the 80 COCO classes (or background) and regress four fine-grained offsets to tighten its box. Candidate boxes arrive in every size and shape, from a tiny distant bird to a bus filling half the frame, yet the classification head expects a fixed-size input grid (typically 7 × 7). Faster R-CNN bridges that gap with RoIPool (from Fast R-CNN): it maps the proposal onto the feature map, divides it into a 7 × 7 grid of sub-windows (bins), and takes the maximum value in each bin. After Stage 2 scores all proposals, non-maximum suppression (NMS) discards lower-scoring boxes that overlap a higher-scoring box of the same class by more than an IoU threshold, leaving one box per object.
Mask R-CNN separates the network into two named pieces: the backbone, which computes feature maps once over the whole image, and the head, which runs separately on each RoI. The authors test two backbone families, each built on a ResNet of 50 or 101 layers or on ResNeXt (a ResNet variant that splits each bottleneck convolution into parallel grouped convolutions):
- ResNet-C4: extracts features from the final layer of ResNet's fourth stage, giving one feature map of 1,024 channels at stride 16. ResNet's fifth stage (
res5, 9 convolutional layers, modified so its first convolution runs on a 7 × 7 RoI with stride 1 instead of 14 × 14 with stride 2) moves into the per-RoI head. Running 9 heavy layers on hundreds of proposals makes this head slow. - ResNet-FPN: uses a Feature Pyramid Network (Lin et al., 2017, co-authored by three of the Mask R-CNN authors). FPN runs the entire ResNet (including
res5) once as the backbone, then adds a top-down pathway with lateral connections to merge coarse, semantically rich maps with fine, high-resolution maps. The output is four 256-channel feature maps ( through ) at strides 4, 8, 16, and 32. Each RoI reads from the pyramid level that matches its size, and the box head shrinks to two lightweight fully connected layers of 1,024 units.
How Mask R-CNN works
Earlier instance-segmentation systems such as DeepMask and MNC (Multi-task Network Cascades) ran segmentation before classification, predicting mask candidates first and classifying them in a later stage. Another strong competitor, FCIS (Fully Convolutional Instance-aware Semantic Segmentation), used position-sensitive score maps to predict classes, boxes, and masks jointly in one convolutional grid, but produced systematic split-and-merge artifacts whenever two instances of the same class overlapped.
Mask R-CNN keeps the RPN completely unchanged and adds a third branch to Stage 2 alongside the existing class and box outputs. For each RoI, this mask branch outputs grids of size , one grid per object category ( on COCO). With ResNet-FPN, ; with ResNet-C4, . Each cell of those grids holds an unbounded real number called a logit, which the logistic sigmoid maps into a probability between 0 and 1 that the pixel belongs to the object.
The mask head keeps a 2D spatial grid instead of flattening features into a vector. Predicting a class label or four box offsets requires summarizing the whole RoI, so the box head flattens the pooled features into a 1D vector and passes it through fully connected layers (a multi-layer perceptron, or MLP). Flattening discards the 2D grid topology: every output pixel would have to re-learn from scratch which input coordinates correspond to top-left versus bottom-right. Worse, an MLP producing 80 × 28 × 28 = 62,720 outputs from a 1,024-unit hidden layer spends 1,024 × 62,720 = 64.2 million weights on its final layer alone.
Mask R-CNN instead builds the mask branch as a small fully convolutional network (FCN): every layer is a 2D convolution, so every intermediate tensor stays a 2D spatial grid and output pixel is computed from local features centered at . On ResNet-FPN, the mask branch pools its own RoI feature grid (twice the spatial resolution of the box head's grid), applies four convolutions of 256 channels with ReLU activations (rectified linear units, ), upsamples to with a stride-2 transposed convolution (deconvolution, with ReLU), and finishes with a convolution to 80 channels. The entire FPN mask head holds about 2.6 million weights (2,643,280 with biases), 24 times fewer than the final layer of the MLP alone, and in Table 2e it scores 2.1 mask AP higher (33.6 against 31.5).
Figure 1 maps the full tensor shapes for both backbones and both phases. Switch between training and inference to see how the mask branch changes position in the graph.
The parallel diagram from the paper's introduction holds only during training. At inference, the box head runs first on all proposals (1,000 for FPN, 300 for C4), per-class NMS removes duplicates, and the mask head runs only on the 100 highest-scoring detections using their already-refined boxes. Running the mask branch on 100 refined boxes instead of 1,000 raw proposals both keeps its runtime overhead to about 20% of Faster R-CNN and improves mask accuracy because the refined boxes frame the objects more tightly.
The mask loss
During training, every sampled RoI is graded on up to three tasks at once, and their losses add together into a single multi-task objective so gradients from classification, localization, and pixel outlining all shape the shared backbone:
and are unchanged from Fast R-CNN: is a cross-entropy log loss over 81 classes (80 COCO categories plus background), and is a smooth-L1 regression loss on the four box-refinement offsets of the ground-truth class, active only for foreground (positive) RoIs.
For the new mask term , every pixel inside the grid is treated as an independent yes-or-no question: does this pixel lie on the object () or on the background ()? If the network outputs probability for a foreground pixel, taking penalizes confident errors steeply () while dropping toward zero as . For a background pixel, the symmetric penalty is . Averaging this binary cross-entropy over all pixels of the RoI's ground-truth class gives:
Because every target pixel is either 1 or 0, exactly one of the two bracketed terms is nonzero at each location : the first penalizes low on foreground pixels, and the second penalizes high on background pixels. Three rules govern which pixels enter (2). First, is defined only on positive RoIs, meaning proposals whose box IoU with some ground-truth object is at least 0.5; background RoIs have no object to outline and contribute zero mask loss. Second, only channel (the ground-truth class of that RoI) is scored, while the other 79 mask channels are ignored. Third, the target grid is the ground-truth polygon clipped to the RoI's own rectangle and rasterized onto an grid (in Detectron's roi_data/mask_rcnn.py, each positive RoI takes the polygon of the ground-truth box with highest IoU, rasterized via polys_to_mask_wrt_box). When a proposal box cuts off part of an object, the target stops at the proposal's edge, matching the paper's definition of the target as the intersection between the RoI and its ground-truth mask.
Take one proposal in an FPN model to put concrete numbers on (2). Suppose an image is resized so its shorter side is 800 pixels, and a proposal around a standing person spans and (width 228.6 pixels, height 531.6 pixels), with box IoU 0.62 against the person's ground-truth box. Because 0.62 ≥ 0.5, the proposal is positive with class . Rasterizing the person's polygon inside this box onto a 28 × 28 grid gives each cell a footprint of 228.6 / 28 ≈ 8.2 pixels wide by 531.6 / 28 ≈ 19.0 pixels tall. The mask head emits 80 × 28 × 28 = 62,720 logits for this single RoI, yet equation (2) evaluates only the 784 logits in the person channel (1.25% of the output). A pixel initialized at logit 0 has probability and incurs loss regardless of whether is 0 or 1.
Differentiating binary cross-entropy with respect to a pre-sigmoid logit has a clean cancellation: the derivative of the sigmoid cancels the denominator of the logarithm, leaving predicted probability minus target label, scaled by :
For our logit-0 pixel where , the gradient is (0.5 − 1) / 784 = , so gradient descent steps upward. The second half of (3) gives zero gradient to the other 79 class channels (Detectron implements this by filling non-target class slots with , which its loss ignores). The final filter for "person" learns exclusively from person RoIs, the "dog" filter exclusively from dog RoIs, and the four shared convolutions below receive gradients from all positive RoIs. One full FPN training step, with tensor shapes and equation references:
# One training step, ResNet-50-FPN, one image (Detectron recipe)
P = fpn(image) # P2..P5: [1, 256, H/s, W/s]
props = rpn(P) # [M, 4] candidate boxes
rois = sample(props, n=512, pos_frac=0.25, pos_iou=0.5) # [512, 4]
lvl = clip(floor(4 + log2(sqrt(area(rois)) / 224)), 2, 5) # Eq. (6)
f_box = roi_align(P, lvl, rois, out=7, samples=2) # [512,256,7,7], Eq. (5)
cls, d = box_head(f_box) # [512, 81], [512, 324]
pos = rois[labels > 0] # [n, 4], n <= 128 positives
f_mask = roi_align(P, lvl, pos, out=14, samples=2) # [n,256,14,14], Eq. (5)
z = mask_head(f_mask) # [n, 80, 28, 28] mask logits
y = rasterize(gt_poly[match(pos)], pos, 28) # [n, 28, 28] in {0, 1}
z_k = z[arange(n), labels[pos] - 1] # [n, 28, 28], ground-truth class k
L_mask = bce_with_logits(z_k, y).mean() # scalar over n * 784 px, Eq. (2)
loss = ce(cls, labels) + smooth_l1(d, box_tgt, pos) + L_mask # Eq. (1)
loss.backward() # Eq. (3): 79 other ch get 0 gradWhy a sigmoid per class instead of a softmax
Why not reuse the loss that semantic segmentation networks like FCN (Long et al., 2015) already use? In semantic segmentation, every pixel gets a softmax across all classes, turning the class logits into a single probability distribution that sums to 1 at each pixel:
Trained with multinomial cross-entropy, the gradient at pixel is for every class (where is 1 for the true class and 0 otherwise). Every channel receives a nonzero gradient, and the denominator forces classes to compete for a fixed probability budget of 1.0 at each pixel. If a person stands in front of a horse inside a person RoI, raising the horse logit on the overlapping torso pixels directly shrinks the person probability even when the person logit has not changed at all. A mask head trained under (4) has to re-solve per-pixel 80-way classification at every coordinate.
Mask R-CNN does not need the mask head to classify the object, because the box branch already classifies the whole RoI using features pooled across the entire instance, and at test time that predicted class selects which mask channel to read. Replacing (4) with (2) removes cross-class competition: given that the RoI is a person, the person channel only answers which pixels inside the box belong to that person. The authors call this decoupling mask and class prediction.
Figure 2 tests this difference on a 14 × 14 person RoI overlapped by a horse. The person logit is fixed at +3 on person pixels and −3 elsewhere, while the slider varies the horse logit on horse pixels from −4 to +8 (starting at +4, one unit above the person logit).
At horse logit +4, the softmax mask loses all 19 person pixels where the horse overlaps (mask IoU drops from 1.00 to 0.67), even though the person channel stayed untouched; slide the horse logit down to +3 or below and the two panels match. Under per-class sigmoids, the person mask depends on the person channel alone and stays at IoU 1.00 across the entire slider range.
The ablation in Table 2b (ResNet-50-C4 on minival) shows how large this effect is in practice: per-pixel softmax scores 24.8 mask AP, whereas per-class sigmoid scores 30.3, a gain of 5.5 AP (+7.1 at and +6.4 at ). The authors also test a class-agnostic variant whose mask head outputs a single binary mask regardless of object category: it reaches 29.7 mask AP, only 0.6 points below the 80-channel default.
What RoIPool rounds away
Even with an FCN head and decoupled sigmoids, dropping a mask branch onto vanilla Faster R-CNN still blurs and shifts the predicted outlines. The source of that shift is RoIPool, the layer that crops each RoI out of the backbone feature map. A mask is a pixel-to-pixel output: cell of the pooled feature grid feeds directly into the region around pixel of the output mask. If the pooled features come from the wrong part of the image, the mask is drawn in the wrong place.
RoIPool introduces spatial error through two separate rounding steps (quantizations). Trace our standing-person proposal (, ) on a stride-16 C4 feature map pooled to a 7 × 7 grid:
- Rounding the RoI edges to integer cells. Converting pixel coordinates to stride-16 feature coordinates gives and . In
caffe-fast-rcnn(roi_pooling_layer.cu), RoIPool snaps every edge withround(x / 16)to whole cells: and . Back in image pixels, the layer now reads instead of : the left edge shifted 5.3 pixels left, the right edge 6.1 pixels right, the top 2.8 pixels up, and the bottom 6.4 pixels down. Each edge can slip by up to half a cell: 8 pixels at stride 16, and 16 pixels at stride 32. - Rounding the bin boundaries to integer cells. The rounded box spans cells 7 through 22 inclusive (16 cells wide), so each of 7 horizontal bins should cover cells. RoIPool instead slices bins from
floor(p * 2.29)toceil((p + 1) * 2.29): bin 0 max-pools cells 7 to 9, bin 1 pools cells 9 to 11, bin 2 pools cells 11 to 13. Adjacent bins share boundary cells, and each bin's true center drifts from the cells it pools.
For box classification, a 6-pixel shift barely matters because a slightly shifted person is still a person. For a mask pasted back into the unrounded box, reading features shifted by up to 8 pixels shifts the predicted contour by up to 8 pixels, pushing tight objects below COCO's 0.75 to 0.95 IoU thresholds. Rounding also turns RoIPool into a staircase function of box position: sliding a box by 3 pixels does nothing until an edge crosses a half-cell rounding boundary, at which point the pooled features jump discontinuously.
How RoIAlign works
RoIAlign eliminates every rounding step. It keeps the floating-point RoI coordinates verbatim, divides the box into exact equal-width floating-point bins, and evaluates the feature map at four regularly spaced points inside each bin (a 2 × 2 sub-grid positioned at 1/4 and 3/4 of the bin's width and height; Detectron calls this ROI_XFORM_SAMPLING_RATIO = 2).
Those floating-point sample coordinates almost never land on an integer feature cell. To read a feature value between grid points, RoIAlign uses bilinear interpolation: picture four elevation stakes standing at the corners of a unit square, and you want the elevation at an interior point . Each corner contributes its value weighted by the area of the rectangle diagonally opposite it, so as you approach one corner its opposite rectangle grows toward area 1 while the other three shrink to 0. Writing the top-left integer corner as , and the fractional offsets as , (both in ):
Check the two sanity limits of (5): if and , only the first term survives with weight 1 and returns exactly; if and , all four weights equal 0.25 and return the unweighted mean of the four corners. Because the four weights always sum to 1, the output varies smoothly as the sample point slides across the grid. RoIAlign averages the four interpolated samples in each bin (Table 2c finds max and average virtually identical, 30.2 vs 30.3 mask AP, and the paper uses average throughout).
Apply (5) to our standing-person RoI on FPN's stride-16 level (assigned there by the rule in the next section), pooled to the mask head's 14 × 14 grid. In feature coordinates the box starts at , and spans 14.29 × 33.23 cells, so each bin measures 1.021 cells wide by 2.373 cells tall. The first sample of the top-left bin sits a quarter of the way into that bin, at x = 7.331 + 0.25 × 1.021 = 7.586 and y = 13.175 + 0.25 × 2.373 = 13.768. Its four surrounding cells are (7, 13), (8, 13), (7, 14), and (8, 14), with and , giving weights 0.096, 0.136, 0.318, and 0.451 (heaviest on (8, 14), the closest corner). Every one of the 14 × 14 × 4 = 784 sample locations is evaluated this way across all 256 channels.
Figure 3 lets you slide an RoI continuously across a stride-16 feature map and compare RoIPool, RoIWarp, and RoIAlign side by side. Watch the amber neighbor links in RoIAlign mode and the curve at the bottom as you drag.
Switch to RoIPool and drag: the violet box snaps between integer grid points while the bottom trace forms a flat staircase with sudden jumps. Switch to RoIWarp (from MNC, Dai et al., 2016) and watch closely: RoIWarp uses bilinear sampling just like RoIAlign, yet it rounds the RoI boundaries first, so its curve is still a staircase because every sample point freezes between rounding jumps. Only RoIAlign moves its teal sample points smoothly with the box and produces a continuous curve.
RoIWarp settles where RoIAlign's accuracy comes from. On ResNet-50-C4 at stride 16 (Table 2c), RoIPool scores 26.9 mask AP, RoIWarp scores 27.2 (max) / 27.1 (avg), and RoIAlign jumps to 30.3 (avg). Bilinear interpolation inside a quantized RoI adds 0.3 points; eliminating quantization adds the remaining 3.1. Doubling the feature stride amplifies the gap. On stride-32 features (ResNet-50-C5, Table 2d), RoIAlign raises mask AP from 23.6 to 30.9 (+7.3 points) and from 21.6 to 32.1 (+10.5 points, a 50% relative gain), while lifting bounding-box AP from 28.2 to 34.0 (+5.8 points). Stride-32 C5 with RoIAlign (30.9) outscores stride-16 C4 with RoIAlign (30.3), refuting the assumption that coarse stride-32 maps cannot support pixel-accurate masks.
Because bilinear interpolation is piecewise linear in , RoIAlign is also piecewise differentiable with respect to the box coordinates. The paper does not backpropagate through the box coordinates, however: even its end-to-end variant in Appendix B follows Faster R-CNN's "approximate" joint training and stops gradients at the RoI coordinates.
The original Detectron RoIAlign kernel carries a constant half-cell shift. Under the standard pixel-area convention where stride-16 feature cell covers image pixels , that cell's center lies at . Detectron's released kernel instead places cell at coordinate without subtracting 0.5 before choosing neighbors, shifting every RoI read by half a cell (8 pixels at stride 16). Detectron2 later added aligned=True to subtract 0.5 and reported no change in accuracy. A plausible reason is that a constant half-cell offset is identical for every RoI so subsequent convolutional layers can learn to compensate for it, whereas RoIPool's rounding error varies from box to box and cannot be undone by fixed filters.
Which pyramid level an RoI reads
On a single-scale stride-16 backbone like C4, objects of wildly different sizes suffer opposite problems: a small 32-pixel-wide traffic light covers only 2 × 2 feature cells (so pooling to 14 × 14 stretches 2 cells across 14 bins), while an 800-pixel bus covers 50 × 50 cells. A Feature Pyramid Network fixes this by keeping four feature maps ( at stride 4, at stride 8, at stride 16, and at stride 32) and routing each RoI to the level where its feature footprint stays between 14 and 28 cells.
An RoI of width and height in resized image pixels has effective side length . FPN (Lin et al., 2017, equation (1)) assigns it to pyramid level via:
clipped to , where has stride . The reference size 224 pixels is ImageNet's standard training crop: a 224 × 224 RoI has and lands on (stride 16, spanning exactly cells). Halving the RoI's side subtracts 1 from the logarithm and moves it down one level to twice the spatial resolution; doubling the side moves it up one level. For our standing person (, ):
Figure 4 plots the four pyramid grids at their true relative cell sizes and compares how many feature cells an RoI spans under FPN versus a single stride-16 C4 map.
Between 56 and 896 pixels, where clipping does not apply, the teal FPN sawtooth stays locked inside the shaded 14-to-28 cell band: every RoI reads from a feature map containing at least as many cells along each side as the 14 × 14 mask pooling grid has bins. Below 56 pixels, the formula clips at (stride 4) and the cell count falls steadily (a 16-pixel object spans only 4 cells), which helps explain why small objects remain the hardest COCO category ( versus for ResNet-101-FPN on test-dev). FPN's finer strides shrink RoIAlign's margin over RoIPool compared with C4 or C5, yet RoIAlign still adds +1.5 mask AP and +0.5 box AP on FPN.
Training, inference, and mask pasting
The training hyperparameters carry over almost unchanged from Fast R-CNN and FPN. Input images are resized so their shorter side is 800 pixels. Training runs across 8 GPUs with 2 images per GPU (an effective mini-batch of 16 images; for the heavier ResNeXt-101 backbone, the authors use 1 image per GPU and halve the starting learning rate from 0.02 to 0.01). From each image, the network samples RoIs at a 1:3 positive-to-negative ratio (positive means box IoU ≥ 0.5): for C4 (at most 16 positives per image) and for FPN (at most 128 positives). Optimization uses stochastic gradient descent (SGD) for 160,000 iterations at learning rate 0.02, dropped by 10× at iteration 120,000, with weight decay 0.0001 and momentum 0.9. RPN anchors span 5 scales and 3 aspect ratios. In the main ablations, the RPN is trained separately with unshared features so second-stage experiments do not require retraining proposals.
On 8 GPUs over COCO trainval35k, ResNet-50-FPN trains in 32 hours (0.72 seconds per 16-image mini-batch) and ResNet-101-FPN in 44 hours. For inference timing, the authors train a ResNet-101-FPN model that shares backbone features between the RPN and the heads via Faster R-CNN's 4-step alternating schedule: it runs in 195 ms per image on an Nvidia Tesla M40 GPU, plus 15 ms on the CPU to resize masks back to the original image resolution (about 5 frames per second). ResNet-101-C4 takes roughly 400 ms per image because of its heavy res5 head, and the paper recommends against using C4 in practice.
# Inference, ResNet-101-FPN, one image
P = fpn(image) # P2..P5: [1, 256, H/s, W/s]
props = rpn(P)[:1000] # [1000, 4] top proposals
lvl_p = fpn_level(props) # [1000], Eq. (6)
f_box = roi_align(P, lvl_p, props, out=7) # [1000, 256, 7, 7], Eq. (5)
cls, d = box_head(f_box) # [1000, 81], [1000, 324]
dets = nms_per_class(decode(props, d), cls)[:100] # <= 100 boxes, class k
lvl_d = fpn_level(dets.boxes) # [100], Eq. (6)
f_mask = roi_align(P, lvl_d, dets.boxes, out=14) # [100,256,14,14], Eq. (5)
z = mask_head(f_mask) # [100, 80, 28, 28]
prob = sigmoid(z[arange(100), dets.k - 1]) # [100, 28, 28], predicted class
masks = [resize(p, box) >= 0.5 for p, box in zip(prob, dets.boxes)]In the last two lines of the inference listing above, the predicted class's 28 × 28 floating-point probability grid is resized inside each detected box and thresholded rather than predicted as a full-image binary map. At test time, Detectron pads that 28 × 28 probability map with a 1-pixel border of zeros, resizes the continuous probabilities bilinearly to the exact pixel dimensions of the detected box, and only then thresholds at 0.5. Thresholding after bilinear upsampling produces smoother contours than resizing a binary 28 × 28 bitmap would, because the 0.5 level set of a bilinear surface cuts diagonally across grid cells.
Figure 5 lets you test both halves of that trade-off: switch the mask resolution from 7 × 7 up to 56 × 56, and slide the detected box's right edge inward to see what happens when the box head clips part of an object.
At 0 px (a tight box), switching from 7 × 7 to 14 × 14 (C4) and 28 × 28 (FPN) smooths the limbs and pushes pixel-wise mask IoU past COCO's strictest 0.90 and 0.95 thresholds, whereas 56 × 56 adds little extra IoU on this silhouette while quadrupling mask-pixel count. Drag the box right edge to −20 px: the mask cuts off at the dashed white box edge, turning the outstretched arm violet and dropping IoU below the upper COCO thresholds regardless of whether is 28 or 56.
Results and ablations
On COCO test-dev (Table 1, single models), Mask R-CNN with ResNet-101-C4 scores 33.1 mask AP, ResNet-101-FPN reaches 35.7 ( 58.0, 37.8), and ResNeXt-101-FPN reaches 37.1 ( 60.0, 39.4, 16.9, 39.9, 53.5). The prior challenge winners were MNC at 24.6 (COCO 2015) and FCIS at 29.2 with OHEM (online hard example mining, which trains preferentially on the highest-loss RoIs), rising to 33.6 as FCIS+++ (COCO 2016) after adding multi-scale training, multi-scale testing, and horizontal flip testing. Mask R-CNN beats FCIS+++ by 2.1 to 3.5 points with none of those test-time extras, and avoids FCIS's visual artifacts on overlapping objects (paper Figure 6) because overlapping people receive separate boxes and separate mask grids.
Mask R-CNN also improves bounding-box object detection even when its predicted masks are discarded at inference (Table 3, test-dev). Evaluating only the box head gives 38.2 for ResNet-101-FPN and 39.8 for ResNeXt-101-FPN, 3.0 points above the strongest earlier single model (Faster R-CNN with TDM, Top-Down Modulation, 36.8). Compared with the FPN paper's Faster R-CNN baseline (36.2), the authors break the 3.6-point jump into three pieces: +1.1 from RoIAlign alone (measured by training Mask R-CNN without its mask branch, giving 37.3), +0.9 from multi-task training with the mask branch (38.2), and +1.6 from upgrading to ResNeXt-101 (39.8). Supervising pixel masks makes the shared backbone learn sharper object boundaries that help the box head too. For ResNeXt-101-FPN, mask AP (37.1) trails box AP (39.8) by only 2.7 points.
Figure 6 brings together every major ablation table from the paper on one shared AP axis so you can compare the size of each design choice directly.
Walk through the tabs in order: decoupling the mask loss buys +5.5 AP; replacing RoIPool with RoIAlign buys +3.4 AP at stride 16 and +7.3 AP at stride 32 (where RoIWarp shows that alignment, not interpolation, produces the gain); an FCN mask head beats two- and three-layer MLP heads by +2.1 AP on ResNet-50-FPN (chosen so neither head starts from pre-trained convolutions); and deeper, pyramidal backbones climb steadily on minival from 30.3 (ResNet-50-C4) to 32.7 (ResNet-101-C4), 33.6 (ResNet-50-FPN), 35.4 (ResNet-101-FPN), and 36.7 (ResNeXt-101-FPN).
Appendix A tests generalization to street scenes on Cityscapes (2,975 finely annotated training images across 8 urban categories, ignoring the dataset's 20,000 coarse images). Using ResNet-50-FPN on fine annotations alone, Mask R-CNN scores 26.2 AP on Cityscapes test, beating DIN (20.0) and SGN (25.0) even though both trained on fine plus coarse data. The sharpest jumps appear on categories with many overlapping instances: person rises from 21.8 to 30.5 and car from 39.4 to 46.9. Initializing the seven shared categories from a COCO-pretrained model lifts Cityscapes test AP to 32.0.
Appendix B stacks later engineering upgrades on COCO minival (Table 8): an updated baseline (180k iterations and box NMS threshold 0.5 instead of 0.3), approximate end-to-end training (+0.6 mask AP and +1.2 box AP), ImageNet-5k pre-training, train-time scale augmentation, ResNeXt-152, non-local self-attention blocks, and multi-scale plus flip test-time augmentation. Together they push a single model to 41.8 mask AP and 47.3 box AP. All three winning teams of the COCO 2017 instance segmentation competition built their systems on Mask R-CNN.
Keypoints as one-hot masks
To demonstrate that the framework generalizes beyond pixel blobs, Section 5 applies Mask R-CNN to human pose estimation on COCO. Each person is annotated with 17 body keypoints: nose, eyes, ears, shoulders, elbows, wrists, hips, knees, and ankles. COCO grades pose predictions with keypoint average precision (, higher is better), which works like mask AP except that instead of pixel IoU it measures Object Keypoint Similarity (OKS), a distance-based score scaled by the person's area and averaged over thresholds 0.50 to 0.95.
Mask R-CNN reframes each keypoint as a binary mask containing exactly one foreground pixel. For every detected person RoI, a keypoint branch outputs 17 independent grids of logits at resolution, built on ResNet-FPN from eight convolutions of 512 channels, a transposed convolution, and a 2× bilinear upsampling layer. Because a person's left wrist sits at one single coordinate rather than covering a variable area, the training target for a visible keypoint is a one-hot map with a 1 at the labeled cell and 0 everywhere else. To encourage a single sharp peak inside that map, the loss applies a softmax cross-entropy across all = 56 × 56 = 3,136 spatial positions of that one keypoint's grid:
Notice how (7) differs from the rejected class softmax (4): the denominator sums over spatial pixels within one keypoint map so the 3,136 spatial probabilities sum to 1.0, while the 17 keypoint types remain separate channels. Doubling the grid from 28 × 28 to 56 × 56 is necessary for point accuracy: inside a 200-pixel-tall person box, one row of a 56 × 56 grid spans 3.6 pixels instead of 7.1.
With no specialized skeleton-graph post-processing, a single ResNet-50-FPN Mask R-CNN running at 5 frames per second reaches 62.7 on COCO test-dev (Table 4), 0.9 points above the multi-stage COCO 2016 winner (CMU-Pose+++, 61.8), and climbs to 63.1 when trained jointly with a person-mask branch. Localization alignment matters even more for single-pixel targets than for region masks: on FPN, which already includes stride-4 features, RoIAlign raises over RoIPool by 4.4 points, from 59.8 to 64.2 on minival (Table 6). Multi-task transfer is asymmetric, however (Table 5, person category on minival): adding the mask branch lifts person box AP (52.5 → 53.6) and keypoint AP (64.2 → 64.7), whereas adding the keypoint branch slightly lowers person box AP (53.6 → 52.0 with mask; 52.5 → 50.7 without mask) and person mask AP (45.8 → 45.1).
Limits and what came next
Mask R-CNN's simplicity carries four concrete limitations. First, because every mask is predicted inside its detected box, any bounding-box truncation cuts off the mask permanently (as Figure 5 demonstrates). Second, stretching a fixed 28 × 28 grid over a large object blurs thin structures like bicycle spokes, fingers, or power lines. Third, small objects remain weak ( for ResNet-101-FPN on COCO test-dev) because proposals under 56 pixels clip at and cover too few feature cells. Fourth, the architecture is not tuned for speed; the authors explicitly leave speed-accuracy engineering (varying image sizes and proposal counts) outside the paper's scope.
Low-data generalization also exposes a sharp failure mode in Appendix A. On Cityscapes, rare vehicle classes with only 200 to 500 fine training instances each (truck ~500, bus ~400, train ~200) suffer large drops between validation and test AP: fine-only val/test scores fall from 28.8 to 22.8 on truck, 53.5 to 32.2 on bus, and 33.0 to 18.6 on train. COCO pre-training raises every number and narrows the gaps (to 38.0/30.1, 57.5/40.9, and 41.2/30.9), but does not eliminate this domain shift, whereas well-represented classes like person and car agree within 1 point between validation and test.
Even so, Mask R-CNN became the standard evaluation harness for vision backbones for years afterward. Detectron2 reimplemented it in PyTorch with aligned=True fixing the half-cell RoIAlign offset. Self-supervised representation papers such as MAE measure transfer quality by fine-tuning a Mask R-CNN on COCO, and the Segment Anything paper benchmarks its masks against ViTDet, a Mask R-CNN detector running on a plain Vision Transformer backbone. Later architectures moved past two-stage proposals and NMS altogether, notably DETR and its mask-predicting descendants, while boundary-refinement heads such as PointRend (Kirillov et al., 2019) directly addressed the 28 × 28 resolution ceiling by re-evaluating uncertain edge points on finer features.
Questions you might still have
Can a predicted mask extend outside its bounding box?
No. The mask head predicts an m × m grid in the RoI's own coordinate frame and pastes it inside the detected box, so every pixel outside that box is zero. If the box head cuts off a person's arm, the mask head cannot recover the missing pixels.
Why is 28 × 28 resolution good enough for a whole object mask?
For a typical COCO object, 28 cells across a 300-pixel person puts one cell every 11 pixels, and bilinearly resizing the soft probabilities before applying the 0.5 threshold produces a smooth contour rather than jagged blocks. Fine structures on large objects still blur out: the keypoint head needed 56 × 56 for point precision, and later work such as PointRend (Kirillov et al., 2019) refines uncertain boundary points at higher resolution.
Does RoIAlign help bounding-box detection when masks are not used?
Yes. On stride-32 features (Table 2d), RoIAlign lifts box AP from 28.2 to 34.0 (+5.8 points). With an FPN backbone on COCO test-dev (Table 3), replacing RoIPool with RoIAlign in Faster R-CNN raises box AP from 36.2 to 37.3 (+1.1 points) with no mask branch at all. Boxes tolerate slight feature shifts better than pixel masks do, so the gain is smaller on FPN than for masks or keypoints.
How does Mask R-CNN differ from semantic segmentation models like U-Net?
A semantic segmentation model such as U-Net assigns one class label to every pixel in the image, so two people standing shoulder to shoulder merge into a single "person" blob. Mask R-CNN runs detection first: each person gets a separate bounding box and a separate binary mask inside that box, so touching or overlapping people remain distinct instances.
Why does the keypoint head use a softmax when the mask head rejects one?
They normalize over completely different axes. The mask head rejects a softmax across the 80 classes at one pixel because classes should not compete once the box branch has named the object. The keypoint head takes a softmax across the 56 × 56 = 3,136 spatial locations of a single keypoint's map because a person has one left shoulder at one location. The 17 keypoint types remain independent maps with no competition between them.
Is Mask R-CNN trained end to end?
Not in the main paper experiments. All main ablations train the Region Proposal Network separately with unshared features so the second stage can be modified without retraining proposals, and the timing model uses Faster R-CNN's 4-step alternating training to share features. Appendix B adds Faster R-CNN's approximate end-to-end training, which ignores gradients with respect to the RoI box coordinates, gaining 0.6 mask AP and 1.2 box AP.
Footnotes & further reading
- The paper: He, Gkioxari, Dollár & Girshick, Mask R-CNN (ICCV 2017 Marr Prize; IEEE TPAMI, DOI 10.1109/TPAMI.2018.2844175). Reference code: Detectron (Caffe2) and its successor Detectron2 (PyTorch).
- The detector it extends: Ren, He, Girshick & Sun, Faster R-CNN: Towards Real-Time Object Detection with Region Proposal Networks (see the Faster R-CNN explainer), and Girshick, Fast R-CNN, which introduced RoIPool and the joint classification and box regression losses.
- The backbones: Lin, Dollár, Girshick, He, Hariharan & Belongie, Feature Pyramid Networks for Object Detection (equation (1) is the level assignment rule); He, Zhang, Ren & Sun, ResNet (see the ResNet explainer); Xie et al., Aggregated Residual Transformations for Deep Neural Networks (ResNeXt).
- The systems it compares with: Dai, He & Sun, Instance-aware Semantic Segmentation via Multi-task Network Cascades (MNC, which introduced RoIWarp); Li, Qi, Dai, Ji & Wei, Fully Convolutional Instance-aware Semantic Segmentation (FCIS); Long, Shelhamer & Darrell, Fully Convolutional Networks for Semantic Segmentation (the per-pixel softmax compared in Table 2b); Ronneberger, Fischer & Brox, U-Net. Bilinear feature sampling draws on Jaderberg et al., Spatial Transformer Networks.
- The benchmarks: Lin et al., Microsoft COCO: Common Objects in Context (evaluation code: pycocotools), and Cordts et al., The Cityscapes Dataset for Semantic Urban Scene Understanding.
- Later work: Kirillov, Wu, He & Girshick, PointRend: Image Segmentation as Rendering; Li, Mao, Girshick & He, Exploring Plain Vision Transformer Backbones for Object Detection (ViTDet); Carion et al., DETR; Kirillov et al., Segment Anything.
How could this explainer be improved? Found an error, or something unclear? I read every message.