Home > Software design >  How to convert nii images to 2D image?
How to convert nii images to 2D image?

Time:09-17

I have stack of images (100 slices) in nii format, and I want to convert them to 2D png format in order to feed them to 2D model.

import nibabel as nib
# Read file
scan = nib.load('/path/to/stackOfimages.nii.gz')
# Get raw data
scan = scan.get_fdata()
print(scan.shape)
(128, 128, 100)

The images were in 2D png format, which I converted to nii.gz to make one 3D image, and now I want to convert them back to png format. because my model is a 2D model I want to feed the model with a stack of slices (each 100 slice for one person) rather than one image at a time. as shown in the figure below

enter image description here

CodePudding user response:

from PIL import Image
...
for plane in range(scan.shape[2]):
    p = scan[:,:,plane].astype(np.uint8)
    img = Image.fromarray(p)
    img.save( f'plane{plane}.png' )
  • Related