4
$\begingroup$

What are .nii files, and how is data stored in them? I have some of these and I want to know how can I create 3D image of MRI scan from them.

I can load the file in my python script using nibabel. Where to go from here next?

$\endgroup$
0

1 Answer 1

4
$\begingroup$

The most common way of processing images in python through numpy arrays. Since you have already loaded your image through nibabel, you need to get the data from the image object and then cast it as a numpy array.

import nibabel as nib
import numpy as np

# Get nibabel image object
img = nib.load("path/to/image.nii")

# Get data from nibabel image object (returns numpy memmap object)
img_data = img.get_data()

# Convert to numpy ndarray (dtype: uint16)
img_data_arr = np.asarray(img_data)

By default this should be a 3D numpy array with a shape of (height,width,image). If you want to access one image you can always use PIL. For example to save the first image of the .nii file:

from PIL import Image
img = Image.fromarray(img_data_arr_norm[:,:,0], 'L')
img.save("image.jpeg")
$\endgroup$
3
  • $\begingroup$ How can I then load the image in another program? $\endgroup$ Commented Mar 6, 2018 at 2:36
  • $\begingroup$ Before saving the slices into the image , I looked at them using matplotlib.pyplot and was able to see all the sections of the brain. But when i saved the slices into the image form as specified using PIL. I see blank images in my directory. $\endgroup$ Commented Mar 6, 2018 at 2:39
  • 2
    $\begingroup$ What other program are you talking about? The blank images are probably an issue of the conversion from numpy array to PIL Image. Try saving the image through matplotlib.pyplot.imsave(). $\endgroup$
    – Djib2011
    Commented Mar 6, 2018 at 10:12

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.