为给定索引插入图像python

Nag*_*S N 5 python interpolation numpy image scipy

我有一个大约 8000x9000 大小的图像作为一个 numpy 矩阵。我还有一个 numpy 2xn 矩阵中的索引列表。这些索引是小数,也可能超出图像大小。我需要插入图像并找到给定索引的值。如果指数超出范围,我需要返回numpy.nan它们。目前我正在 for 循环中进行,如下所示

def interpolate_image(image: numpy.ndarray, indices: numpy.ndarray) -> numpy.ndarray:
    """

    :param image:
    :param indices: 2xN matrix. 1st row is dim1 (rows) indices, 2nd row is dim2 (cols) indices
    :return:
    """
    # Todo: Vectorize this
    M, N = image.shape
    num_indices = indices.shape[1]
    interpolated_image = numpy.zeros((1, num_indices))
    for i in range(num_indices):
        x, y = indices[:, i]
        if (x < 0 or x > M - 1) or (y < 0 or y > N - 1):
            interpolated_image[0, i] = numpy.nan
        else:
            # Todo: Do Bilinear Interpolation. For now nearest neighbor is implemented
            interpolated_image[0, i] = image[int(round(x)), int(round(y))]
    return interpolated_image
Run Code Online (Sandbox Code Playgroud)

但是 for 循环花费了大量时间(正如预期的那样)。我怎样才能矢量化这个?我找到了scipy.interpolate.interp2d,但我无法使用它。有人可以解释如何使用这种方法或任何其他方法也可以。我也发现了这个,但它又不符合我的要求。给定 x 和 y 索引,这些生成的插值矩阵。我不想要那个。对于给定的索引,我只想要内插值,即我需要一个向量输出。不是矩阵。

我这样试过,但如上所述,它给出了一个矩阵输出

f = interpolate.interp2d(numpy.arange(image.shape[0]), numpy.arange(image.shape[1]), image, kind='linear')
interp_image_vect = f(indices[:,0], indices[:,1])
RuntimeError: Cannot produce output of size 73156608x73156608 (size too large)
Run Code Online (Sandbox Code Playgroud)

现在,我已经实现了最近邻插值。scipy interp2d 没有最近的邻居。如果库充当最近邻居(这样我可以比较),那就太好了。如果没有,那也很好。

Nat*_*eks 3

看起来scipy.interpolate.RectBivariateSpline会成功:

from scipy.interpolate import RectBivariateSpline
image = # as given
indices = # as given

spline = RectBivariateSpline(numpy.arange(M), numpy.arange(N), image)

interpolated = spline(indices[0], indices[1], grid=False)
Run Code Online (Sandbox Code Playgroud)

这会为您提供插值,但不会为您提供nan所需的位置。您可以通过以下方式获得where

nans = numpy.zeros(interpolated.shape) + numpy.nan
x_in_bounds = (0 <= indices[0]) & (indices[0] < M)
y_in_bounds = (0 <= indices[1]) & (indices[1] < N)
bounded = numpy.where(x_in_bounds & y_in_bounds, interpolated, nans)
Run Code Online (Sandbox Code Playgroud)

我用 2624x2624 图像和 100,000 个点对此进行了测试indices,结果显示整个过程花费了不到一秒的时间。