首页 > 解决方案 > 具有 lxmxn 广播形状的高级整数索引

问题描述

今天早些时候,我问过这个关于整数数组索引的问题,但我无法将答案应用到激发这个问题的问题上。

简而言之,p_stack1包含c_stack1从我正在研究的图像处理算法派生的数组。 p_stack1包含概率数据并c_stack1包含整数分类。我需要找到对图像中每个像素具有最高概率的分类,尺寸为 768 x 1024。从整数数组索引的文档中,它提供了一种使用整数索引从高维数组中子集数据的方法。

我的原始问题的解决方案适用于 nxnxn 形状数组的简化示例,但似乎不适用于 lxmxn 形状数组。

#dummy data
p_stack1 = np.reshape(np.random.uniform(0,1,2359296),(3,768,1024))
c_stack1 = np.reshape(np.random.randint(0,4,2359296),(3,768,1024))

#find where max value occurs on axis 0
ind_new=p_stack1.argmax(axis=0)

#Create assending indicies
nx, ny = 768,1024
xx = np.arange(ny)
aa= np.tile(xx,(ny,1))
bb = np.column_stack(tuple(aa))[:nx,:]
aa= np.tile(xx,(ny,1))[:nx,:]

#perform the integer array indexing
print(c_stack1[ind_new, aa,bb])

最后一个打印语句返回错误:

IndexError: index 768 is out of bounds for axis 1 with size 768

aa我检查了and的形状,bb两者都是(768, 1024)

我错过了什么?

标签: pythonarraysnumpyindexing

解决方案


看起来你的尺寸混淆了:

c_stack1.shape   # (3, 768, 1024)
aa.max()         # 1023
bb.max()         # 767

所以,当你跑

c_stack1[ind_new, aa, bb]

您将尝试axis=1使用比可用值更高的值进行索引,因此出现错误

要么转身aabb要么c_stack1[ind_new, bb, aa]也能解决问题


推荐阅读