← back

Bilinear Image Resizing

#240 · Computer Vision · Medium

⊣ Solve on deep-ml.com

Problem

Implement bilinear image resizing to scale an image to a target size using bilinear interpolation.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
def bilinear_resize(
    image: list[list[list[float]]],
    new_H: int,
    new_W: int,
) -> list[list[list[float]]]:
    """
    image: [H, W, C]
    Returns resized image [new_H, new_W, C]
    """
    H = len(image)
    W = len(image[0])
    C = len(image[0][0])

    result = [[[0.0] * C for _ in range(new_W)] for _ in range(new_H)]

    for i in range(new_H):
        for j in range(new_W):
            # Map output pixel to input coordinates
            src_h = i * (H - 1) / max(new_H - 1, 1)
            src_w = j * (W - 1) / max(new_W - 1, 1)

            h0 = int(src_h)
            w0 = int(src_w)
            h1 = min(h0 + 1, H - 1)
            w1 = min(w0 + 1, W - 1)

            dh = src_h - h0
            dw = src_w - w0

            for c in range(C):
                # Bilinear interpolation
                top = image[h0][w0][c] * (1 - dw) + image[h0][w1][c] * dw
                bot = image[h1][w0][c] * (1 - dw) + image[h1][w1][c] * dw
                val = top * (1 - dh) + bot * dh
                result[i][j][c] = round(val, 4)

    return result

Explanation

  1. For each output pixel, compute its corresponding fractional position in the input image.
  2. Find the four nearest input pixels (top-left, top-right, bottom-left, bottom-right).
  3. Interpolate horizontally across the top and bottom pairs, then vertically between the results.
  4. This produces smooth scaling without the blocky artifacts of nearest-neighbor interpolation.

Complexity

  • Time: O(new_H new_W C)
  • Space: O(new_H new_W C) for the resized image