8

From this question How to convert Nifti file to Numpy array? , I created a 3D numpy array of nifti image. I made some modifications to this array, like I changed depth of the array by adding padding of zeroes. Now I want to convert this array back to nifti image, how can I do that?

I tried:

imga = Image.fromarray(img, 'RGB')
imga.save("modified/volume-20.nii")

but it doesn't identify nii extension. I also tried:

nib.save(img,'modified/volume-20.nii')

this is also not working, because img must be nibabel.nifti1.Nifti1Image if I want to use nib.save feature. In both of the examples above img is a 3D numpy array.

seralouk
  • 30,938
  • 9
  • 118
  • 133
Prvt_Yadav
  • 324
  • 1
  • 6
  • 20

1 Answers1

8

Assuming that you a numpy array and you want to use nib.save function, you need to first get the affine transformation.

Example:

# define the path to the data
func_filename = os.path.join(data_path, 'task-rest_bold.nii.gz')

# load the data
func = nib.load(func_filename)

# do computations that lead to a 3D numpy array called "output"
# bla bla bla
# output = np.array(....)

# to save this 3D (ndarry) numpy use this
ni_img = nib.Nifti1Image(output, func.affine)

nib.save(ni_img, 'output.nii.gz')

Now you will be able to overlay the output.nii.gz onto the task-rest_bold.nii.gz

seralouk
  • 30,938
  • 9
  • 118
  • 133
  • Hello , Can you please help me with this post? https://stackoverflow.com/questions/56698087/how-to-remove-a-modality-from-mri-image-python-nibabel This is related to this topic as well – The Great Jun 21 '19 at 07:11