I have a 3D array and a list of 3D indexes. My aim is to isolate a small 3D volume of a specific size (3x3x3 or 5x5x5 or whatever) for every index (with the index lying in the middle of the volume).
At the moment, I do this: 1) Group five 2D arrays (with the interested one in the middle, following the indexes). So having a 5xNxN array. 2) For a 5x5x5 volume, for each 2D array (0,N,N; 1,N,N..etc) of my 5xNxN array, I crop a 5x5 array around the same index. 3) Stack these five 5x5 2D arrays to obtain my small 3D volume.
Is there a fastest way to do this job?
Here an explanatory code:
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
Thanks
Numpy supports slicing like this quite easily:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With