对 NumPy 数组进行上采样和插值

tda*_*tda 6 python arrays interpolation numpy scipy

我有一个数组,例如:

array = np.arange(0,4,1).reshape(2,2)

> [[0 1
    2 3]]
Run Code Online (Sandbox Code Playgroud)

我想对这个数组进行上采样并插入结果值。我知道对数组进行上采样的一个好方法是使用:

array = eratemp[0].repeat(2, axis = 0).repeat(2, axis = 1)
[[0 0 1 1]
 [0 0 1 1]
 [2 2 3 3]
 [2 2 3 3]]
Run Code Online (Sandbox Code Playgroud)

但我无法找到一种方法来插入值以消除数组的每个 2x2 部分之间的“块状”性质。

我想要这样的东西:

[[0 0.4 1 1.1]
 [1 0.8 1 2.1]
 [2 2.3 3 3.1]
 [2.1 2.3 3.1 3.2]]
Run Code Online (Sandbox Code Playgroud)

像这样的东西(注意:这些不会是确切的数字)。我知道可能无法对这个特定的 2D 网格进行插值,但是在我的答案中使用第一个网格,在上采样过程中应该可以进行插值,因为您正在增加像素数,因此可以“填补空白” '。

我对插值的类型不太感兴趣,只要最终输出是平滑的表面!我曾尝试使用 scipy.interp2d 方法但无济于事,如果有人能分享他们的智慧,将不胜感激!

J. *_*sen 6

您可以使用 SciPyinterp2d进行插值,您可以在此处找到文档。

我稍微修改了文档中的示例:

from scipy import interpolate
x = np.array(range(2))
y = np.array(range(2))
a = np.array([[0, 1], [2, 3]])
xx, yy = np.meshgrid(x, y)
f = interpolate.interp2d(x, y, a, kind='linear')

xnew = np.linspace(0, 2, 4)
ynew = np.linspace(0, 2, 4)
znew = f(xnew, ynew)
Run Code Online (Sandbox Code Playgroud)

如果你打印znew它应该是这样的:

array([[ 0.        ,  0.66666667,  1.        ,  1.        ],
       [ 1.33333333,  2.        ,  2.33333333,  2.33333333],
       [ 2.        ,  2.66666667,  3.        ,  3.        ],
       [ 2.        ,  2.66666667,  3.        ,  3.        ]])
Run Code Online (Sandbox Code Playgroud)