[Neuroimaging] Load, Modify and Save Nifti

Matthew Brett matthew.brett at gmail.com
Mon Jul 20 13:38:38 CEST 2015


Hi,

On Mon, Jul 20, 2015 at 12:20 PM, Ángel Torrado Carvajal
<angel.torrado at urjc.es> wrote:
> Hi all,
>
> I am a newby using nibabel and I am having some trouble.
>
> I want to load a Nifti volume, modify its image, and save it. However, if I
> do something like this:
>
> img = nb.load("input.nii.gz")
>
> matrix = img.get_data()
> matrix = np.zeros(matrix.shape)
> nb.save(img, "output.nii.gz")

We should definitely make this into a FAQ entry.

The principle here is a Python principle, which is that everything is a pointer.

So

In [4]: A = 1
In [5]: B = A
In [6]: B = 2
In [7]: A
Out[7]: 1

Your array assignment is therefore just making `matrix` point to a
different array and `matrix` no longer points to anything to do with
the image.

You need to do something like this:

img = nb.load("input.nii.gz")
matrix = np.zeros(img.shape)
new_img = nb.Nifti1Image(matrix, img.affine, img.header)
nb.save(new_img, "output.nii.gz")

Cheers,

Matthew


More information about the Neuroimaging mailing list