Problems porting Matlab interp2 to SciPy interp2d

强颜欢笑 提交于 2019-12-11 10:04:33

问题


I'm rewriting a Matlab's code in Python Language. In Matlab code I have this function: gt= interp2(I(:,:,i)',xi,yi,'cubic')';, where I is a RGB image, xi and yi are 2D matrixes with same shape defining the x and y coordinates. After I set gt(isnan(gt))=0; for the values outside the boundaries. This function runs perfectly on Matlab.

In Python I wrote the following code: gt=interpolate.interp2d(x,y,img.T,kind='cubic',fill_value=0), where x and y are the same as the xi and yi in Matlab, and img is a gray-scale image. Anyway i get the following exception: "Invalid length for input z for non rectangular grid") ValueError: Invalid length for input z for non rectangular grid". What is wrong? Thank you very much.


回答1:


Looking at the documentation you should note a few things:

  1. If x and y represent a regular grid, consider using RectBivariateSpline.

  2. x and y should be 1D vectors unlike in Matlab and they match with Matlab's x and y and NOT with xi and yi. Those come later.

  3. SciPy will return a function to use to interpolate later. Matlab retuns the interpolated vector immediately.

You've used it in Matlab but implicitly assuming that

[X, Y] = meshgrid(1:size(I,1), 1:size(I,2))
gt= interp2(X, Y, I(:,:,i)',xi,yi,'cubic')';

So it's actually this X and Y that you need to pass to interpolation.interp2d and NOT xi and yi, they come later.

In SciPy you can actually skip the meshgrid step and just use a normal range but also it outputs a function for later rather than performing the interpolation on the spot (note there might be small errors in my definitions of x and y, I'm not that familiar with arange):

x = arange(1, img.shape[0]+1)
y = arange(1, img.shape[1]+1)
f = interpolation.interp2d(x, y, img.T)

and then when you want to do the interpolation:

gt = f(xi, yi)


来源:https://stackoverflow.com/questions/23567252/problems-porting-matlab-interp2-to-scipy-interp2d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!