繁体   English   中英

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

[英]Upsample and Interpolate a NumPy Array

我有一个数组,例如:

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

> [[0 1
    2 3]]

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

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]]

但我无法找到一种方法来插入值以消除数组的每个 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]]

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

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

您可以将SciPy interp2d用于插值,可以在此处找到文档。

我对文档中的示例进行了一些修改:

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)

如果打印znew它应该如下所示:

array([[ 0.        ,  0.66666667,  1.        ,  1.        ],
       [ 1.33333333,  2.        ,  2.33333333,  2.33333333],
       [ 2.        ,  2.66666667,  3.        ,  3.        ],
       [ 2.        ,  2.66666667,  3.        ,  3.        ]])

我会使用scipy.misc.imresize

array = np.arange(0,4,1).reshape(2,2)
from skimage.transform import resize
out = scipy.misc.imresize(array, 2.0)

2.0表示我希望输出为输入尺寸的两倍。 您也可以提供一个inttuple来指定原始尺寸的百分比或仅指定新尺寸本身。

这很容易使用,但是有一个额外的步骤,因为imresize调整所有内容,使您的最大值变为255,而最小值变为0。(并且它将数据类型更改为np.unit8 。)您可能需要执行以下操作:

out = out.astype(array.dtype) / 255 * (np.max(array) - np.min(array)) + np.min(array)

让我们看一下输出

>>> out.round(2)
array([[0.  , 0.25, 0.75, 1.  ],
       [0.51, 0.75, 1.26, 1.51],
       [1.51, 1.75, 2.26, 2.51],
       [2.  , 2.25, 2.75, 3.  ]])

imresize带有弃用警告和替代品,但:

DeprecationWarning:不建议使用imresize imresize在SciPy 1.0.0中已弃用,在1.2.0中将被删除。 请改用skimage.transform.resize

SciPy 中的表单重采样方法。 表示您可以在一个轴上依次对 2d 阵列进行上采样,然后在另一个轴上进行上采样。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM