Question

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.

Was it helpful?

Solution

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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top