我有一个大小约为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
但是for循环花费了大量的时间(如预期)。我该如何进行矢量化处理?我找到了scipy.interpolate.interp2d,但我无法使用它。有人能解释一下如何使用它或者其他方法也可以。我还发现了this,但它也不符合我的要求。给定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)
目前,我已经实现了最近邻插值。scipy interp2d没有最近邻插值。如果库函数有最近邻插值(这样我就可以进行比较),那将是很好的。如果没有,也没关系。
image1 = numpy.where(numpy.isnan(image), -1, image)
有什么想法吗?或者如何在这种插值中使用“nan”? - Nagabhushan S N