Created
September 16, 2019 16:30
-
-
Save dgobbi/f2ddb36292bcfd189e13ea7b3c14c58a to your computer and use it in GitHub Desktop.
Example of reading and writing a NIfTI file with nibabel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Program nifti_readwrite.py | |
Sep 16, 2019 | |
David Gobbi | |
""" | |
import sys | |
import argparse | |
import nibabel as nib | |
def main(argv): | |
"""Callable entry point. | |
""" | |
parser = argparse.ArgumentParser(prog=argv[0]) | |
parser.add_argument('-i', '--input', required=True, help="Input file.") | |
parser.add_argument('-o', '--output', required=True, help="Output file.") | |
args = parser.parse_args(argv[1:]) | |
# read the input image | |
infile = nib.load(args.input) | |
# get the data, undo the transpose | |
data = infile.get_data().T | |
# get x, y, z spacing (in that order) | |
pixdim = infile.header['pixdim'][1:4] | |
# index into the image with "data[z,y,x]" (z index comes first) | |
# create an output file with the same transform and header as input | |
outfile = nib.Nifti1Image(data.T, infile.affine, header=infile.header) | |
nib.save(outfile, args.output) | |
if __name__ == '__main__': | |
r = main(sys.argv) | |
if r is not None: | |
sys.exit(r) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment