Search code examples
pythonparsingimage-preprocessingmedical-imaging

How to pass multiple files(.nii format) as input file using python command line?


I have a folder with 20 .nii files. Need to convert it into png, so using python nii2png.py for the same. nii2png.py This is the file I am making changes in. Here are 2 files for your reference: Here these are 2 .nii files. It has the following syntax:

!python nii2png.py -i <input file> -o <output folder>

How can I pass these 20 .nii files in a loop or some other solution? This is the starting of the nii2png file:

import numpy, shutil, os, nibabel
import sys, getopt
import scipy.misc
import imageio
import argparse

def main(argv):
inputfile = ''
outputfile = ''

try:
    opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
except getopt.GetoptError:
    print('nii2png.py -i <inputfile> -o <outputfile>')
    sys.exit(2)
for opt, arg in opts:
    if opt == '-h':
        print('nii2png.py -i <inputfile> -o <outputfile>')
        sys.exit()
    elif opt in ("-i", "--input"):
        inputfile = arg
    elif opt in ("-o", "--output"):
        outputfile = arg

print('Input file is ', inputfile)
print('Output folder is ', outputfile)

Please ignore the indentation of the function.


Solution

  • Probably a better plan is to have a -o parameter for the output folder and have the rest of the command line be input file names, instead of using a single -i parameter. Now you can specify things like nli2png.py -o xxx a*.png b*.png left/c*.png.

    import numpy, shutil, os, nibabel
    import sys
    import scipy.misc
    import imageio
    
    def main(argv):
        if not argv:
            print('nii2png.py -o <outputfolder> <input> <input>...')
            sys.exit()
    
        grab = 0
        outputfolder = '.'
        inputfiles = []
        for arg in argv:
            if arg == '-o':
                grab = 1
            elif grab:
                outputfolder = arg
                grab = 0
            else:
                inputfiles.append(arg)
    
        print('Input files are ', inputfiles)
        print('Output folder is ', outputfolder)
    
    main(sys.argv[1:])