Using Nibabel library for reading NIFTI images

1 minute read

For my thesis I have to work with brain images. Usually, brain images are in a special formal, which is NIFTI. This format allows us to have all the information of the image in a header, and then the information of the 3-dimensional image. The primary goal of NIfTI is to provide coordinated and targeted service, training, and research to speed the development and enhance the utility of informatics tools related to neuroimaging. The National Institute of Mental Health and the National Institute of Neurological Disorders and Stroke are joint sponsors of this initiative.

In my case, I want to work not with 3D images, but with 2D images. This is for I’ve found that the library Nibabel for getting the slices of the brain I want, since in the NIFTI images the brain is divided in as many slices as each dimension of the 3D image.

I’m going to give here a code example of how to get the slice of the brain that we want using Nibabel and the library Matplotlib:

import nibabel as nib
import matplotlib.pyplot as plt
import numpy as np
import math
import matplotlib.image
import subprocess

def convert_images(image_name, folder_type, label_of_images, allImages, slice_number):
	#load the image_name
	epi_img = nib.load(image_name)
	#gest the data from the image
	epi_img_data = epi_img.get_data()
	#getting the slices
	print("Getting the slices")
	index2 = np.array(epi_img_data[1], dtype=int)
  # depeding which dimension you you put the slice number, you get a different view
	std_image = epi_img.get_data()[:,:,slice_number]
	slice_1 = epi_img_data[:,:,slice_number]
	#plotting the slice that we care for in gray color scale
	print("Plotting the slices")
	plot = plt.imshow(slice_1, cmap="gray")
	plt.axis('off')
	plot.axes.get_xaxis().set_visible(False)
	plot.axes.get_yaxis().set_visible(False)
	if allImages == "1":
		full_path = folder_type + "/" + image_name + '.png'

	else:
		full_path = folder_type + '/' +  label_of_images + '/' + image_name + '.png'
	#sving it
	print("Saving the slice")
	#plt.savefig(full_path, bbox_inches='tight', pad_inches = 0)
	matplotlib.image.imsave(full_path, std_image, cmap="gray")

With this function, what we are achieving is getting the slice that we want from the NIFTI images, previously loaded with the nibabel package, and then saving it to a specific location using the library matplotlib.

I hope this piece of code could help someone.

Paco