Bilinear Interpolation: Blending Four Pixels

Computer VisionMedium+15 XP+15

Bilinear Interpolation: Blending Four Pixels

Resize, rotate or warp an image and you end up needing the pixel at position (1.7, 2.3) — a place where no pixel exists. Bilinear interpolation invents it, by blending the four pixels surrounding that spot in proportion to how close each one is.

Task: write bilinear(grid, x, y) returning the interpolated value, rounded to 4 decimal places.

The coordinate convention, since this is where everyone gets confused: x is the column, y is the row. So the value at whole coordinates (x, y) is grid[y][x].

The method:

  1. x0 = floor(x), y0 = floor(y) — the top-left of the four surrounding pixels. x1 = x0 + 1, y1 = y0 + 1.
  2. dx = x - x0, dy = y - y0 — how far along you are between them, each between 0 and 1.
  3. Blend along x twice, once on the top row and once on the bottom:
    • top = (1 - dx) * grid[y0][x0] + dx * grid[y0][x1]
    • bottom = (1 - dx) * grid[y1][x0] + dx * grid[y1][x1]
  4. Blend those two along y: (1 - dy) * top + dy * bottom.
  • Coordinates are always inside the grid. But x can be exactly the last column — where x0 + 1 runs off the edge — so clamp x1 to width - 1 and y1 to height - 1. With dx = 0 there the out-of-range neighbour carries no weight anyway.
  • The order of the two blends doesn't matter: interpolate along y first and you get the identical number.

At the exact centre of four pixels, all four weights are 0.25 and you get their plain average — a good first check.

Examples

grid = [[0, 10], [20, 30]]
x = 0.5
y = 0.5
returns 15.0
grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
x = 1.5
y = 0.25
returns 3.25

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