Resize an image with bilinear interpolation

Why it matters A half-pixel mismatch between training and serving resize is a classic silent accuracy drop.

Resizing is everywhere in vision preprocessing. Implement the align_corners=False convention.

Write bilinear_resize(img, out_h, out_w) for a 2D array. For output pixel (i, j), source coordinates are y = (i + 0.5) * H / out_h - 0.5 and x = (j + 0.5) * W / out_w - 0.5, clamped to [0, H - 1] and [0, W - 1]. Interpolate between the 4 surrounding pixels (floor and floor + 1, clamped).

Signaturedef bilinear_resize(img, out_h, out_w)

Example

resizing [[0, 10]] to (1, 4) gives [0, 2.5, 7.5, 10].

Understand the idea

Bilinear resizing computes each output pixel by mapping it back to a fractional position in the input and blending the 4 nearest input pixels by distance. With align_corners=False, pixel centres map to pixel centres, hence the 0.5 terms. Worked example: resize the row [[0, 10, 20]] (W = 3) to width 2. For j = 0: x = (0 + 0.5) * 3 / 2 - 0.5 = 0.25, which sits between pixels 0 and 1, so the value is 0 + 0.25 * (10 - 0) = 2.5. For j = 1: x = 1.5 * 1.5 - 0.5 = 1.75, between pixels 1 and 2, so 10 + 0.75 * 10 = 17.5. The output is [2.5, 17.5]. Rule: y = (i + 0.5) * H / out_h - 0.5 and x = (j + 0.5) * W / out_w - 0.5, each clamped to [0, size - 1]; take y0 = floor(y), y1 = min(y0 + 1, H - 1) and the same for x; blend the 4 pixels with weights (1 - dy)(1 - dx), (1 - dy) dx, dy (1 - dx) and dy dx. Used in: vision preprocessing and segmentation upsampling.

Shapes and data flow

out (i, j) -> source (y, x) = ((i, j) + 0.5) * scale - 0.5
4 neighbours (y0|y1, x0|x1) -> weighted sum
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

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

  • Sample 1: examplebilinear_resize([[0, 10]], 1, 4)
  • Sample 2: upsamplebilinear_resize([[0, 1], [2, 3]], 3, 3)