v9.1.1
Menu

Resize Image (Nearest Neighbor)

mediumFREEBook OverviewImage ProcessingCV: Introduction to Computer Vision

Implement an image resizing algorithm using the nearest neighbor interpolation technique. This task involves increasing or decreasing the dimensions of a given image while maintaining its visual content.

The concept of image resizing is fundamental in computer vision, as it enables images to be adapted for various applications, such as display on different devices or use in specific algorithms. Nearest neighbor interpolation is a simple, yet effective method for resizing images, which works by mapping each pixel in the output image to the nearest pixel in the input image. This process can be mathematically represented as finding the corresponding position in the input image for each output pixel position.

Here are the steps to achieve this:

  1. Calculate the source x and y coordinates for each output pixel.
  2. Use these coordinates to find the nearest source pixel. The calculation of source coordinates can be expressed as srcx=⌊x⋅WsrcWdst⌋,srcy=⌊y⋅HsrcHdst⌋src_x = \lfloor x \cdot \frac{W_{src}}{W_{dst}} \rfloor, \quad src_y = \lfloor y \cdot \frac{H_{src}}{H_{dst}} \rfloor.
srcx=⌊x⋅WsrcWdst⌋,srcy=⌊y⋅HsrcHdst⌋src_x = \lfloor x \cdot \frac{W_{src}}{W_{dst}} \rfloor, \quad src_y = \lfloor y \cdot \frac{H_{src}}{H_{dst}} \rfloor

This technique is widely used in image processing applications.

Example

Input
resize_nn([[1,2],[3,4]], 4, 4)
Output
[[1,1,2,2],[1,1,2,2],[3,3,4,4],[3,3,4,4]]
Reasoning
  • Input: image is a 2×22 \times 2 grayscale grid with rows [1,2] and [3,4], so Hsrc=Wsrc=2H_{src} = W_{src} = 2. The target size is new_h =4= 4, new_w =4= 4.
  • Scale factors: HsrcHdst=WsrcWdst=24=0.5\frac{H_{src}}{H_{dst}} = \frac{W_{src}}{W_{dst}} = \frac{2}{4} = 0.5. Each output step moves only half a pixel in the source.
  • Rows: for output rows y=0,1,2,3y = 0, 1, 2, 3 we get y⋅0.5=0,0.5,1,1.5y \cdot 0.5 = 0, 0.5, 1, 1.5, and the floors are 0,0,1,10, 0, 1, 1. Columns x=0..3x = 0..3 map to 0,0,1,10, 0, 1, 1 the same way.
  • Example pixel: output (y=2,x=3)(y=2, x=3) reads source row ⌊1⌋=1\lfloor 1 \rfloor = 1, column ⌊1.5⌋=1\lfloor 1.5 \rfloor = 1, which holds the value 44.
  • Output: a 4×44 \times 4 grid [[1,1,2,2],[1,1,2,2],[3,3,4,4],[3,3,4,4]]. Every source pixel becomes a 2×22 \times 2 block of identical values, and no new values are invented.
  • Notice: when shrinking, the factor is above 1 and pixels get skipped. With the single row 1,2,3,41, 2, 3, 4 resized to width 2, x=0,1x = 0, 1 map to columns 0,20, 2, giving [[1, 3]]. Nothing is averaged.

Constraints

  • Output dimensions new_h, new_w are positive integers
  • Input is a 2D grayscale image

More from CV: Introduction to Computer Vision

solution.py

Test results

Sign in to run your code against the test cases.