Skip to content

Instantly share code, notes, and snippets.

@ilkayisik
Created April 27, 2019 18:32
Show Gist options
  • Save ilkayisik/52df651ffc4fa954098a13a57832472a to your computer and use it in GitHub Desktop.
Save ilkayisik/52df651ffc4fa954098a13a57832472a to your computer and use it in GitHub Desktop.
load, create and save nifti image with nibabel
from nibabel import load, save, Nifti1Image
# load main image
nii_path = path_to_nii_file
zmap = load(nii_path)
img_data = zmap.get_data()
# load anothor image to mask
mask_path = path_to_mask
mask = load(mask_path)
mask_data = mask.get_data()
# do masking
masked_file = mask_data * img_data
# binarize it
masked_file = np.where(masked_file > 0 , 1, 0)
#save the new file out
out = Nifti1Image(masked_file, header=zmap.header, affine=zmap.affine)
save(out, 'path_to/mask.nii.gz')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment