Skip to content
Advertisement

Slicing a 3D image to create a 2D image

I have several 3D images of shape (32,32,32) and I want to create 2D images from them. I want to do that by getting each slice in the z-axis and putting each of them in a square array in order, something like this:

enter image description here

Because I want the 2D image to be square I need to fill the missing slices with zeros (Black in the example).

This is what I did:

JavaScript

And It worked!! But I want to automate it, so I tried this:

JavaScript

But it didn’t work, the slice index for 3d_image (j) is not changing, and I don’t know how to change the index range for grid after every 6th slice.

Could you help me?

Advertisement

Answer

Here’s an automated way to do it. Let’s say your array with shape (32, 32, 32) is called n. Note that this method relies on all 3 dimensions having the same size.

JavaScript

final_im now contains what you want. Below is a representation where each image is a different color and the “black” areas are purple because matplotlib colormaps are funny like that: Picture

Anyway, you can tell that the images go where they’re supposed to and you get your empty space along the bottom.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement