PIXELBANKv9.1.0
Menu

Given a 2D image (matrix of values) and a floating-point coordinate (x,y)(x, y) where xx is column and yy is row, compute the bilinearly interpolated value.

Algorithm:

  1. Clamp coordinates to valid range: x∈[0,W−1]x \in [0, W-1], y∈[0,H−1]y \in [0, H-1]
  2. Find the four nearest integer coordinates: (x0,y0)(x_0, y_0), (x1,y0)(x_1, y_0), (x0,y1)(x_0, y_1), (x1,y1)(x_1, y_1)
    • Ensure x0≤W−2x_0 \leq W-2 and y0≤H−2y_0 \leq H-2 (so x1,y1x_1, y_1 are valid)
  3. Compute fractional parts: dx=x−x0dx = x - x_0, dy=y−y0dy = y - y_0
  4. Interpolate: f(x,y)=f(x0,y0)(1−dx)(1−dy)+f(x1,y0)⋅dx(1−dy)+f(x0,y1)(1−dx)⋅dy+f(x1,y1)⋅dx⋅dyf(x,y) = f(x_0,y_0)(1-dx)(1-dy) + f(x_1,y_0) \cdot dx(1-dy) + f(x_0,y_1)(1-dx) \cdot dy + f(x_1,y_1) \cdot dx \cdot dy

Round to 4 decimal places.

Example:

Input:
image = [[10, 20, 30], [40, 50, 60], [70, 80, 90]]
x = 0.5, y = 0.5
Output:
30.0
Reasoning:
  • The coordinates (x,y)=(0.5,0.5)(x, y) = (0.5, 0.5) are clamped to the valid range, yielding (x,y)=(0.5,0.5)(x, y) = (0.5, 0.5) since they are already within the bounds.
  • The four nearest integer coordinates are found: (x0,y0)=(0,0)(x_0, y_0) = (0, 0), (x1,y0)=(1,0)(x_1, y_0) = (1, 0), (x0,y1)=(0,1)(x_0, y_1) = (0, 1), (x1,y1)=(1,1)(x_1, y_1) = (1, 1), with fractional parts dx=0.5dx = 0.5 and dy=0.5dy = 0.5.
  • The bilinear interpolation formula is applied: f(x,y)=f(0,0)(1−0.5)(1−0.5)+f(1,0)â‹…0.5(1−0.5)+f(0,1)(1−0.5)â‹…0.5+f(1,1)â‹…0.5â‹…0.5=10â‹…0.25+20â‹…0.25+40â‹…0.25+50â‹…0.25=2.5+5+10+12.5=30.0f(x,y) = f(0,0)(1-0.5)(1-0.5) + f(1,0) \cdot 0.5(1-0.5) + f(0,1)(1-0.5) \cdot 0.5 + f(1,1) \cdot 0.5 \cdot 0.5 = 10 \cdot 0.25 + 20 \cdot 0.25 + 40 \cdot 0.25 + 50 \cdot 0.25 = 2.5 + 5 + 10 + 12.5 = 30.0.
  • The result is rounded to 4 decimal places, yielding 30.030.0.

Constraints:

  • image is a 2D list (at least 2x2)
  • x is column coordinate, y is row coordinate
  • Clamp to valid range before interpolating
  • Return a single float rounded to 4 decimal places
🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.
Bilinear Interpolation - Medium | PixelBank