在 Numpy 数组的行或列之间进行插值

kak*_*kyo 5 python numpy

我有一个宽 x 高的阵列 A1。还有另一个 W x M 数组 A2,其中 M << H。沿着该维度的这些 M 点应该放在所有 W 维度的等距单元中。我已经通过以下方式实现了这一点

hopSize = H / M
A1[:, 0 : min(A1.shape[1], hopSize*M) : hopSize] = A2
Run Code Online (Sandbox Code Playgroud)

现在我想填充 M 个锚点的值,以填充这些锚点之间沿 H 维度的所有点,例如,锚点 1 的值将被复制到 的每个点A1[:, Anchor1 : Anchor2]

我想知道是否有一种方法可以在不使用 for 循环的情况下实现这一目标。

ali*_*i_m 5

一般方法是使用scipy.interpolate.interp1d

import numpy as np
from scipy.interpolate import interp1d

# generate some example data
W = 3
H = 10
M = 5

A2 = np.arange(W * M).reshape(W, M)
print(A2)
# [[ 0  1  2  3  4]
#  [ 5  6  7  8  9]
#  [10 11 12 13 14]]

# the initial column indices for A2
x = np.arange(M)

# we create a scipy.interpolate.interp1d instance
itp_A2 = interp1d(x, A2, kind='nearest')

# the output column coordinates for A1
xi = np.linspace(0, M - 1, H)

# we get the interpolated output by calling the interp1d instance with the
# output coordinates
A1 = itp_A2(xi)
print(A1)
# [[  0.   0.   1.   1.   2.   2.   3.   3.   4.   4.]
#  [  5.   5.   6.   6.   7.   7.   8.   8.   9.   9.]
#  [ 10.  10.  11.  11.  12.  12.  13.  13.  14.  14.]]
Run Code Online (Sandbox Code Playgroud)

除了最近邻插值之外,您还可以进行线性插值、二次插值、三次插值等。


对于使用最近邻插值按整数因子进行上采样的特殊情况,您可以使用np.repeat

# upsampling factor
fac = H / M

print(np.repeat(A2, fac, 1))
# [[ 0  0  1  1  2  2  3  3  4  4]
#  [ 5  5  6  6  7  7  8  8  9  9]
#  [10 10 11 11 12 12 13 13 14 14]]
Run Code Online (Sandbox Code Playgroud)