我有一个 3D 数组和一个 3D 索引列表。我的目标是为每个索引(索引位于体积的中间)隔离特定大小(3x3x3 或 5x5x5 或其他)的小型 3D 体积。
目前,我这样做: 1) 将五个二维数组分组(中间有感兴趣的数组,在索引之后)。所以有一个 5xNxN 数组。 2) 对于 5x5x5 体积,对于我的 5xNxN 阵列的每个二维阵列(0、N、N;1、N、N..等),我围绕同一索引裁剪一个 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
谢谢
最佳答案
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
关于python - 使用 Python 在 3D 数组中裁剪 3D 数组的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53235813/