Algorithm Search⌘K

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.

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
Properties
deterministiclearnednetwork cost excludedquantization free
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 KK masks of m×mm \times m 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 FF with CC channels, each a grid of WF×HFW_F \times H_F cells, from a backbone network with stride SS pixels per cell;
  • for each of RR boxes, a box b=(x1,y1,x2,y2)b = (x_1, y_1, x_2, y_2) in image coordinates, a class kk and KK mask logit grids of m×mm \times m, from the heads of the network;
  • the image size W×HW \times H, the output size PP of RoIAlign, the number ss of samples per bin side and the threshold θ\theta.

The center of pixel (u,v)(u, v) is the point (u,v)(u, v), and values are read as F[v][u]F[v][u]. A box in image coordinates goes to feature coordinates by x↦(x+12)/S−12x \mapsto (x + \tfrac12)/S - \tfrac12, which keeps the cell centers aligned (Lemma 2 of the proof).

The output is, for each box, a P×PP \times P feature grid per channel for the heads, and a binary mask of W×HW \times H pixels. In training there is also the mask loss of each positive box.

The algorithm

  1. ROI-ALIGN(F, b, P, s) ▷ b = (x1, y1, x2, y2) in feature coordinates
  2. 1bw ← (x2 - x1) / P ; bh ← (y2 - y1) / P
  3. 2for each bin (r, c) with 0 ≤ r, c < P do
  4. 3acc ← 0
  5. 4for each sample (a, d) with 0 ≤ a, d < s do
  6. 5y ← y1 + (r + (a + 1/2)/s) bh ; x ← x1 + (c + (d + 1/2)/s) bw
  7. 6acc ← acc + BILINEAR(F, x, y) ▷ 0 if the point is more than 1 cell outside
  8. 7out[r][c] ← acc / s^2
  9. PASTE-MASK(M, b, W, H, θ) ▷ M is m × m, b in image coordinates
  10. 8for each pixel (u, v) with x1 ≤ u < x2, y1 ≤ v < y2, 0 ≤ u < W, 0 ≤ v < H do
  11. 9mx ← (u - x1) m / (x2 - x1) - 1/2 ; my ← (v - y1) m / (y2 - y1) - 1/2
  12. 10out[v][u] ← 1 if BILINEAR(M, mx, my) ≥ θ, else 0 ▷ clamp to the mask, no zero rule
  13. 11return out

Lines L1 to L7 cut the box into P×PP \times P equal bins and average s×ss \times s bilinear samples at the centers of equal sub-rectangles of each bin. Nothing is rounded. The paper uses four samples per bin, s=2s = 2, 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 m×mm \times m cells of the box lands on the matching mask value. The mask is that of the predicted class kk, after the sigmoid, so M=σ(logits[k])M = \sigma(\text{logits}[k]). The paper thresholds at θ=0.5\theta = 0.5.

The mask loss for a positive box of true class kk with target tt (m×mm \times m values in {0,1}\{0, 1\}) is the mean over the m2m^2 cells of log⁡(1+ez)−tz\log(1 + e^z) - t z, where zz is the logit of mask kk. The total loss is L=Lcls+Lbox+LmaskL = L_{\mathrm{cls}} + L_{\mathrm{box}} + L_{\mathrm{mask}}. The target is the ground-truth mask of the object matched to the box, cut to the box and resampled to m×mm \times m. 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 28×2828 \times 28 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 4×44 \times 4 feature map with one channel, F[v][u]=u+4vF[v][u] = u + 4v, and the box (0.5,0.5,2.5,2.5)(0.5, 0.5, 2.5, 2.5) with P=2P = 2 and s=2s = 2. Then bw=bh=1b_w = b_h = 1. Bin (0,0)(0, 0) has samples at x,y∈{0.75,1.25}x, y \in \{0.75, 1.25\}. Their values are 0.75+30.75 + 3, 1.25+31.25 + 3, 0.75+50.75 + 5 and 1.25+51.25 + 5, and the mean is 5, the value at the bin center (1,1)(1, 1). The full output is

(56910).\begin{pmatrix} 5 & 6 \\ 9 & 10 \end{pmatrix}.

Move the box by 0.1 to the right, to (0.6,0.5,2.6,2.5)(0.6, 0.5, 2.6, 2.5): the output becomes 5.1,6.1,9.1,10.15.1, 6.1, 9.1, 10.1. Move it by 0.01 to the left, to (0.49,0.5,2.49,2.5)(0.49, 0.5, 2.49, 2.5): the output becomes 4.99,5.99,8.99,9.994.99, 5.99, 8.99, 9.99. 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 (10111415)\begin{pmatrix} 10 & 11 \\ 14 & 15 \end{pmatrix} for the first box and (9101314)\begin{pmatrix} 9 & 10 \\ 13 & 14 \end{pmatrix} for the box moved by 0.01. A move of 0.01 cell changes every output by 1.

For the paste, take the 2×22 \times 2 mask (0.90.20.80.1)\begin{pmatrix} 0.9 & 0.2 \\ 0.8 & 0.1 \end{pmatrix} and the box (−0.5,−0.5,3.5,3.5)(-0.5, -0.5, 3.5, 3.5), which covers the pixels 0 to 3 in both directions, in a 4×44 \times 4 image. Pixel u=1u = 1 goes to mx=1.5⋅2/4−0.5=0.25m_x = 1.5 \cdot 2/4 - 0.5 = 0.25, and pixel u=2u = 2 to mx=0.75m_x = 0.75. In row v=0v = 0, my=−0.25m_y = -0.25 is clamped to 0, so pixel (1,0)(1, 0) reads 0.75⋅0.9+0.25⋅0.2=0.725≥0.50.75 \cdot 0.9 + 0.25 \cdot 0.2 = 0.725 \ge 0.5 and pixel (2,0)(2, 0) reads 0.25⋅0.9+0.75⋅0.2=0.375<0.50.25 \cdot 0.9 + 0.75 \cdot 0.2 = 0.375 < 0.5. In row v=3v = 3, pixel (1,3)(1, 3) reads 0.75⋅0.8+0.25⋅0.1=0.6250.75 \cdot 0.8 + 0.25 \cdot 0.1 = 0.625 and pixel (2,3)(2, 3) reads 0.2750.275. 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 x↦(x+12)/S−12x \mapsto (x + \tfrac12)/S - \tfrac12 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 m×mm \times m 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 σ(z)−t\sigma(z) - t, 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 gg has WW columns and HH rows, the value of cell (i,j)(i, j) is g[j][i]g[j][i], and the center of the cell is the point (i,j)(i, j). A box is b=(x1,y1,x2,y2)b = (x_1, y_1, x_2, y_2) with x1<x2x_1 < x_2 and y1<y2y_1 < y_2. Let Dx=max⁡∣g[j][i+1]−g[j][i]∣D_x = \max |g[j][i+1] - g[j][i]| and Dy=max⁡∣g[j+1][i]−g[j][i]∣D_y = \max |g[j+1][i] - g[j][i]| over all valid indices.

Lemma 1 (bilinear interpolation). For (x,y)∈[0,W−1]×[0,H−1](x, y) \in [0, W-1] \times [0, H-1], BILINEAR returns

g^(x,y)=∑i,jg[j][i] Λ(x−i) Λ(y−j),Λ(t)=max⁡(0,1−∣t∣).\hat g(x, y) = \sum_{i, j} g[j][i]\, \Lambda(x - i)\, \Lambda(y - j), \qquad \Lambda(t) = \max(0, 1 - |t|).

The function g^\hat g (a) is a convex combination of at most four grid values, (b) equals αx+βy+γ\alpha x + \beta y + \gamma if g[j][i]=αi+βj+γg[j][i] = \alpha i + \beta j + \gamma for all cells, and (c) satisfies ∣g^(x,y)−g^(x′,y′)∣≤Dx∣x−x′∣+Dy∣y−y′∣|\hat g(x, y) - \hat g(x', y')| \le D_x |x - x'| + D_y |y - y'|.

Proof. Let x0=⌊x⌋x_0 = \lfloor x \rfloor, ax=x−x0a_x = x - x_0, and the same for yy. For i∉{x0,x0+1}i \notin \{x_0, x_0 + 1\} we have ∣x−i∣≥1|x - i| \ge 1 and Λ(x−i)=0\Lambda(x - i) = 0. Also Λ(x−x0)=1−ax\Lambda(x - x_0) = 1 - a_x and Λ(x−x0−1)=ax\Lambda(x - x_0 - 1) = a_x. So the sum has the four terms that the code computes, with weights (1−ax)(1−ay)(1 - a_x)(1 - a_y), ax(1−ay)a_x (1 - a_y), (1−ax)ay(1 - a_x) a_y and axaya_x a_y. These are nonnegative with sum 1, which is (a). At x=W−1x = W - 1 we have ax=0a_x = 0, so the clamped index min⁡(x0+1,W−1)\min(x_0 + 1, W - 1) gets weight 0 and does no harm.

For (b), ∑iΛ(x−i)=1\sum_i \Lambda(x - i) = 1 and ∑ii Λ(x−i)=(1−ax)x0+ax(x0+1)=x\sum_i i\, \Lambda(x - i) = (1 - a_x) x_0 + a_x (x_0 + 1) = x on [0,W−1][0, W - 1]. The sums split, and g^=αx+βy+γ\hat g = \alpha x + \beta y + \gamma.

For (c), in a cell [x0,x0+1]×[y0,y0+1][x_0, x_0 + 1] \times [y_0, y_0 + 1] the partial derivative in xx is (1−ay)(g[y0][x0+1]−g[y0][x0])+ay(g[y0+1][x0+1]−g[y0+1][x0])(1 - a_y)(g[y_0][x_0 + 1] - g[y_0][x_0]) + a_y (g[y_0 + 1][x_0 + 1] - g[y_0 + 1][x_0]), a convex combination of two horizontal differences, so its absolute value is at most DxD_x. The same holds in yy. g^\hat g 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 xx and then along yy gives the bound. □\square

Outside the grid the code first clamps xx to [0,W−1][0, W - 1] and yy to [0,H−1][0, H - 1]. Clamping is 1-Lipschitz, so (a) and (c) still hold on [−1,W]×[−1,H][-1, W] \times [-1, H]. Beyond that band the code returns 0, as the Detectron code does. This makes the result jump at x=−1x = -1, x=Wx = W, y=−1y = -1 and y=Hy = H.

Theorem 1 (RoIAlign). Let lines L1 to L7 run on a box bb with P×PP \times P bins and s×ss \times s samples per bin, and let every sample point lie in [−1,W]×[−1,H][-1, W] \times [-1, H].

  1. Sample points. Bin (r,c)(r, c) is the rectangle [x1+c bw,x1+(c+1)bw]×[y1+r bh,y1+(r+1)bh][x_1 + c\, b_w, x_1 + (c + 1) b_w] \times [y_1 + r\, b_h, y_1 + (r + 1) b_h], with bw=(x2−x1)/Pb_w = (x_2 - x_1)/P and bh=(y2−y1)/Pb_h = (y_2 - y_1)/P. Its samples are the centers of the s×ss \times s equal sub-rectangles of the bin, so the output is the midpoint rule for the mean of g^\hat g over the bin.
  2. Affine maps. If gg is affine as in Lemma 1(b) and the bin lies in [0,W−1]×[0,H−1][0, W - 1] \times [0, H - 1], then output (r,c)(r, c) is the value of the affine function at the bin center.
  3. Continuity. If bb and b′b' are two boxes with all samples in [0,W−1]×[0,H−1][0, W - 1] \times [0, H - 1], then every output changes by at most Dxmax⁡(∣x1−x1′∣,∣x2−x2′∣)+Dymax⁡(∣y1−y1′∣,∣y2−y2′∣)D_x \max(|x_1 - x_1'|, |x_2 - x_2'|) + D_y \max(|y_1 - y_1'|, |y_2 - y_2'|).
  4. Integer shifts. If g′[j+δy][i+δx]=g[j][i]g'[j + \delta_y][i + \delta_x] = g[j][i] for integers δx\delta_x, δy\delta_y, and the samples of bb in gg and of the shifted box b+(δx,δy,δx,δy)b + (\delta_x, \delta_y, \delta_x, \delta_y) in g′g' 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 (a,b)(a, b) of bin (r,c)(r, c) at y=y1+(r+(a+12)/s)bhy = y_1 + (r + (a + \tfrac12)/s) b_h and x=x1+(c+(b+12)/s)bwx = x_1 + (c + (b + \tfrac12)/s) b_w. The bin has width bwb_w, the sub-rectangles have width bw/sb_w / s, and sub-rectangle bb has its center at x1+c bw+(b+12)bw/sx_1 + c\, b_w + (b + \tfrac12) b_w / s. Line L7 divides the sum of line L6 by s2s^2.

(2) By Lemma 1(b), g^\hat g 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 (b+12)/s(b + \tfrac12)/s over b=0,…,s−1b = 0, \ldots, s - 1 is 12\tfrac12, so the mean point is (x1+(c+12)bw,y1+(r+12)bh)(x_1 + (c + \tfrac12) b_w, y_1 + (r + \tfrac12) b_h), the bin center.

(3) Each sample point has x=(1−t)x1+tx2x = (1 - t) x_1 + t x_2 with t=(c+(b+12)/s)/P∈(0,1)t = (c + (b + \tfrac12)/s)/P \in (0, 1). So ∣x−x′∣≤(1−t)∣x1−x1′∣+t∣x2−x2′∣≤max⁡(∣x1−x1′∣,∣x2−x2′∣)|x - x'| \le (1 - t)|x_1 - x_1'| + t |x_2 - x_2'| \le \max(|x_1 - x_1'|, |x_2 - x_2'|), and the same for yy. Lemma 1(c) bounds the change of each sample, and an average of numbers that each change by at most ϵ\epsilon changes by at most ϵ\epsilon.

(4) The sample points of the shifted box are the old ones plus (δx,δy)(\delta_x, \delta_y). An integer shift keeps the fractions axa_x and aya_y and adds (δx,δy)(\delta_x, \delta_y) to the four grid indices. So the four weights are the same, and the four grid values are the same by the hypothesis. □\square

Quantized RoI pooling does not satisfy (3). It rounds the box to whole cells, so its output is a step function of x1x_1: in the example of the main page a move of 0.010.01 cell changes every output by 1, while the RoIAlign output changes by 0.010.01.

Lemma 2 (feature coordinates). Let pixel uu cover the interval [u−12,u+12][u - \tfrac12, u + \tfrac12] and let cell ii of a feature map of stride SS cover pixels iSiS to iS+S−1iS + S - 1. The affine map ϕ(x)=(x+12)/S−12\phi(x) = (x + \tfrac12)/S - \tfrac12 sends the interval of cell ii, [iS−12,iS+S−12][iS - \tfrac12, iS + S - \tfrac12], onto [i−12,i+12][i - \tfrac12, i + \tfrac12], and the center iS+(S−1)/2iS + (S - 1)/2 to ii.

Proof. ϕ(iS−12)=i−12\phi(iS - \tfrac12) = i - \tfrac12 and ϕ(iS+S−12)=i+12\phi(iS + S - \tfrac12) = i + \tfrac12, and ϕ\phi is affine, so the midpoint goes to the midpoint ii. □\square

So the function image_to_feature puts a box on the feature map without the half-cell shift that the map x↦x/Sx \mapsto x / S 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 MM have m×mm \times m values in [0,1][0, 1], and let lines L8 to L11 paste it for box bb into a w×hw \times h image with threshold θ\theta.

  1. The pixel set. A pixel (u,v)(u, v) is visited if and only if 0≤u<w0 \le u < w, 0≤v<h0 \le v < h, x1≤u<x2x_1 \le u < x_2 and y1≤v<y2y_1 \le v < y_2. All other pixels are 0.
  2. Mask cells. Split the box into m×mm \times m equal cells. The center of cell (j,k)(j, k), the point (x1+(j+12)(x2−x1)/m, y1+(k+12)(y2−y1)/m)(x_1 + (j + \tfrac12)(x_2 - x_1)/m,\ y_1 + (k + \tfrac12)(y_2 - y_1)/m), goes to the point (j,k)(j, k) under the map of line L9. So a pixel at the center of a mask cell reads exactly that mask value.
  3. Constant masks. If all values of MM are μ\mu, the output is 1 exactly on the pixels of (1) when μ≥θ\mu \ge \theta, and 0 everywhere when μ<θ\mu < \theta.
  4. Step masks. Let mm be even and let M[k][j]=1M[k][j] = 1 for j<m/2j < m/2 and 0 otherwise, with θ=12\theta = \tfrac12. Then a visited pixel is 1 if and only if u≤(x1+x2)/2u \le (x_1 + x_2)/2.

Proof. (1) For an integer uu, u≥x1u \ge x_1 if and only if u≥⌈x1⌉u \ge \lceil x_1 \rceil, and u<x2u < x_2 if and only if u≤⌈x2⌉−1u \le \lceil x_2 \rceil - 1. Line L8 loops over exactly these integers, cut to the image.

(2) Put x=x1+(j+12)(x2−x1)/mx = x_1 + (j + \tfrac12)(x_2 - x_1)/m into mx=(x−x1)m/(x2−x1)−12m_x = (x - x_1) m / (x_2 - x_1) - \tfrac12. This gives mx=jm_x = j. The same holds for yy.

(3) By Lemma 1(a) with clamping, every interpolated value is μ\mu.

(4) The value at mxm_x does not depend on mym_y, since all rows are equal. For mx≤m/2−1m_x \le m/2 - 1 it is 1, for mx≥m/2m_x \ge m/2 it is 0, and in between it is 1−(mx−(m/2−1))=m/2−mx1 - (m_x - (m/2 - 1)) = m/2 - m_x. Clamping only moves points into the parts where the value is constant. So the value is at least 12\tfrac12 if and only if mx≤(m−1)/2m_x \le (m - 1)/2, that is (u−x1)m/(x2−x1)≤m/2(u - x_1) m / (x_2 - x_1) \le m / 2, that is u≤(x1+x2)/2u \le (x_1 + x_2)/2. □\square

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 mx=(u−x1)m/(x2−x1)m_x = (u - x_1) m / (x_2 - x_1) without the −12-\tfrac12 would shift the edge by half a mask cell to the right.

Theorem 3 (the mask loss). For logits zz and a binary target tt, the per-pixel term of mask_loss is ℓ(z,t)=max⁡(z,0)−tz+log⁡(1+e−∣z∣)\ell(z, t) = \max(z, 0) - t z + \log(1 + e^{-|z|}). Then:

  1. ℓ(z,t)=−tlog⁡σ(z)−(1−t)log⁡(1−σ(z))\ell(z, t) = -t \log \sigma(z) - (1 - t) \log(1 - \sigma(z)) with σ(z)=1/(1+e−z)\sigma(z) = 1/(1 + e^{-z}), the binary cross-entropy of the sigmoid.
  2. ∂ℓ/∂z=σ(z)−t\partial \ell / \partial z = \sigma(z) - t, ℓ\ell is strictly convex in zz, ℓ≥0\ell \ge 0, and ℓ(0,t)=log⁡2\ell(0, t) = \log 2.
  3. The loss for an RoI of class kk does not depend on the logits of the other K−1K - 1 masks, so their gradients from this RoI are zero.

Proof. (1) max⁡(z,0)+log⁡(1+e−∣z∣)=log⁡(1+ez)\max(z, 0) + \log(1 + e^{-|z|}) = \log(1 + e^z), checked separately for z≥0z \ge 0 and z<0z < 0. Also −log⁡σ(z)=log⁡(1+e−z)=log⁡(1+ez)−z-\log \sigma(z) = \log(1 + e^{-z}) = \log(1 + e^z) - z and −log⁡(1−σ(z))=log⁡(1+ez)-\log(1 - \sigma(z)) = \log(1 + e^z). So the right side is t(log⁡(1+ez)−z)+(1−t)log⁡(1+ez)=log⁡(1+ez)−tzt (\log(1 + e^z) - z) + (1 - t) \log(1 + e^z) = \log(1 + e^z) - t z.

(2) The derivative of log⁡(1+ez)\log(1 + e^z) is σ(z)\sigma(z), and the second derivative is σ(z)(1−σ(z))>0\sigma(z)(1 - \sigma(z)) > 0. Both terms of (1) are nonnegative because σ∈(0,1)\sigma \in (0, 1). At z=0z = 0 the value is log⁡2\log 2.

(3) The code reads only logits[k]. □\square

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 O(1)O(1) per channel, so RoIAlign on a map with CC channels costs O(CP2s2)O(C P^2 s^2) per box. Pasting costs O(1)O(1) per visited pixel, at most O(wh)O(w h) per box. The loss costs O(m2)O(m^2) 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 RR be the number of boxes, CC the number of channels and AA the total area of the boxes in pixels.

  • RoIAlign, lines L1 to L7, makes P2s2P^2 s^2 samples per box, each of cost O(1)O(1) per channel: O(RCP2s2)O(R C P^2 s^2) in total.
  • Pasting, lines L8 to L11, costs O(1)O(1) per pixel in the box, so O(A)O(A) in total, and A≤RWHA \le R W H.
  • The mask loss costs O(m2)O(m^2) per positive box. Only the mask of the true class is read.

The output takes O(RCP2)O(R C P^2) for the RoI features and O(RWH)O(R W H) for full-size masks. Implementations often keep the m×mm \times m 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 KK masks and the class head chooses one. The loss of a box touches only one of them.
  • Masks at fixed resolution. The mask has m×mm \times m 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 m×mm \times m 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 m×mm \times m 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 x/Sx / S instead of (x+12)/S−12(x + \tfrac12)/S - \tfrac12 shifts all features by up to half a cell. Use the same convention in training and at inference.
  • The paste offset. Without the −12-\tfrac12 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 KK 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 m×mm \times m 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.

mask_r_cnn.pyI0RawGitHub
# 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

  1. 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)
  2. 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
  3. 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
  4. 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
  5. 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
  6. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example