14. October 2010

Nearest-Neighbor-Resampling in Matlab

This article shows the derivation of an algorithm for resizing images in Matlab, using nearest-neighbor interpolation. Scaling an image is mathematically just multiplying image coordinates by a scaling factor. Surprisingly, when dealing with digital images, the scaling process becomes a little bit more complex.

 1 function g = resample(f, sx, sy)
 2 %% Scales an image using nearest neighbor interpolation.
 3 % f     - the input image
 4 % sx    - the scaling factor in x-direction
 5 % sy    - the scaling factor in y-direction
 6     g = zeros(size(f, 1) * sx, size(f, 2) * sy, class(f));
 7     for i = 1:size(g, 1)
 8         for j = 1:size(g, 2)
 9             fi = 1 + round((i - 0.5) / sx - 0.5);
10             fj = 1 + round((j - 0.5) / sy - 0.5);
11             g(i, j) = f(fi, fj);
12         end
13     end
14 end

How to find this arithmetic expression? Step by step.

Convert a 1-based index i to a 0-based index i’



Convert a 0-based index i’ to a Cartesian coordinate

The first pixel has coordinate 0.5, the next pixel 1.5 and so on. This provides
consistent spacing between pixels and follows the standard image representation
on screens and other media.






Chaining the transformations together

Now, given an 1-based index i_f from the input image, how to calculate the corresponding 1-based index i_g in the output image? By chaining the transformations together.


By inverting the composite function, we obtain the sought-after function


We can now plug in the function definitions


Compare this expression with the algorithm.