Skip to content

Instantly share code, notes, and snippets.

@ahmedhosny
Created December 12, 2017 15:49
Show Gist options
  • Save ahmedhosny/0ca01caaeb0d9ece8af451ff6559d35f to your computer and use it in GitHub Desktop.
Save ahmedhosny/0ca01caaeb0d9ece8af451ff6559d35f to your computer and use it in GitHub Desktop.
nrrd to nifti
import nrrd # pip install pynrrd
import nibabel as nib # pip install nibabel
import numpy as np
# load nrrd
_nrrd = nrrd.read('/path/to/nrrd.nrrd')
data = _nrrd[0]
header = _nrrd[1]
print data.shape, header
# save nifti
img = nib.Nifti1Image(data, np.eye(4))
nib.save(img,'/path/to/nifti.nii.gz')
@neurolabusc
Copy link

This code is elegant in its simplicity and potentially really useful. My main concern is you set the SForm to an identity matrix, which does not preserve the spatial information (image orientation, voxel size). Can your script be updated to retain this information? The combination of space origin, space and space directions fields in NRRD can describe this transform.

For Python3 compatibility you might want to change print data.shape, header to read

print(data.shape)
print(header)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment