Python numpy get 2d数组,其中最后一个维度根据2d数组进行索引

Python numpy get 2d数组,其中最后一个维度根据2d数组进行索引,python,numpy,multidimensional-array,object-slicing,Python,Numpy,Multidimensional Array,Object Slicing,我确实读过numpy索引,但我没有找到我想要的 我有一个288*384的图像,其中每个像素可以有一个[0,15]的标签。 它存储在一个3d(288384,16)形状的numpy数组中im 例如,使用im[:,:,1],我可以得到所有像素都有标签1的图像 我有另一个2d数组标签,(288*384)形状,包含每个像素的标签 如何使用一些巧妙的切片获得每个像素都有对应像素的图像 使用循环,即: result = np.zeros((288,384)) for x,y in zip(range(288)

我确实读过numpy索引,但我没有找到我想要的

我有一个288*384的图像,其中每个像素可以有一个[0,15]的标签。 它存储在一个3d(288384,16)形状的numpy数组中
im

例如,使用
im[:,:,1]
,我可以得到所有像素都有标签1的图像

我有另一个2d数组
标签
,(288*384)形状,包含每个像素的标签

如何使用一些巧妙的切片获得每个像素都有对应像素的图像

使用循环,即:

result = np.zeros((288,384))
for x,y in zip(range(288), range(384)):
    result[x,y] = im[x,y,labelling[x,y]]

但这当然是低效的。

新结果

短期结果是

np.choose(labelling,im.transpose(2,0,1))
旧结果

试试这个

im[np.arange(288)[:,None],np.arange(384)[None,:],labelling]
它适用于以下情况:

import numpy
import numpy.random
import itertools

a = numpy.random.randint(5,size=(2,3,4))
array([[[4, 4, 0, 0],
        [0, 4, 1, 1],
        [3, 4, 4, 2]],

      [[4, 0, 0, 2],
        [1, 4, 2, 2],
        [4, 2, 4, 4]]])

b = numpy.random.randint(4,size=(2,3))
array([[1, 1, 0],
       [1, 2, 2]])

res = a[np.arange(2)[:,None],np.arange(3)[None,:],b]
array([[4, 4, 3],
       [0, 2, 4]])

# note that zip is not doing what you expect it to do
result = np.zeros((2,3))
for x,y in itertools.product(range(2),range(3)):
    result[x,y] = a[x,y,b[x,y]]

array([[4., 4., 3.],
       [0., 2., 4.]])
请注意,
zip
并没有达到您期望的效果

zip(range(2),range(3))
[(0, 0), (1, 1)]
可能你指的是
itertools.product

list(itertools.product(range(2),range(3)))
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]
通过使用
numpy.ix\uuu

xx,yy = np.ix_( np.arange(2), np.arange(3) )

res = a[xx,yy,b]

有进展吗?它起作用了吗。。。如果您不知道如何接受答案,请参阅