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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With