I need the exact Python equivalent function of this Matlab function in order to interpolate matrices.
In Matlab I have:
interp2(X, Y, Z, XI, YI) while in Scipy I have:
interp2d(X, Y, Z). In Scipy XI and YI are missing. How can I resolve this? I'm using all parameters in Matlab.
5 Answers
The correct syntax is ip = interp2d(x, y, z); zi = ip(xi, yi).
Also, interp2d is not exactly the same as interp2. RectBivariateSpline is closer.
I have encountered the same issue, and figured out that scipy.ndimage.map_coordinates does the same as Vq = interp2(V,Xq,Yq). Please read the documentation of these commands to find out the solution for your case.
Try this for Matlab's Vq = interp2(V,Xq,Yq) :
Vq = scipy.ndimage.map_coordinates(V, [Xq.ravel(), Yq.ravel()], order=3, mode='nearest').reshape(V.shape) 0for interp2(v,xq,yq)
ip = scipy.interpolate.griddata((y.ravel(),x.ravel()),distorted.ravel(),(yq.ravel(),xq.ravel())) Note that the result returned needs to be resized. i.e ( ip.resize(img.shape))
here y,x are
x,y = np.meshgrid(np.arange(w),np.arange(h)) where w,h is the width and height of the image respectively.
For more you can read griddata documentation.
For interp2(X,Y,V,Xq,Yq), simply replace
x,ywithX,Y
Interp2d outputs another function which allows you to call Xi and Yi. However, watch out! It evaluates them as a matrix, and not a scalar. You will have to use a for loop to evaluate each pair of values for Xi and Yi individually and get the same behavior as MATLAB.
F=interpolate.interp2d(X,Y,Z) Zi=[] for i, j in zip(Xi,Yi) Zi.append(F(i,j)) 2Just wanted to weigh in on this myself, as I was also struggling to find a Python equivalent of the MATLAB code:
[X, Y] = meshgrid(x, y') [XI, YI] = meshgrid(xi, yi') Vq = interp2(X, Y, Z', XI, YI) coeff = diag(Vq)' where in my specific case, the MATLAB variables and sizes were,
- x & y: (m x 1) and (1 x n), respectively.
- xi & yi: both were (1 x w) size.
- X & Y: (m x n) mesh grids of my sample points.
- Z: (n x m) array of my corresponding function values (transposed in function).
- XI & YI: both were (w x w) mesh grids of my query points.
- coeff: (1 x w) array of the coefficients of interpolation.
I played around with scipy.interpolate.RectBivariateSpline and was able to get the exact results produced by the MATLAB code. It was just a bit tricky as the documentation is a bit confusing, but the key is to use the .ev method. The Python code is as follows:
from scipy.interpolate import RectBivariateSpline # NOTE: The x, y, xi, and yi arrays are kept 1-dimensional, and not converted to meshgrids. interp = RectBivariateSpline(x, y, Z, kx=1, ky=1) coeff = interp.ev(xi, yi) This code should give you the exact same results as the MATLAB code, where the sizes of my Python variables are as follows,
- x & y: (m,) and (n,), respectively.
- Z: (m x n), which is transposed from MATLAB.
- xi & yi: both variables are (w,) shape.
- coeff: (w,).