Implement bilinear image resizing to scale an image to a target size using bilinear interpolation.
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