ROI Pooling: Any Box to a Fixed Grid

Computer VisionHard+20 XP+20

ROI Pooling: Any Box to a Fixed Grid

An object detector proposes regions of wildly different sizes — a tall pedestrian box, a wide car box — and then has to feed each one to a dense layer that demands a fixed input size. ROI pooling solves it by carving any region into a fixed grid of bins and taking the maximum in each.

Task: write roi_pool(feature_map, roi, out_size) returning an out_size × out_size grid.

roi is [row_start, col_start, row_end, col_end], with both ends inclusive. So its height is row_end - row_start + 1 and its width col_end - col_start + 1.

For output cell (i, j), the bin covers rows:

[ row_start+⌊i⋅hout_size⌋,    row_start+⌈(i+1)⋅hout_size⌉)\left[\, row\_start + \left\lfloor \frac{i \cdot h}{out\_size} \right\rfloor, \;\; row\_start + \left\lceil \frac{(i+1) \cdot h}{out\_size} \right\rceil \right)[row_start+⌊out_sizei⋅h​⌋,row_start+⌈out_size(i+1)⋅h​⌉)

and the columns follow the same formula with j and w. The lower bound is inclusive, the upper exclusive. Take the maximum feature value over that block.

  • floor on the start and ceil on the end is the standard trick for dividing a region that doesn't divide evenly: every bin gets at least one row and column, and neighbouring bins may share a row where the split falls mid-pixel.
  • out_size is never larger than the ROI's height or width, so no bin is ever empty.
  • Values can be any numbers. Return the maxima as they are, without rounding.

The point of all this is that the output size is fixed by out_size alone, no matter the region's dimensions. That's what lets one trained dense head score thousands of differently-shaped proposals from a single pass over the feature map — the architectural idea that made Fast R-CNN fast.

Examples

feature_map = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
roi = [0, 0, 3, 3]
out_size = 2
returns [[6, 8], [14, 16]]
feature_map = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
roi = [1, 1, 2, 2]
out_size = 2
returns [[6, 7], [10, 11]]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run