Algorithmadvanced
Mask R-CNN
Also called Mask RCNN.
Faster R-CNN with RoIAlign and a third head that predicts a binary mask per class for each detection, for instance segmentation.
- Solves
- Instance segmentation
- Time
- O(R C P^2 s^2 + R W H) worstO(R C P^2 s^2 + A) average · best
- Space
- O(R C P^2 + R W H) extra
- Where
- A = the total area in pixels of the R boxes; C = the number of feature channels; H = the image height; P = the side of the RoIAlign output; R = the number of boxes; W = the image width; s = the samples per bin side
- Model
- Real RAM
- Properties
- deterministiclearnednetwork cost excludedquantization free
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Kaiming He, Georgia Gkioxari, Piotr Dollar, Ross Girshick, 2017
Mask R-CNN is a two-stage detector for instance segmentation. It extends Faster R-CNN with a third head: for each detected box, a small fully convolutional network predicts masks of values, one for each class, and the mask of the predicted class is resized to the box and thresholded. The paper made two changes that are not learned. RoIAlign replaces RoI pooling: it reads the feature map at points with no rounding, by bilinear interpolation, so the features stay aligned with the box. The mask loss is a per-pixel sigmoid cross-entropy on the mask of the true class only, so the classes do not compete for a pixel. This page covers RoIAlign, the pasting of the mask into the image and the mask loss, with proofs and code. The network, its training and its cost are outside the page, and the quality of its masks is a benchmark result, not a theorem.
In plain words
First a detector finds boxes around objects and says what class each object is. For each box, the method reads the features under the box into a small grid of fixed size. It does not snap the box to the coarse grid of the features. It reads values at exact points between grid cells by mixing the four nearest cells. A small network then draws a mask, a square of numbers between 0 and 1 that says which parts of the box belong to the object. It draws one mask for each class and keeps the one for the class that the detector chose. The method stretches this square to the size of the box, puts it in the image, and marks the pixels where the value is at least one half.
The problem
The input of the non-learned steps is:
- a feature map with channels, each a grid of cells, from a backbone network with stride pixels per cell;
- for each of boxes, a box in image coordinates, a class and mask logit grids of , from the heads of the network;
- the image size , the output size of RoIAlign, the number of samples per bin side and the threshold .
The center of pixel is the point , and values are read as . A box in image coordinates goes to feature coordinates by , which keeps the cell centers aligned (Lemma 2 of the proof).
The output is, for each box, a feature grid per channel for the heads, and a binary mask of pixels. In training there is also the mask loss of each positive box.
The algorithm
ROI-ALIGN(F, b, P, s) ▷ b = (x1, y1, x2, y2) in feature coordinates- 1
bw ← (x2 - x1) / P ; bh ← (y2 - y1) / P - 2
for each bin (r, c) with 0 ≤ r, c < P do - 3
acc ← 0 - 4
for each sample (a, d) with 0 ≤ a, d < s do - 5
y ← y1 + (r + (a + 1/2)/s) bh ; x ← x1 + (c + (d + 1/2)/s) bw - 6
acc ← acc + BILINEAR(F, x, y) ▷ 0 if the point is more than 1 cell outside - 7
out[r][c] ← acc / s^2 PASTE-MASK(M, b, W, H, θ) ▷ M is m × m, b in image coordinates- 8
for each pixel (u, v) with x1 ≤ u < x2, y1 ≤ v < y2, 0 ≤ u < W, 0 ≤ v < H do - 9
mx ← (u - x1) m / (x2 - x1) - 1/2 ; my ← (v - y1) m / (y2 - y1) - 1/2 - 10
out[v][u] ← 1 if BILINEAR(M, mx, my) ≥ θ, else 0 ▷ clamp to the mask, no zero rule - 11
return out
Lines L1 to L7 cut the box into equal bins and average bilinear samples at the centers of equal sub-rectangles of each bin. Nothing is rounded. The paper uses four samples per bin, , and allows the maximum or the average; the Detectron code and this page use the average. BILINEAR mixes the four nearest cells, clamps points that are less than one cell outside the map, and gives 0 for points further out, as the Detectron code does.
Lines L8 to L11 run at inference. Each pixel center in the box goes to mask coordinates so that the center of each of the cells of the box lands on the matching mask value. The mask is that of the predicted class , after the sigmoid, so . The paper thresholds at .
The mask loss for a positive box of true class with target ( values in ) is the mean over the cells of , where is the logit of mask . The total loss is . The target is the ground-truth mask of the object matched to the box, cut to the box and resampled to . A box is positive if its IoU with a ground-truth box is at least 0.5.
The network around these steps, from Section 3 of the paper: a backbone (ResNet with a C4 head, or ResNet with a feature pyramid network) gives the feature map, a region proposal network gives the boxes, and the box head classifies and refines them. The mask head is a small stack of convolutions and a deconvolution on the RoIAlign output, and its masks are in the FPN design of Table 2e. At inference the box head runs first, then non-maximum suppression, and the mask head runs only on the top 100 boxes.
Example
Take a feature map with one channel, , and the box with and . Then . Bin has samples at . Their values are , , and , and the mean is 5, the value at the bin center . The full output is
Move the box by 0.1 to the right, to : the output becomes . Move it by 0.01 to the left, to : the output becomes . Each output follows the box.
Quantized RoI max pooling, which rounds the box to whole cells (half up) and takes the maximum of each bin, gives for the first box and for the box moved by 0.01. A move of 0.01 cell changes every output by 1.
For the paste, take the mask and the box , which covers the pixels 0 to 3 in both directions, in a image. Pixel goes to , and pixel to . In row , is clamped to 0, so pixel reads and pixel reads . In row , pixel reads and pixel reads . The pasted mask is 1 in columns 0 and 1 and 0 in columns 2 and 3, in all four rows.
Correctness
The non-learned steps have proofs, in proofs/correctness.md. These are theorems:
- Bilinear sampling. Each sample is a convex combination of at most four map values, it is exact for a map that is affine in the cell index, and it is Lipschitz in the sample point with the largest difference of neighboring cells as the constant.
- RoIAlign. The samples are the midpoint rule for the mean of the interpolated map over each bin. On an affine map each output is the value at the bin center. Each output is a Lipschitz function of the box, while samples stay inside the map, and a shift of map and box by whole cells does not change it. RoI pooling has none of these, because of the rounding.
- Coordinates. The map sends the pixels of a feature cell onto that cell, with centers on centers.
- Pasting. Exactly the pixels whose centers are in the half-open box are visited. The centers of the cells of the box read the matching mask values. For a mask that is 1 on the left half and 0 on the right, the pasted edge is at the middle of the box, with no shift of half a mask cell.
- Mask loss. The per-pixel term is the binary cross-entropy of the sigmoid, convex in the logit with gradient , and it does not depend on the masks of the other classes.
The quality of the masks is a benchmark result. The paper reports mask AP on COCO, with ablations in Table 2 that compare RoIAlign with RoI pooling and independent sigmoid masks with a per-pixel softmax over the classes. In both cases the variant of this page gave higher AP in the setting of the paper.
Proof: Correctness of RoIAlign, mask pasting and the mask lossfull
This proof covers the parts of Mask R-CNN that are not learned: RoIAlign (lines L1 to L7 of the main page), the pasting of a mask into the image (lines L8 to L11) and the mask loss. It says nothing about the quality of the network weights. That is a benchmark question.
Conventions. A grid has columns and rows, the value of cell is , and the center of the cell is the point . A box is with and . Let and over all valid indices.
Lemma 1 (bilinear interpolation). For , BILINEAR returns
The function (a) is a convex combination of at most four grid values, (b) equals if for all cells, and (c) satisfies .
Proof. Let , , and the same for . For we have and . Also and . So the sum has the four terms that the code computes, with weights , , and . These are nonnegative with sum 1, which is (a). At we have , so the clamped index gets weight 0 and does no harm.
For (b), and on . The sums split, and .
For (c), in a cell the partial derivative in is , a convex combination of two horizontal differences, so its absolute value is at most . The same holds in . is continuous across cell borders, since there one weight is zero, and so it is Lipschitz with these constants along each axis. Going first along and then along gives the bound.
Outside the grid the code first clamps to and to . Clamping is 1-Lipschitz, so (a) and (c) still hold on . Beyond that band the code returns 0, as the Detectron code does. This makes the result jump at , , and .
Theorem 1 (RoIAlign). Let lines L1 to L7 run on a box with bins and samples per bin, and let every sample point lie in .
- Sample points. Bin is the rectangle , with and . Its samples are the centers of the equal sub-rectangles of the bin, so the output is the midpoint rule for the mean of over the bin.
- Affine maps. If is affine as in Lemma 1(b) and the bin lies in , then output is the value of the affine function at the bin center.
- Continuity. If and are two boxes with all samples in , then every output changes by at most .
- Integer shifts. If for integers , , and the samples of in and of the shifted box in both lie in the region where the two grids agree up to the shift, then the outputs are equal.
Proof. (1) Line L5 places sample of bin at and . The bin has width , the sub-rectangles have width , and sub-rectangle has its center at . Line L7 divides the sum of line L6 by .
(2) By Lemma 1(b), is affine on the bin, so the mean of the samples is the affine function at the mean of the sample points. The mean of over is , so the mean point is , the bin center.
(3) Each sample point has with . So , and the same for . Lemma 1(c) bounds the change of each sample, and an average of numbers that each change by at most changes by at most .
(4) The sample points of the shifted box are the old ones plus . An integer shift keeps the fractions and and adds to the four grid indices. So the four weights are the same, and the four grid values are the same by the hypothesis.
Quantized RoI pooling does not satisfy (3). It rounds the box to whole cells, so its output is a step function of : in the example of the main page a move of cell changes every output by 1, while the RoIAlign output changes by .
Lemma 2 (feature coordinates). Let pixel cover the interval and let cell of a feature map of stride cover pixels to . The affine map sends the interval of cell , , onto , and the center to .
Proof. and , and is affine, so the midpoint goes to the midpoint .
So the function image_to_feature puts a box on the feature map without the half-cell shift that the map would cause. This is the alignment that the option aligned=True of Detectron2 gives, written for integer pixel centers.
Theorem 2 (pasting). Let the mask have values in , and let lines L8 to L11 paste it for box into a image with threshold .
- The pixel set. A pixel is visited if and only if , , and . All other pixels are 0.
- Mask cells. Split the box into equal cells. The center of cell , the point , goes to the point under the map of line L9. So a pixel at the center of a mask cell reads exactly that mask value.
- Constant masks. If all values of are , the output is 1 exactly on the pixels of (1) when , and 0 everywhere when .
- Step masks. Let be even and let for and 0 otherwise, with . Then a visited pixel is 1 if and only if .
Proof. (1) For an integer , if and only if , and if and only if . Line L8 loops over exactly these integers, cut to the image.
(2) Put into . This gives . The same holds for .
(3) By Lemma 1(a) with clamping, every interpolated value is .
(4) The value at does not depend on , since all rows are equal. For it is 1, for it is 0, and in between it is . Clamping only moves points into the parts where the value is constant. So the value is at least if and only if , that is , that is .
Part 4 shows that the 0.5 level of the interpolated mask is at the true position of the step, not shifted by half a mask cell. A map without the would shift the edge by half a mask cell to the right.
Theorem 3 (the mask loss). For logits and a binary target , the per-pixel term of mask_loss is . Then:
- with , the binary cross-entropy of the sigmoid.
- , is strictly convex in , , and .
- The loss for an RoI of class does not depend on the logits of the other masks, so their gradients from this RoI are zero.
Proof. (1) , checked separately for and . Also and . So the right side is .
(2) The derivative of is , and the second derivative is . Both terms of (1) are nonnegative because . At the value is .
(3) The code reads only logits[k].
Part 3 is the point of the design in the paper: with a softmax over the classes at each pixel the masks of different classes would compete, and with independent sigmoids they do not. That this gives better masks is a benchmark result of the paper, not a consequence of the theorem.
Cost. Line L6 costs per channel, so RoIAlign on a map with channels costs per box. Pasting costs per visited pixel, at most per box. The loss costs per RoI. All counts are in the real-RAM model.
Complexity
The model is the real RAM. The cost of the backbone, the region proposals and the heads is outside the page. Let be the number of boxes, the number of channels and the total area of the boxes in pixels.
- RoIAlign, lines L1 to L7, makes samples per box, each of cost per channel: in total.
- Pasting, lines L8 to L11, costs per pixel in the box, so in total, and .
- The mask loss costs per positive box. Only the mask of the true class is read.
The output takes for the RoI features and for full-size masks. Implementations often keep the masks with their boxes and paste only when needed. The paper reports that the system runs at about 5 frames per second; that is a measurement on the GPU of 2017 and includes the network.
Properties
- No quantization. RoIAlign never rounds a coordinate. Its output is a continuous function of the box, so small errors of the box give small changes of the features.
- Masks per class. The head predicts masks and the class head chooses one. The loss of a box touches only one of them.
- Masks at fixed resolution. The mask has values whatever the box size, so large objects get coarse masks. The paste interpolates, but it cannot add detail.
- Box-limited masks. Pixels outside the box are always 0. An error of the box cuts the mask.
- Overlap. Masks of different instances can overlap. A panoptic output needs an extra rule to give each pixel to one segment.
- Learned. The masks depend on the training data and the weights. There is no guarantee for a given image.
Variants and improvements
- RoIAlign options. Detectron2 has an option aligned that shifts the box by half a pixel before sampling, as on this page, and a sampling ratio that can adapt the number of samples to the box size. The first Detectron code did not shift.
- Keypoints. The paper also predicts human keypoints with the same structure: one map per keypoint with a single hot pixel and a softmax over the pixels.
- Panoptic FPN. A semantic segmentation branch on the same FPN features adds stuff classes, which gives a panoptic segmentation.
- Better masks. Later work rescores masks by their predicted IoU, refines the mask at the boundary, or cascades several box heads.
- Single-stage and set-based methods. Other instance segmentation methods predict masks without RoIs, for example from dense grids of mask coefficients. Set-based detectors in the style of DETR predict a set of masks with a matching loss.
When to use it
Use Mask R-CNN when you need one mask per object, of a known set of classes, and a GPU is available: counting cells or people, robot grasping, or the instance part of a panoptic system. It is a strong and well documented baseline, with public code and weights. If you need only class labels per pixel, use semantic segmentation. If you need fine boundaries on large objects, add a refinement step, because of the masks. Without a GPU, or without training data, classical segmentation with graph cuts or watershed on a given box may be enough.
Pitfalls
- The half-pixel offset. Mapping a box with instead of shifts all features by up to half a cell. Use the same convention in training and at inference.
- The paste offset. Without the of line L9 the pasted mask moves by half a mask cell, which is several pixels for large boxes.
- Pasting at the wrong size. Paste the mask with the box of the final, refined detection, not the proposal that the mask head saw, as the paper does at inference.
- Softmax across classes. A softmax over the masks at each pixel makes the classes compete, which the paper reports as worse.
- Samples outside the map. Boxes that reach far outside the image get zeros for the far samples. This is a rule of the code, not of the paper, and implementations differ.
- Overlapping masks. Instance masks are not a partition. Before computing a panoptic score, resolve the overlaps, for example by detection score.
Implementations
The network is outside this page. The Python code in impl/python/mask_r_cnn.py implements only the steps that are not learned: bilinear sampling with the Detectron border rule, RoIAlign, the map from image to feature coordinates, the paste of an mask into the image, and the mask loss. The tests use feature maps and logits that they build by hand or with a fixed seed. They check the example above, the tent-function form of bilinear sampling, exact values on constant and affine maps, invariance to a shift by whole cells, the bounded change under a small move of the box against the jump of a quantized RoI pooling, the zero rule far outside the map, the pasted pixel set of full and half masks, and that the loss ignores the masks of the other classes.
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mask-r-cnn/. The authors are listed in prov/24WQPY.jsonl.
"""The non-learned parts of Mask R-CNN: RoIAlign sampling, mask pasting and the mask loss.
Coordinates follow one convention: the center of cell (u, v) of a grid is the
point (u, v), and grid values are g[v][u]. A box is (x1, y1, x2, y2) in
continuous coordinates. For a feature map of stride s, image coordinate x
maps to feature coordinate (x + 0.5) / s - 0.5 (see image_to_feature).
The network that makes the feature map and the mask logits is not here.
"""
import math
def bilinear(g, x, y, zero_outside=True):
"""Bilinear interpolation of grid g at (x, y).
With zero_outside, a point with x < -1, x > W, y < -1 or y > H gives 0, as in
the Detectron code. Other points are clamped to [0, W - 1] x [0, H - 1].
"""
h, w = len(g), len(g[0])
if zero_outside and (x < -1.0 or x > w or y < -1.0 or y > h):
return 0.0
x = min(max(x, 0.0), w - 1.0)
y = min(max(y, 0.0), h - 1.0)
x0, y0 = int(math.floor(x)), int(math.floor(y))
x1, y1 = min(x0 + 1, w - 1), min(y0 + 1, h - 1)
ax, ay = x - x0, y - y0
top = (1 - ax) * g[y0][x0] + ax * g[y0][x1]
bottom = (1 - ax) * g[y1][x0] + ax * g[y1][x1]
return (1 - ay) * top + ay * bottom
def roi_align(feat, box, p, s):
"""Return the p x p output of RoIAlign on the feature map feat for box, with s x s samples per bin."""
x1, y1, x2, y2 = box
bw, bh = (x2 - x1) / p, (y2 - y1) / p # @line L1
out = [[0.0] * p for _ in range(p)]
for r in range(p): # @line L2
for c in range(p):
acc = 0.0 # @line L3
for a in range(s): # @line L4
for b in range(s):
y = y1 + (r + (a + 0.5) / s) * bh # @line L5
x = x1 + (c + (b + 0.5) / s) * bw
acc += bilinear(feat, x, y) # @line L6
out[r][c] = acc / (s * s) # @line L7
return out
def paste_mask(mask, box, w, h, thresh=0.5):
"""Paste an m x m mask of probabilities for box (image coordinates) into a w x h binary image."""
m = len(mask)
x1, y1, x2, y2 = box
out = [[0] * w for _ in range(h)]
for v in range(max(0, math.ceil(y1)), min(h, math.ceil(y2))): # @line L8
for u in range(max(0, math.ceil(x1)), min(w, math.ceil(x2))):
mx = (u - x1) * m / (x2 - x1) - 0.5 # @line L9
my = (v - y1) * m / (y2 - y1) - 0.5
out[v][u] = 1 if bilinear(mask, mx, my, zero_outside=False) >= thresh else 0 # @line L10
return out # @line L11
def image_to_feature(box, stride):
"""Map a box from image coordinates to the coordinates of a feature map with the given stride."""
return tuple((x + 0.5) / stride - 0.5 for x in box)
def mask_loss(logits, k, target):
"""Mean binary cross-entropy of the mask of class k against a binary target; the other K - 1 masks do not count."""
m = len(target)
total = 0.0
for v in range(m):
for u in range(m):
z, t = logits[k][v][u], target[v][u]
# log(1 + e^z) - t z, computed without overflow
total += max(z, 0.0) - t * z + math.log1p(math.exp(-abs(z)))
return total / (m * m)
test_mask_r_cnn.py 130 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mask-r-cnn/. The authors are listed in prov/24WQPY.jsonl.
import math
import random
from mask_r_cnn import bilinear, image_to_feature, mask_loss, paste_mask, roi_align
def tent_interp(g, x, y):
"""Bilinear interpolation written as a sum of tent functions, for points inside the grid."""
return sum(
g[j][i] * max(0.0, 1 - abs(x - i)) * max(0.0, 1 - abs(y - j))
for j in range(len(g))
for i in range(len(g[0]))
)
def roi_pool(feat, box, p):
"""Quantized RoI max pooling, for contrast: round the box, split it into integer bins, take the max."""
x1, y1, x2, y2 = (int(math.floor(c + 0.5)) for c in box)
rw, rh = max(x2 - x1 + 1, 1), max(y2 - y1 + 1, 1)
out = [[0.0] * p for _ in range(p)]
for r in range(p):
for c in range(p):
ys = range(y1 + math.floor(r * rh / p), y1 + math.ceil((r + 1) * rh / p))
xs = range(x1 + math.floor(c * rw / p), x1 + math.ceil((c + 1) * rw / p))
out[r][c] = max(feat[y][x] for y in ys for x in xs)
return out
def test_linear_map_example():
feat = [[x + 4 * y for x in range(4)] for y in range(4)]
out = roi_align(feat, (0.5, 0.5, 2.5, 2.5), 2, 2)
assert all(abs(a - b) < 1e-12 for ra, rb in zip(out, [[5, 6], [9, 10]]) for a, b in zip(ra, rb))
moved = roi_align(feat, (0.6, 0.5, 2.6, 2.5), 2, 2)
assert abs(moved[0][0] - 5.1) < 1e-12
def test_bilinear_equals_tent_sum_inside_the_grid():
rng = random.Random(21)
g = [[rng.uniform(-1, 1) for _ in range(6)] for _ in range(5)]
for _ in range(200):
x, y = rng.uniform(0, 5), rng.uniform(0, 4)
assert abs(bilinear(g, x, y) - tent_interp(g, x, y)) < 1e-12
def test_constant_and_linear_maps():
rng = random.Random(22)
const = [[3.5] * 8 for _ in range(7)]
lin = [[0.3 * x - 1.7 * y + 2.0 for x in range(8)] for y in range(7)]
for _ in range(30):
x1, y1 = rng.uniform(0, 3), rng.uniform(0, 3)
box = (x1, y1, x1 + rng.uniform(0.5, 4), y1 + rng.uniform(0.5, 3))
for s in (1, 2, 3):
out = roi_align(const, box, 3, s)
assert all(abs(v - 3.5) < 1e-12 for row in out for v in row)
out = roi_align(lin, box, 3, s)
bw, bh = (box[2] - box[0]) / 3, (box[3] - box[1]) / 3
for r in range(3):
for c in range(3):
cx, cy = box[0] + (c + 0.5) * bw, box[1] + (r + 0.5) * bh
assert abs(out[r][c] - (0.3 * cx - 1.7 * cy + 2.0)) < 1e-12
def test_shift_by_whole_cells():
rng = random.Random(23)
feat = [[rng.uniform(0, 1) for _ in range(10)] for _ in range(9)]
shifted = [[feat[y - 2][x - 3] if y >= 2 and x >= 3 else 0.0 for x in range(10)] for y in range(9)]
box = (0.3, 0.8, 4.1, 5.2)
a = roi_align(feat, box, 4, 2)
b = roi_align(shifted, (box[0] + 3, box[1] + 2, box[2] + 3, box[3] + 2), 4, 2)
assert all(abs(x - y) < 1e-12 for ra, rb in zip(a, b) for x, y in zip(ra, rb))
def test_output_is_continuous_in_the_box_but_pooling_jumps():
rng = random.Random(24)
feat = [[rng.uniform(0, 1) for _ in range(8)] for _ in range(8)]
box = (1.45, 1.2, 5.3, 6.1)
nudged = (1.55, 1.2, 5.3, 6.1)
a, b = roi_align(feat, box, 2, 2), roi_align(feat, nudged, 2, 2)
# Each sample moves by at most 0.1 cell, and bilinear interpolation is Lipschitz with constant 2 max |f|.
assert max(abs(x - y) for ra, rb in zip(a, b) for x, y in zip(ra, rb)) <= 0.2
pa, pb = roi_pool(feat, box, 2), roi_pool(feat, nudged, 2)
assert pa != pb # the rounded box jumps from x1 = 1 to x1 = 2
def test_samples_far_outside_give_zero():
feat = [[1.0] * 4 for _ in range(4)]
assert bilinear(feat, -1.5, 1.0) == 0.0 and bilinear(feat, 1.0, 4.5) == 0.0
assert bilinear(feat, -0.5, 1.0) == 1.0 # between -1 and 0 the value is clamped
out = roi_align(feat, (-4.0, 0.0, 0.0, 2.0), 2, 1)
assert out[0][0] == 0.0 and out[0][1] == 1.0
def test_image_to_feature():
# Pixels 0 .. 3 form cell 0 of a stride 4 map; their area is [-0.5, 3.5] and the cell center is 1.5.
assert image_to_feature((-0.5, -0.5, 3.5, 7.5), 4) == (-0.5, -0.5, 0.5, 1.5)
assert image_to_feature((1.5, 1.5, 1.5, 1.5), 4) == (0.0, 0.0, 0.0, 0.0)
def test_paste_example_and_full_masks():
mask = [[0.9, 0.2], [0.8, 0.1]]
out = paste_mask(mask, (-0.5, -0.5, 3.5, 3.5), 6, 5)
assert out == [[1, 1, 0, 0, 0, 0]] * 4 + [[0] * 6]
full = paste_mask([[1.0] * 28 for _ in range(28)], (1.2, 0.7, 4.9, 3.1), 7, 5)
inside = {(u, v) for v in range(5) for u in range(7) if 1.2 <= u < 4.9 and 0.7 <= v < 3.1}
assert {(u, v) for v in range(5) for u in range(7) if full[v][u]} == inside
def test_half_mask_fills_half_the_box():
m = 28
left = [[1.0 if j < m // 2 else 0.0 for j in range(m)] for _ in range(m)]
out = paste_mask(left, (-0.5, -0.5, 15.5, 7.5), 16, 8)
assert all(out[v] == [1] * 8 + [0] * 8 for v in range(8))
def test_mask_loss_uses_only_the_class_mask():
rng = random.Random(25)
m, k = 4, 3
target = [[rng.randrange(2) for _ in range(m)] for _ in range(m)]
logits = [[[rng.uniform(-3, 3) for _ in range(m)] for _ in range(m)] for _ in range(k)]
base = mask_loss(logits, 1, target)
logits[0] = [[50.0] * m for _ in range(m)]
logits[2] = [[-50.0] * m for _ in range(m)]
assert mask_loss(logits, 1, target) == base
perfect = [[[40.0 if t else -40.0 for t in row] for row in target]]
assert mask_loss(perfect, 0, target) < 1e-15
zeros = [[[0.0] * m for _ in range(m)]]
assert abs(mask_loss(zeros, 0, target) - math.log(2)) < 1e-15
History
R-CNN (2014) classified warped crops of proposals, Fast R-CNN (2015) shared the network over the image with RoI pooling, and Faster R-CNN (2015) learned the proposals. Instance segmentation before 2017 often built masks from segment proposals and then classified them. He, Gkioxari, Dollar and Girshick (2017) added a mask head to Faster R-CNN in parallel with the box head and fixed the misalignment of RoI pooling with RoIAlign. The method won the Marr Prize at ICCV 2017. It became the standard baseline on COCO, and Detectron and Detectron2 made its code widely used.
References
- Kaiming He, Georgia Gkioxari, Piotr Dollar and Ross Girshick, Mask R-CNN, IEEE International Conference on Computer Vision (ICCV), 2017 (arXiv 1703.06870), Section 3 (the mask branch with K masks of m x m, the per-pixel sigmoid, the loss L = L_cls + L_box + L_mask on the k-th mask only, the paragraph RoIAlign with four sampled points per bin), Section 3.1 (training with positive RoIs at IoU 0.5 or more, inference on the top 100 boxes, resize to the box and threshold at 0.5), Section 4.2 and Table 2 (the ablations)
- Detectron2 documentation, detectron2.layers (ROIAlign with the options aligned and sampling_ratio, paste_masks_in_image), ROIAlign (aligned=True shifts the box by -0.5 before sampling, sampling_ratio of 0 or less is adaptive) and paste_masks_in_image
- Shaoqing Ren, Kaiming He, Ross Girshick and Jian Sun, Faster R-CNN, towards real-time object detection with region proposal networks, NIPS 2015, the region proposal network and the two-stage detector that Mask R-CNN extends
- Tsung-Yi Lin, Piotr Dollar, Ross Girshick, Kaiming He, Bharath Hariharan and Serge Belongie, Feature pyramid networks for object detection, CVPR 2017, the assignment of each RoI to a pyramid level by its size, used by the FPN backbone of Mask R-CNN
- Tsung-Yi Lin et al., Microsoft COCO, common objects in context, European Conference on Computer Vision (ECCV), 2014, the instance segmentation task and its mask AP, the benchmark of the Mask R-CNN paper
- Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Section 6.4, Semantic segmentation (the part on instance segmentation)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 24WQPY Edit this page History Report an error Markdown