Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a nifti file from a numpy array

I have a numpy array that I would like to covert into a nifti file. Through the documentation it seems PyNIfTI used to do this with:

image=NiftiImage(Array)               

However, PyNIfTI isn't supported anymore. NiBabel, the successor to PyNIfTI, doesn't seem to support this function. I must be missing something. Does anyone know how to do this?

like image 682
Michelle Avatar asked Feb 04 '15 20:02

Michelle


People also ask

How do I save as NIfTI?

The File/Save As/Analyze (NIfTI-1) command saves the current image as a Nifti-1 . img/. hdr pair, File/Save As/NIfTI-1 saves as a combined header/image file (. nii), and File/Save As/Analyze 7.5 saves in Analyze 7.5 format.

How do I export a NumPy file to CSV?

You can save your NumPy arrays to CSV files using the savetxt() function. This function takes a filename and array as arguments and saves the array into CSV format. You must also specify the delimiter; this is the character used to separate each variable in the file, most commonly a comma.

Can you convert NumPy array to list in Python?

With NumPy, np. array objects can be converted to a list with the tolist() function. The tolist() function doesn't accept any arguments. If the array is one-dimensional, a list with the array elements is returned.


2 Answers

The replacement function in the newer NiBabel package would be called Nifty1Image. However, you are required to pass in the affine transformation defining the position of that image with respect to some frame of reference.

In its simplest form, it would look like this:

import nibabel as nib
import numpy as np

data = np.arange(4*4*3).reshape(4,4,3)

new_image = nib.Nifti1Image(data, affine=np.eye(4))

You could also write to a NIfTI-2 file format by using Nifti2Image, which also requires the affine transformation.

like image 169
Oliver W. Avatar answered Oct 06 '22 17:10

Oliver W.


Accepted answer is sufficient. I am adding few lines of detailed explanation for the same.

import nibabel as nib
import numpy as np

data = np.arange(4*4*3).reshape(4,4,3)

new_image = nib.Nifti1Image(data, affine=np.eye(4))

The function np.eye(n) returns a n by n identity matrix.
Here this np.eye(4) is used to generate 4 by 4 matrix as Nifti processes 4 by 4 file format. So you 3 by 3 matrix is converted to 4 by 4 by multiplication with 4 by 4 identity matrix.

So, always affine = np.eye(4) will work.

Same is applicable to both Nifti1Image and Nifti2Image

like image 29
shantanu pathak Avatar answered Oct 06 '22 16:10

shantanu pathak