pythonnumpy

Nearest neighbor interpolation


Say that I have an array:

arr = np.arange(4).reshape(2,2)

The array arr contains the elements

array([[0, 1],
       [2, 3]])

I want to increase the resolution of the array in such a way that the following is achieved:

np.array([0,0,1,1],
         [0,0,1,1],
         [2,2,3,3],
         [2,2,3,3]])

what is this operation called? Nearest-neighbor interpolation?

It is possible to get my desired output with the following

np.concat(np.repeat(arr,4).reshape(-1,2,2,2), axis=-1).reshape(4,4)

Is there a more general way of doing this for any kind of matrix?


Solution

  • You're looking for "nearest-neighbour upsampling", instead of "interpolation".

    A concise and efficient way to do this in numpy:

    import numpy as np
    
    arr = np.arange(6).reshape(2, 3)
    
    upsampled = np.repeat(np.repeat(arr, 2, axis=0), 2, axis=1)
    
    print("Original Array:")
    print(arr)
    print("Upsampled Array:")
    print(upsampled)
    

    Note: I changed your sample data to (2,3) to show that the original shape does not affect the function.

    Result:

    Original Array:
    [[0 1 2]
     [3 4 5]]
    Upsampled Array:
    [[0 0 1 1 2 2]
     [0 0 1 1 2 2]
     [3 3 4 4 5 5]
     [3 3 4 4 5 5]]
    

    If you need it to be more memory efficient, you can also use:

    upsampled2 = np.kron(arr, np.ones((2, 2), dtype=int))
    
    print("Upsampled Array using Kronecker product:")
    print(upsampled2)
    

    Result:

    Upsampled Array using Kronecker product:
    [[0 0 1 1 2 2]
     [0 0 1 1 2 2]
     [3 3 4 4 5 5]
     [3 3 4 4 5 5]]
    

    Libraries like scipy may offer even more efficient methods of doing the same, if your data is very large.