如何使用另一个数组的高度将3d numpy数组切片为2d

zqry0prt  于 2023-03-30  发布在  其他
关注(0)|答案(2)|浏览(71)

我有两个数组:

a.shape
# (1024, 768, 100)
heights.shape
# (1024, 768)

我想从a中提取一个二维图像,它将沿着2轴取一个元素,从heights中取其索引。类似于这样:

result = a[:,:,h]

其中h是数组heights中的值(在适当的坐标中)。
结果的形状为(1024, 768)
使用循环很容易,但效率很低:

result = np.zeros(heights.shape)
for i in range(a.shape[0]):
    for j in range(a.shape[1]):
        h = heights[i][j]
        result[i][j] = a[i][j][h]

示例:

a = np.arange(30).reshape((3,2,5)) + 5
# array([[[ 5,  6,  7,  8,  9],
#         [10, 11, 12, 13, 14]],
#
#        [[15, 16, 17, 18, 19],
#         [20, 21, 22, 23, 24]],
#
#        [[25, 26, 27, 28, 29],
#         [30, 31, 32, 33, 34]]])

heights = np.asarray([[0, 2], [1, 4], [1, 3]])
# array([[0, 2],
#        [1, 4],
#        [1, 3]])

print(expected_result)
# array([[ 5, 12],
#        [16, 24],
#        [26, 33]]

我怎样才能以一种有效的方式做到这一点?

yws3nbqq

yws3nbqq1#

使用numpy.take_along_axis + numpy.squeeze的组合:

np.squeeze(np.take_along_axis(a, heights[:, :, None], -1))
array([[ 5, 12],
       [16, 24],
       [26, 33]])
iih3973s

iih3973s2#

一个更手动的解决方案,您可以使用广播创建适当的花式索引:

a[np.arange(h.shape[0])[:, None], np.arange(h.shape[1]), h]

相关问题