使用Python在3D数组中裁剪3D数组的最快方法

时间:2018-11-10 03:40:57

标签: python arrays numpy

我有一个3D数组和一个3D索引列表。我的目标是为每个索引(索引位于卷的中间)隔离一个特定大小的3D小体积(3x3x3或5x5x5或其他大小)。

此刻,我这样做: 1)将五个2D数组分组(感兴趣的一个位于中间,紧随索引之后)。所以有一个5xNxN数组。 2)对于5x5x5的体积,对于我的5xNxN数组的每个2D数组(0,N,N; 1,N,N..etc),我围绕相同的索引裁剪5x5数组。 3)堆叠这五个5x5 2D阵列以获得较小的3D体积。

有没有最快的方法来完成这项工作?

以下是说明代码:

arr = np.zeros((7,7,7)) #Just a 3D array
ind = [3, 3, 3] #My index
for el in range(arr.shape[0]):
    if el==ind[0]:
        group = arr[el-2:el+3] #it isolates a 3D volume with arr[ind[0]] in the middle
        volume_3d = []
        for i in group:
            volume_2d = i[ind[1]-2:ind[1]+3, ind[2]-2:ind[2]+3]
            volume_3d.append (volume_2d) #it builds the 3D volume

谢谢

1 个答案:

答案 0 :(得分:1)

Numpy非常容易地支持这样的切片:

dim = 5
x = dim // 2
i,j,k = ind

volume_3d = arr[i-x:i+(dim-x), j-x:j+(dim-x), k-x:k+(dim-x)].copy()

# Your implementation.
dim = 5
x = dim // 2
arr = np.random.randn(7, 7, 7)
el = ind[0]
group = arr[el-x:el+(dim-x)] 
volume_3d = []
for i in group:
    volume_2d = i[ind[1]-x:ind[1]+(dim-x), ind[2]-x:ind[2]+(dim-x)]
    volume_3d.append (volume_2d)

# Proposed in this post.
i,j,k = ind
volume_3d_2 = arr[i-x:i+(dim-x), j-x:j+(dim-x), k-x:k+(dim-x)]

print(np.array_equal(volume_3d, volume_3d_2))
True