情景
我有一个4Dndarray,由多个维度(体素,dim1,dim2,dim3)的3D图像/体素组成,比如说(12个体素,96个像素,96个像素,96个像素).我的目标是从middle of the volume of m voxels个样本中抽取n slices个样本.
我已经查看了(advanced) indexing上的Numpy文档,以及解释广播的this answer文档,以及解释Numpy插入newaxis
的this answer文档,但我仍然无法理解我的场景中的潜在行为.
问题
最初,我试图通过使用以下代码一次性索引数组来实现上述目的:
import numpy as np
array = np.random.rand(12, 96, 96, 96)
n = 4
m_voxels = 6
samples_range = np.arange(0, m_voxels)
middle_slices = array.shape[1] // 2
middle_slices_range = np.arange(middle_slices - n // 2, middle_slices + n // 2)
samples_from_the_middle = array[samples_range, middle_slices_range, :, :]
我没有获得形状数组(6、4、96、96),而是遇到了以下IndexError:
IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (6,) (4,)
当我try 显式或分两步为数组编制索引时,它按预期工作:
explicit_indexing = array[0:6, 46:50, :, :]
temp = array[samples_range]
samples_from_the_middle = temp[:, middle_slices_range, :, :]
explicit_indexing.shape # output: (6, 4, 96, 96)
samples_from_the_middle.shape # output: (6, 4, 96, 96)
或者,如本answer中所述,另一种方法是:
samples_from_the_middle = array[samples_range[:, np.newaxis], middle_slices_range, :, :]
samples_from_the_middle.shape # output: (6, 4, 96, 96)
我有以下几个问题:
- 为什么在显式索引(使用冒号)正常工作时,
np.arange
方法无法产生预期的结果,即使我们实际上是使用相同范围的整数进行索引? - 为什么在第一个索引1D数组中添加
newaxis
似乎就解决了这个问题?
任何真知灼见都将不胜感激.