Skip to content

Commit c79620f

Browse files
committed
ENH: Add simple nib-convert tool
1 parent f8de8ce commit c79620f

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed

nibabel/cmdline/convert.py

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
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+
Convert neuroimaging file to new parameters
12+
"""
13+
14+
import argparse
15+
from pathlib import Path
16+
import warnings
17+
18+
import nibabel as nib
19+
20+
21+
def _get_parser():
22+
"""Return command-line argument parser."""
23+
p = argparse.ArgumentParser(description=__doc__)
24+
p.add_argument("infile",
25+
help="Neuroimaging volume to convert")
26+
p.add_argument("outfile",
27+
help="Name of output file")
28+
p.add_argument("--out-dtype", action="store",
29+
help="On-disk data type; valid argument to numpy.dtype()")
30+
p.add_argument("--image-type", action="store",
31+
help="Name of NiBabel image class to create, e.g. Nifti1Image. "
32+
"If specified, will be used prior to setting dtype. If unspecified, "
33+
"a new image like `infile` will be created and converted to a type "
34+
"matching the extension of `outfile`.")
35+
p.add_argument("-f", "--force", action="store_true",
36+
help="Ignore warnings if possible")
37+
p.add_argument("-V", "--version", action="version", version=f"{p.prog} {nib.__version__}")
38+
39+
return p
40+
41+
42+
def main(args=None):
43+
"""Main program function."""
44+
parser = _get_parser()
45+
opts = parser.parse_args(args)
46+
orig = nib.load(opts.infile)
47+
48+
if not opts.force and Path(opts.outfile).exists():
49+
raise FileExistsError(f"Output file exists: {opts.outfile}")
50+
51+
if opts.image_type:
52+
klass = getattr(nib, opts.image_type)
53+
else:
54+
klass = orig.__class__
55+
56+
out_img = klass.from_image(orig)
57+
if opts.out_dtype:
58+
try:
59+
out_img.set_data_dtype(opts.out_dtype)
60+
except Exception as e:
61+
if opts.force:
62+
warnings.warn(f"Ignoring error: {e!r}")
63+
else:
64+
raise
65+
66+
nib.save(out_img, opts.outfile)

setup.cfg

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ all =
7676
[options.entry_points]
7777
console_scripts =
7878
nib-conform=nibabel.cmdline.conform:main
79+
nib-convert=nibabel.cmdline.convert:main
7980
nib-ls=nibabel.cmdline.ls:main
8081
nib-dicomfs=nibabel.cmdline.dicomfs:main
8182
nib-diff=nibabel.cmdline.diff:main

0 commit comments

Comments
 (0)