[英]How can I use nearest neighbor interpolation only outside of bounds when using RegularGridInterpolator
Using RegularGridInterpolator
for obtaining values outside of the hull (bounds) of the input data one can choose between extrapolation or fixed values.使用
RegularGridInterpolator
获取输入数据外壳(边界)之外的值,可以选择外推法或固定值。 How can I get linear interpolation inside the hull and nearest neighbor interpolation outside of the hull?如何获得船体内部的线性插值和船体外部的最近邻插值?
The following class uses two interpolators.以下类使用两个插值器。 The first sets all values outside the hull to
np.nan
.第一个将外壳外的所有值设置为
np.nan
。 The second interpolator does nearest neighbor interpolation only on those nan
values.第二个插值器仅对那些
nan
值进行最近邻插值。
class RegularGridInterpolatorNNextrapol:
def __init__( self, points, values, method='linear' ):
self.interp = RegularGridInterpolator(points, values, method=method,
bounds_error=False, fill_value=np.nan)
self.nearest = RegularGridInterpolator(points, values, method='nearest',
bounds_error=False, fill_value=None)
def __call__( self, xi ):
vals = self.interp( xi )
idxs = np.isnan( vals )
vals[idxs] = self.nearest( xi[idxs] )
return vals
Here is an example which results in the image below:这是一个导致下图的示例:
x = np.linspace( -0.5, 0.5, 5 )
y = np.linspace( -0.5, 0.5, 5 )
X1, Y1 = np.meshgrid(x, y)
z = np.hypot(X1, Y1)
interp = RegularGridInterpolatorNNextrapol((x,y), z)
X = np.linspace(min(x)-0.2, max(x)+0.2,40)
Y = np.linspace(min(y)-0.2, max(y)+0.2,40)
X, Y = np.meshgrid(X, Y) # 2D grid for interpolation
pts = np.column_stack((X.flatten(),Y.flatten()))
Z = interp( pts )
plt.pcolormesh(X, Y, Z.reshape(X.shape), shading='auto')
plt.plot(X1, Y1, "ok" )
plt.legend()
plt.colorbar()
plt.axis("equal")
plt.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.