I had 328 grayscale images with the size 128*128 and I convert all of them into a 3D array with the shape (128,128,328). Now I want to convert it into 5 separated 3d arrays with the shape of (128,128,64) without changing in sequence.
As you can see 328 is not divisible by 64 and using dsplit function is not working.
Is there any way to slice the 3d array on depth axes dynamically?
Advertisement
Answer
JavaScript
x
13
13
1
import numpy as np
2
3
arr = np.zeros(shape=(128,128,328))
4
5
# make aray divisible by 5 (trim it to the depth of 320)
6
arr = arr[:, :, :320]
7
8
# Split array
9
arrays = np.dsplit(arr, 5)
10
11
for array in arrays:
12
print(array.shape)
13
Output:
JavaScript
1
6
1
(128, 128, 64)
2
(128, 128, 64)
3
(128, 128, 64)
4
(128, 128, 64)
5
(128, 128, 64)
6
EDIT: Here is the same thing written in a dynamic way.
JavaScript
1
17
17
1
import numpy as np
2
3
num_subarrays = 5
4
subarray_depth = 64
5
6
# Initialize array
7
arr = np.zeros(shape=(128,128,328))
8
9
# make aray divisible by subarray_depth
10
arr = arr[:, :, :(arr.shape[2] // subarray_depth) * subarray_depth]
11
12
# Split array
13
arrays = np.dsplit(arr, num_subarrays)
14
15
for array in arrays:
16
print(array.shape)
17