numpy获取2d数组,其中最后一个维度是根据2d数组索引的 [英] numpy get 2d array where last dimension is indexed according to a 2d array

查看:606
本文介绍了numpy获取2d数组,其中最后一个维度是根据2d数组索引的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I did read on numpy indexing but I didn't find what I was looking for.

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

I have a 288*384 image, where each pixel can have a labelling in [0,15]. It is stored in a 3d (288,384,16)-shaped numpy array im.

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

With im[:,:,1], I can for example get the image where all pixels have the label 1.

我还有另一个二维数组labelling,形状为(288 * 384),其中包含每个像素的标签.

I have another 2d array labelling, (288*384)-shaped, containing a label for each pixel.

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

How do I get the image where each pixel has the corresponding pixel using some clever slicing?

使用循环,即:

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并没有达到您的期望

Note that zip is not doing what you expect

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_

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

res = a[xx,yy,b]

这篇关于numpy获取2d数组,其中最后一个维度是根据2d数组索引的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆