Skip to content

Instantly share code, notes, and snippets.

@jcreinhold
Created January 3, 2019 19:28
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save jcreinhold/fdd701211191450284c5718502eabbd4 to your computer and use it in GitHub Desktop.
Convert PAR/REC to NIfTI
#/usr/bin/env python
# convert all parrec files in a directory to nifti
import argparse
from glob import glob
import os
import sys
import nibabel as nib
def arg_parser():
parser = argparse.ArgumentParser(description='convert all parrec images in a directory to nifti')
parser.add_argument('img_dir', type=str)
parser.add_argument('out_dir', type=str)
return parser
def split_filename(filepath):
path = os.path.dirname(filepath)
filename = os.path.basename(filepath)
base, ext = os.path.splitext(filename)
if ext == '.gz':
base, ext2 = os.path.splitext(base)
ext = ext2 + ext
return path, base, ext
def main():
try:
args = arg_parser().parse_args()
fns = glob(os.path.join(args.img_dir, '*.par'))
if len(fns) == 0:
fns = glob(os.path.join(args.img_dir, '*.PAR'))
if len(fns) == 0:
raise Exception(f'Could not find .par files in {args.img_dir}')
for fn in fns:
print(f'Converting image: {fn}')
img = nib.load(fn)
_, base, _ = split_filename(fn)
out_fn = os.path.join(args.out_dir, base + '.nii.gz')
nifti = nib.Nifti1Image(img.dataobj, img.affine, header=img.header)
nifti.set_data_dtype('<f4')
nifti.to_filename(out_fn)
print(f'Saved to: {out_fn}')
return 0
except Exception as e:
print(e)
return 1
if __name__ == "__main__":
sys.exit(main())
@Kangwa-83
Copy link

do i need to run it the directory where my files are or i can direct a path?

@jcreinhold
Copy link
Author

You don't need to run the script in a specific directory. The first argument you provide the script is the path to the directory containing the PAR/REC images. The second argument is the path to save the converted NIfTI images. (The first and second arguments can be the same if you want to save the NIfTI files to the same directory that the PAR/REC files are in.)

@Kangwa-83
Copy link

  1. Please guide on how to enter the arg_parser() variables: img_dir and out_dir

  2. I am running this function with the variable paths: split_filename('/V1','V1'). I am getting the following error


TypeError Traceback (most recent call last)
in
----> 1 split_filename('/V1','V1')

TypeError: split_filename() takes 1 positional argument but 2 were given

@Kangwa-83
Copy link

I have got it. Thanks a lot for writing this script. Do you have anything on fitting and texture analysis?

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