Bilinear Image Resizing

Medium
Computer Vision

Task: Image Resizing with Bilinear Interpolation

Bilinear interpolation is a fundamental technique in computer vision for resizing images. Unlike nearest-neighbor interpolation which simply picks the closest pixel, bilinear interpolation considers the four nearest pixels and computes a weighted average based on the distances to each pixel.

Implement a function bilinear_resize(image, new_height, new_width) that resizes a grayscale or RGB image to the specified dimensions using bilinear interpolation.

Input:

  • image: A 2D list/array (grayscale) or 3D list/array (RGB) representing an image
  • new_height: Target height of the resized image (positive integer)
  • new_width: Target width of the resized image (positive integer)

Output:

  • Return the resized image as a nested list with values rounded to 2 decimal places

Notes:

  • Map each output pixel to corresponding source coordinates
  • Use the four nearest source pixels for interpolation
  • Handle boundary cases by clamping coordinates to valid range
  • Works for both upscaling and downscaling

Examples

Example 1:
Input: image = [[0, 100], [100, 200]] bilinear_resize(image, 4, 4)
Output: [[0.0, 50.0, 100.0, 100.0], [50.0, 100.0, 150.0, 150.0], [100.0, 150.0, 200.0, 200.0], [100.0, 150.0, 200.0, 200.0]]
Explanation: The 2x2 image is upscaled to 4x4. Each output pixel maps to source coordinates with scale factor 0.5. For example, output pixel (1,1) maps to source (0.5, 0.5), which lies at the center of all four source pixels. The bilinear interpolation computes: 0*0.25 + 100*0.25 + 100*0.25 + 200*0.25 = 100.

Starter Code

import numpy as np

def bilinear_resize(image, new_height: int, new_width: int) -> list:
    """
    Resize an image using bilinear interpolation.
    
    Args:
        image: 2D (grayscale) or 3D (RGB) array representing an image
        new_height: Target height of the resized image
        new_width: Target width of the resized image
    
    Returns:
        Resized image as a nested list with values rounded to 2 decimal places
    """
    # Your code here
    pass
Lines: 1Characters: 0
Ready
The AI Interview - Master AI/ML Interviews