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?
Data Science Stack Exchange is a question and answer site for Data science professionals, Machine Learning specialists, and those interested in learning more about the field. It only takes a minute to sign up.
Sign up to join this communityThe 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")