Problems
Loading...
1 / 1

Bilinear Interpolation

Computer Vision
Medium

Bilinear interpolation is the standard method for resizing images. When scaling an image to a new size, each output pixel maps to a non-integer position in the source image. The output value is computed as a weighted average of the four nearest source pixels.

Given a 2D grid of values and target dimensions (new_h, new_w), resize the grid using bilinear interpolation.

Coordinate Mapping

Each output pixel (i, j) maps to a source position:

src_y=iH1Hnew1src_x=jW1Wnew1src\_y = i \cdot \frac{H - 1}{H_{new} - 1} \qquad src\_x = j \cdot \frac{W - 1}{W_{new} - 1}

If the output dimension is 1, the source coordinate is 0.

Interpolation

Let (y0, x0) be the integer part (floor) of (src_y, src_x), and dy, dx be the fractional parts. Set y1 = min(y0 + 1, H - 1) and x1 = min(x0 + 1, W - 1) to handle boundary pixels. The output value is:

out=I[y0][x0](1dy)(1dx)  +  I[y1][x0]dy(1dx)\text{out} = I[y_0][x_0]\,(1-dy)(1-dx) \;+\; I[y_1][x_0]\,dy\,(1-dx) +  I[y0][x1](1dy)dx  +  I[y1][x1]dydx+\; I[y_0][x_1]\,(1-dy)\,dx \;+\; I[y_1][x_1]\,dy\,dx

Return the resized grid as a 2D list of floats.

Loading visualization...

Examples

Input:

image = [[0, 10], [20, 30]] new_h = 3, new_w = 3

Output:

[[0, 5, 10], [10, 15, 20], [20, 25, 30]]

The 2x2 grid is upscaled to 3x3. Corner values are preserved, and intermediate values are linearly interpolated.

Input:

image = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]] new_h = 2, new_w = 2

Output:

[[0, 3], [12, 15]]

Downscaling a 4x4 grid to 2x2. The output pixels land exactly on the four corners of the source image.

Hint 1

Split the source coordinate into an integer part (floor) and a fractional part. The fractional part gives you the interpolation weights.

Hint 2

Watch out for division by zero when new_h or new_w is 1.

Requirements

  • Map output coordinates to source coordinates using the align-corners formula
  • Interpolate using the four nearest source pixels
  • Clamp neighbor coordinates to stay within bounds
  • Handle single-row or single-column outputs

Constraints

  • 1 <= image height, width <= 100
  • 1 <= new_h, new_w <= 200
  • Pixel values are numbers (int or float)
  • Time limit: 300 ms
Try Similar Problems