|
| 1 | +#!python |
| 2 | +# emacs: -*- mode: python-mode; py-indent-offset: 4; indent-tabs-mode: nil -*- |
| 3 | +# vi: set ft=python sts=4 ts=4 sw=4 et: |
| 4 | +### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## |
| 5 | +# |
| 6 | +# See COPYING file distributed along with the NiBabel package for the |
| 7 | +# copyright and license terms. |
| 8 | +# |
| 9 | +### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## |
| 10 | +""" |
| 11 | +Conform neuroimaging volume to arbitrary shape and voxel size. |
| 12 | +""" |
| 13 | + |
| 14 | +import argparse |
| 15 | +from pathlib import Path |
| 16 | +import sys |
| 17 | + |
| 18 | +import numpy as np |
| 19 | + |
| 20 | +from nibabel import __version__ |
| 21 | +from nibabel.loadsave import load |
| 22 | +from nibabel.processing import conform |
| 23 | + |
| 24 | + |
| 25 | +def _get_parser(): |
| 26 | + """Return command-line argument parser.""" |
| 27 | + p = argparse.ArgumentParser(description=__doc__) |
| 28 | + p.add_argument("infile", |
| 29 | + help="Neuroimaging volume to conform.") |
| 30 | + p.add_argument("outfile", |
| 31 | + help="Name of output file.") |
| 32 | + p.add_argument("--out-shape", nargs=3, default=(256, 256, 256), |
| 33 | + help="Shape of the conformed output.") |
| 34 | + p.add_argument("--voxel-size", nargs=3, default=(1, 1, 1), |
| 35 | + help="Voxel size in millimeters of the conformed output.") |
| 36 | + p.add_argument("--orientation", default="RAS", |
| 37 | + help="Orientation of the conformed output.") |
| 38 | + p.add_argument("-f", "--force", action="store_true", |
| 39 | + help="Overwrite existing output files.") |
| 40 | + p.add_argument("-V", "--version", action="version", version="{} {}".format(p.prog, __version__)) |
| 41 | + |
| 42 | + return p |
| 43 | + |
| 44 | + |
| 45 | +def main(args=None): |
| 46 | + """Main program function.""" |
| 47 | + parser = _get_parser() |
| 48 | + if args is None: |
| 49 | + namespace = parser.parse_args(sys.argv[1:]) |
| 50 | + else: |
| 51 | + namespace = parser.parse_args(args) |
| 52 | + |
| 53 | + kwargs = vars(namespace) |
| 54 | + from_img = load(kwargs["infile"]) |
| 55 | + |
| 56 | + if not kwargs["force"] and Path(kwargs["outfile"]).exists(): |
| 57 | + raise FileExistsError("Output file exists: {}".format(kwargs["outfile"])) |
| 58 | + |
| 59 | + out_img = conform(from_img=from_img, |
| 60 | + out_shape=kwargs["out_shape"], |
| 61 | + voxel_size=kwargs["voxel_size"], |
| 62 | + order=3, |
| 63 | + cval=0.0, |
| 64 | + orientation=kwargs["orientation"]) |
| 65 | + |
| 66 | + out_img.to_filename(kwargs["outfile"]) |
0 commit comments