Two-stage detectors and Mask R-CNN cut a fixed-size feature grid out of the backbone's feature map for every proposed box. RoIAlign does this without rounding any coordinate: it splits the box into equal bins, samples a few points per bin with bilinear interpolation and averages them. Implement it with the exact conventions of the widely used reference implementation.
bilinear_sample(feat, y, x) for a 2-D map feat of shape (H, W) and real coordinates (row y, column x), returning a float:
- If y<−1, y>H, x<−1 or x>W, return
0.0.
- Clamp negative coordinates to 0. Let y0=⌊y⌋. If y0≥H−1, set y0=y1=H−1 and y=H−1; otherwise y1=y0+1. Do the same for x with W.
- With ly=y−y0 and lx=x−x0, return
(1−ly)(1−lx)F[y0,x0]+(1−ly)lxF[y0,x1]+ly(1−lx)F[y1,x0]+lylxF[y1,x1].
roi_align(features, rois, output_size, spatial_scale=1.0, sampling_ratio=-1, aligned=True)
features is (C, H, W); rois is (R, 4) boxes [x1, y1, x2, y2] in input-image coordinates; output_size is an int or a pair (ph, pw). Return a float array (R, C, ph, pw).
- For each box let o=0.5 if
aligned else 0. The box start is (x1s−o, y1s−o) with s = spatial_scale, and its width and height are (x2−x1)s and (y2−y1)s. When aligned is false, raise the width and height to at least 1.
- Bin size: width /
pw and height / ph. Samples per bin: sampling_ratio along each axis if it is positive, otherwise ⌈height/ph⌉ rows and ⌈width/pw⌉ columns.
- Bin (i,j) with gh×gw samples averages
bilinear_sample (per channel) at rows ystart+ibh+(u+0.5)bh/gh for u=0..gh−1 and columns xstart+jbw+(v+0.5)bw/gw for v=0..gw−1, dividing the sum by max(ghgw,1).