Implement RoI max pooling for region features

Why it matters Fast R-CNN and Faster R-CNN used RoI pooling to feed region features into the box head; RoIAlign later removed the rounding.

Two-stage detectors cut a fixed-size feature grid out of the backbone map for every proposed box. RoI pooling does it with quantised bins and a max.

Write roi_pool(feat, rois, out_size, spatial_scale). feat is (C, H, W); rois is (R, 4) of image-space (x1, y1, x2, y2). For each roi: x_start = round(x1 * scale), x_end = round(x2 * scale) (and the same for y), using round half up, floor(v + 0.5). roi_w = max(x_end - x_start + 1, 1), roi_h likewise, bin_w = roi_w / out_size, bin_h = roi_h / out_size. Bin (ph, pw) covers rows floor(ph * bin_h) + y_start up to (not including) ceil((ph + 1) * bin_h) + y_start, and the same for columns; clip both ends to [0, H] and [0, W]. Each output is the max over the bin for each channel, or 0 if the bin is empty. Return (R, C, out_size, out_size).

Signaturedef roi_pool(feat, rois, out_size, spatial_scale)

Example

feat = arange(16).reshape(1, 4, 4), rois = [[0, 0, 3, 3]], out_size = 2, spatial_scale = 1 gives [[[[5, 7], [13, 15]]]].

Understand the idea

A detector proposes boxes of all sizes, but the classifier after it wants a fixed-size input. RoI pooling lays a fixed grid, say 2 x 2, over each box on the feature map and keeps the largest value in each grid cell. Big and small boxes all come out the same size, like summarising any length of book in exactly four bullet points.

Tiny example: a 4 x 4 map with values 0 to 15 and a box covering all of it. With a 2 x 2 grid each bin is 2 x 2 cells: the top-left bin holds 0, 1, 4, 5, max 5. The others give 7, 13 and 15.

Rules: start = round(x * scale); bin = roi_size / out_size; rows floor(ph * bin) to ceil((ph + 1) * bin), offset by the start; output = max over the bin, or 0 if empty.

Fast R-CNN introduced this layer; Mask R-CNN replaced it with RoIAlign to avoid the rounding errors.

Shapes and data flow

feat (C,H,W), rois (R,4) -> out (R, C, out_size, out_size)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: exampleroi_pool(np.arange(16).reshape(1, 4, 4), [[0.0, 0.0, 3.0, 3.0]], 2, 1.0)
  • Sample 2: scaled roiroi_pool(F, [[2.0, 2.0, 9.0, 13.0], [0.0, 0.0, 4.0, 4.0]], 2, 0.5)