0

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.

enter image description here

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?

2
  • So how do you want to do it if 328 is not divisible by 64? Please explain what exactly should the result be. How to handle the images which will remain after the splitting of this 3D array into 5 smaller arrays? Commented Apr 1, 2022 at 18:39
  • I would discard the residual units. I want 5 separated arrays with 64 images in them individually, I don't need the rest of my images Commented Apr 1, 2022 at 18:47

1 Answer 1

1
import numpy as np

arr = np.zeros(shape=(128,128,328))

# make aray divisible by 5 (trim it to the depth of 320)
arr = arr[:, :, :320]

# Split array
arrays = np.dsplit(arr, 5)

for array in arrays:
    print(array.shape)

Output:

(128, 128, 64)
(128, 128, 64)
(128, 128, 64)
(128, 128, 64)
(128, 128, 64)

EDIT: Here is the same thing written in a dynamic way.

import numpy as np

num_subarrays = 5
subarray_depth = 64

# Initialize array
arr = np.zeros(shape=(128,128,328))

# make aray divisible by subarray_depth
arr = arr[:, :, :(arr.shape[2] // subarray_depth) * subarray_depth]

# Split array
arrays = np.dsplit(arr, num_subarrays)

for array in arrays:
    print(array.shape) 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. This is working now, but I wanted a dynamic code, not hard coding.
@Pegtomous I have updated the answer. Hope that's what you wanted

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.