Creating a nifti file from a numpy array

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


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.