将Matlab interp2移植到SciPy interp2d时出现问题 [英] Problems porting Matlab interp2 to SciPy interp2d
问题描述
我正在用Python语言重写Matlab的代码.
在Matlab代码中,我具有以下功能:gt= interp2(I(:,:,i)',xi,yi,'cubic')';
,其中I
是RGB图像,xi
和yi
是具有相同形状的2D矩阵,定义了x和y坐标.
在将gt(isnan(gt))=0;
设置为边界之外的值之后.
此功能可在Matlab上完美运行.
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.
在Python中,我编写了以下代码:gt=interpolate.interp2d(x,y,img.T,kind='cubic',fill_value=0)
,其中x
和y
与Matlab中的xi
和yi
相同,而img是灰度图像.
无论如何,我得到以下异常:"Invalid length for input z for non rectangular grid")
ValueError: Invalid length for input z for non rectangular grid"
.
怎么了?
非常感谢.
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.
推荐答案
Looking at the documentation you should note a few things:
如果x和y代表规则网格,请考虑使用 RectBivariateSpline .
If x and y represent a regular grid, consider using RectBivariateSpline.
x
和y
应该是一维矢量,与Matlab不同,它们应与Matlab的x
和y
和 NOT 与xi
和yi
匹配.那些会晚一点.
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.
SciPy将返回一个函数,供以后插值使用. Matlab立即调整插值向量.
SciPy will return a function to use to interpolate later. Matlab retuns the interpolated vector immediately.
您已经在Matlab中使用了它,但隐含地假设了
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')';
因此实际上是您需要传递给X
和Y
的插值.interp2d而非NOT xi
和yi
,它们会稍后出现.
So it's actually this X
and Y
that you need to pass to interpolation.interp2d and NOT xi
and yi
, they come later.
在SciPy中,您实际上可以跳过meshgrid
步骤,仅使用正常范围,但是它会输出一个函数供以后使用,而不是在现场进行插值(请注意,我在x
的定义中可能存在小错误和y
,我对arange
不太熟悉:
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)
这篇关于将Matlab interp2移植到SciPy interp2d时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!