Python – 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:


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?

Best Solution

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.