0

我有一个形状 (68, 64, 64) 的 ndarray,称为“预测”。这些尺寸对应于 image_number、height、width。对于每个图像,我有一个长度为 2 的元组,其中包含对应于每个 64x64 图像中特定位置的坐标,例如 (12, 45)。我可以将这些坐标堆叠到另一个形状为 (68,2) 的 Numpy ndarray 中,称为“位置”。

如何在不使用循环的情况下构造切片对象或构造必要的高级索引索引来访问这些位置?寻求语法帮助。目标是使用没有循环的纯 Numpy 矩阵。

工作循环结构

Import numpy as np
# example code with just ones...The real arrays have 'real' data.
prediction = np.ones((68,64,64), dtype='float32')
locations = np.ones((68,2), dtype='uint32')

selected_location_values = np.empty(prediction.shape[0], dtype='float32')
for index, (image, coordinates) in enumerate(zip(prediction, locations)):
    selected_locations_values[index] = image[coordinates]

期望的方法

selected_location_values = np.empty(prediction.shape[0], dtype='float32')

correct_indexing = some_function_here(locations). # ?????
selected_locations_values = predictions[correct_indexing]
4

1 回答 1

0

一个简单的索引应该可以工作:

img = np.arange(locations.shape[0])
r = locations[:, 0]
c = locations[:, 1]
selected_locations_values = predictions[img, r, c]

花式索引通过选择与广播索引的形状相对应的索引数组的元素来工作。在这种情况下,索引非常简单。您只需要范围来告诉您每个位置对应的图像。

于 2019-10-27T05:53:03.730 回答