[英]Interpolation in a 2d matrix
I am trying to interpolate on a 2d array where the array has between its values zeros, which I want to replace these values with values that are close to or around these values, I have been reviewing several examples but I have not been successful in my search, I have tried the following interpolation code.我正在尝试在二维数组上进行插值,其中数组的值介于零值之间,我想用接近或接近这些值的值替换这些值,我一直在查看几个示例,但我没有成功搜索一下,我试过下面的插值代码。
import numpy as np
from scipy import interpolate
mymin,mymax = 0,3
X = np.linspace(mymin,mymax,4)
Y = np.linspace(mymin,mymax,4)
x,y = np.meshgrid(X,Y)
test = np.array([[ 1.2514318 , 0, 1.25148472, 1.25151133],
[ 1.25087456, 0, 1.25092764, 1.25095435],
[ 1.25031581, 1.25034238, 1.25036907, 0],
[ 0, 1.24978222, 0, 1.24983587]])
f = interpolate.interp2d(x,y,test,kind='linear')
X_n = np.linspace(mymin,mymax,4)
Y_n = np.linspace(mymin,mymax,4)
test_n = f(X_n,Y_n)
print (test_n)
[[ 1.25143180e+00 2.77555756e-16 1.25148472e+00 1.25151133e+00]
[ 1.25087456e+00 2.49800181e-16 1.25092764e+00 1.25095435e+00]
[ 1.25031581e+00 1.25034238e+00 1.25036907e+00 1.38777878e-17]
[ 5.33635770e-17 1.24978222e+00 -1.11022302e-16 1.24983587e+00]]
As you can see if it works correctly but the places where the zeros were, it became a very small value that does not correspond to its values that are around it, would the way I am interpolating have a failure?正如您所看到的,它是否正常工作,但零所在的地方,它变成了一个非常小的值,与它周围的值不对应,我插值的方式会失败吗?
Python can not know that you do not want to consider the zero values. Python 不知道你不想考虑零值。 So you need to remove them from your 2D array:
所以你需要从你的二维数组中删除它们:
import numpy as np
from scipy import interpolate
# Dummy data
d = np.array([[1.2514318 , 0, 1.25148472, 1.25151133],
[1.25087456, 0, 1.25092764, 1.25095435],
[1.25031581, 1.25034238, 1.25036907, 0 ],
[0, 1.24978222, 0, 1.24983587]])
# Get the index of the non zero values
y,x = np.where(d!=0)
# Create your interpolation function on the non zero values
f = interpolate.interp2d(x,y,d[d!=0],kind='linear')
# Interpolate
X = np.arange(len(d))
print(f(X,X))
# OUTPUT:
#[[1.2514318 1.25145823 1.25148472 1.25151133]
# [1.25087456 1.25090106 1.25092764 1.25095435]
# [1.25031581 1.25034238 1.25036907 1.25039598]
# [0.94306808 1.24978222 1.39770265 1.24983587]]
Noticed that this 2D linear interpolation provide some pretty bad result for the values that are on the boundary of your space domain.请注意,这种 2D 线性插值会为您的空间域边界上的值提供一些非常糟糕的结果。 This was expected since a linear interpolation cannot guess what are the values that are outside the given space domain.
这是意料之中的,因为线性插值无法猜测给定空间域之外的值是什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.