1

我有一个函数,它接受一个 3D numpy 数组(我们将其称为卷),并将其转换为 2D 切片列表。我希望用户能够指定对其进行切片的轴。我用下面的代码管理这个,但是三重 if 语句似乎不是最优雅的方法。我会感谢人们对是否可以以更好的方式实现这一点的想法。

axis = 0 # Can be set to 0, 1, or 2 

volume = np.ones((100, 100, 100))

n_slices = volume.shape[axis]

slices = []

for i in range(n_slices):

    if axis == 0:
        my_slice = volume[i, :, :]
    elif axis == 1:
        my_slice = volume[:, i, :]
    elif axis == 2:
        my_slice = volume[:, :, i]

    slices.append(my_slice)
4

3 回答 3

3

只需使用np.moveaxis-

slices_ar = np.moveaxis(volume,axis,0)

最好的部分是它是一个输入视图,因此在运行时几乎是免费的。让我们验证view-part-

In [83]: np.shares_memory(volume, np.moveaxis(volume,axis,0))
Out[83]: True

或者,使用np.rollaxis它做同样的事情 -

np.rollaxis(volume,axis,0)
于 2019-09-25T19:46:31.087 回答
1

我猜你想要的是 [numpy.split()]:( https://docs.scipy.org/doc/numpy/reference/generated/numpy.split.html )

axis = 0 # Can be set to 0, 1, or 2 
volume = np.ones((100, 100, 100))
n_slices = volume.shape[axis]

slices = np.split(volume, n_slices, axis)
于 2019-09-25T19:48:45.367 回答
1

你可以使用

my_slice = volume[tuple(i if n == axis else slice(100) for n in range(3))]

以便

slices = [volume[tuple(i if n == axis else slice(100) for n in range(3))] for i in range(100)]
于 2019-09-25T19:49:51.140 回答