I am extremely frustrated because after several hours I can't seem to be able to do a seemingly easy 3D interpolation in python. In Matlab all I had to do was
Vi = interp3(x,y,z,V,xi,yi,zi)
What is the exact equivalent of this using scipy's ndimage.map_coordinate or other numpy methods?
Thanks
The exact equivalent to MATLAB's
interp3
would be using scipy'sinterpn
for one-off interpolation:The default method for both MATLAB and scipy is linear interpolation, and this can be changed with the
method
argument. Note that only linear and nearest-neighbor interpolation is supported byinterpn
for 3 dimensions and above, unlike MATLAB which supports cubic and spline interpolation as well.When making multiple interpolation calls on the same grid it is preferable to use the interpolation object
RegularGridInterpolator
, as in the accepted answer above.interpn
usesRegularGridInterpolator
internally.In scipy 0.14 or later, there is a new function
scipy.interpolate.RegularGridInterpolator
which closely resemblesinterp3
.The MATLAB command
Vi = interp3(x,y,z,V,xi,yi,zi)
would translate to something like:Here is a full example demonstrating both; it will help you understand the exact differences...
MATLAB CODE:
The result is
Vi=[268 357]
which is indeed the value at those two points(2,6,8)
and(3,5,7)
.SCIPY CODE:
Again it's
[268,357]
. So you see some slight differences: Scipy uses x,y,z index order while MATLAB uses y,x,z (strangely); In Scipy you define a function in a separate step and when you call it, the coordinates are grouped like (x1,y1,z1),(x2,y2,z2),... while matlab uses (x1,x2,...),(y1,y2,...),(z1,z2,...).Other than that, the two are similar and equally easy to use.
Basically,
ndimage.map_coordinates
works in "index" coordinates (a.k.a. "voxel" or "pixel" coordinates). The interface to it seems a bit clunky at first, but it does give you a lot of flexibility.If you want to specify the interpolated coordinates similar to matlab's
interp3
, then you'll need to convert your intput coordinates into "index" coordinates.There's also the additional wrinkle that
map_coordinates
always preserves the dtype of the input array in the output. If you interpolate an integer array, you'll get integer output, which may or may not be what you want. For the code snippet below, I'll assume that you always want floating point output. (If you don't, it's actually simpler.)I'll try to add more explanation later tonight (this is rather dense code).
All in all, the
interp3
function I have is more complex than it may need to be for your exact purposes. Howver, it should more or less replicate the behavior ofinterp3
as I remember it (ignoring the "zooming" functionality ofinterp3(data, zoom_factor)
, whichscipy.ndimage.zoom
handles.)