JfVerm
JfVerm

Reputation: 33

Resizing numpy ndarray with linear interpolation

Say I want to resize an array of shape (100,100,100) into an array of shape (57,57,57) using linear interpolation.

Basically I need a functiona that takes a n-dim array with shape S, and transforms it without complaining into an array with the same number of dimensions but with a different shape S' using interpolation.

Is there a simple and fast way to do this with numpy and scipy? I found things like 1d interpolation, 2d interpolation, grid interpolation, but they require linear spaces and whatnot I don't really understand.

Upvotes: 3

Views: 4839

Answers (1)

mrcl
mrcl

Reputation: 2190

You can use the method griddata from scipy.interpolate

from scipy.interpolate import griddata

Lets say your 3D array is given by:

array3d

You will need to reshape your data and create another array with the original indexes, or point coordinates

N=100
array3DAux = array3D.reshape(N**3)

# ijk is an (N**3,3) array with the indexes of the reshaped array.
ijk = mgrid[0:N,0:N,0:N].reshape(3,N**3).T

Now you can create the new grid that you want do find the new interpolated points.

#In your case 57 points
n = 57j
i,j,k = mgrid[0:N:n,0:N:n,0:N:n]

There are 3 interpolation methods nearest, linear and cubic as follows

newArray3D_z0 = griddata(ijk,array3DAux,(i,j,k),method="nearest")
newArray3D_z1 = griddata(ijk,array3DAux,(i,j,k),method="linear")
newArray3D_z2 = griddata(ijk,array3DAux,(i,j,k),method="cubic")

In this case it will work to reduce or increase the size of your 3D array.

Hope it helps

Upvotes: 3

Related Questions