我有两个 numpy 数组image
和warped_image
和索引数组ix,iy
。我需要向warped_image
添加image
,以便将image[i,j]
添加到warped_image[iy[i,j],ix[i,j]]
.如果(iy[i,j], ix[i,j])
对所有i,j
都是唯一的,则以下代码有效。但是当它们不是唯一的时,即当image
中的 2 个元素需要添加到warped_image
中的同一元素时,只添加其中一个。如何将image
中的两个元素添加到warped_image
中的同一元素中?
请注意,我不想使用任何for
循环。我想保持这个矢量化。我计划将来将代码转换为TensorFlow或PyTorch,以使用GPU功能。那是因为,我有数百张这样的图像,每张图像都是全高清分辨率。
import numpy
image = numpy.array([[246, 50, 101], [116, 1, 113], [187, 110, 64]])
iy = numpy.array([[1, 0, 2], [1, 1, 0], [2, 0, 2]])
ix = numpy.array([[0, 2, 1], [1, 2, 0], [0, 1, 2]])
warped_image = numpy.zeros(shape=image.shape)
warped_image[iy, ix] += image
>> warped_image
Out[31]:
array([[ 113., 110., 50.],
[246., 116., 1.],
[187., 101., 64.]])
对于上述情况,索引是唯一的,因此输出符合预期。
import numpy
image = numpy.array([[246, 50, 101], [116, 1, 113], [187, 110, 64]])
iy = numpy.array([[1, 0, 2], [1, 0, 2], [2, 2, 2]])
ix = numpy.array([[0, 2, 1], [1, 2, 0], [0, 1, 2]])
warped_image = numpy.zeros(shape=image.shape)
warped_image[iy, ix] += image
>> warped_image
Out[32]:
array([[ 0., 0., 1.],
[246., 116., 0.],
[187., 110., 64.]])
预期输出:
array([[ 0., 0., 51.],
[246., 116., 0.],
[300., 211., 64.]])
在这种情况下,有 3 对索引重叠,因此失败。 例如image[0,1]
和image[1,1]
应将 gt 添加到warped_image[0,2]
以给出值 51。然而,只有其中一个(image[1,1]
)被添加以给出值1。
上下文:
我正在尝试将图像从视图 1 扭曲到 视图 2。我已经计算了哪个像素必须去哪里。在像素重叠的情况下,我需要对它们进行加权平均值。所以,我需要实现上述目标。更多细节在这里
使用 numpy.add.at:
import numpy
image = numpy.array([[246, 50, 101], [116, 1, 113], [187, 110, 64]])
iy = numpy.array([[1, 0, 2], [1, 0, 2], [2, 2, 2]])
ix = numpy.array([[0, 2, 1], [1, 2, 0], [0, 1, 2]])
warped_image = numpy.zeros(shape=image.shape)
np.add.at(warped_image, (iy, ix), image)
print(warped_image)
输出
[[ 0. 0. 51.]
[246. 116. 0.]
[300. 211. 64.]]