Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • paulmc/fslpy
  • ndcn0236/fslpy
  • seanf/fslpy
3 results
Show changes
Showing
with 563 additions and 89 deletions
......@@ -10,8 +10,8 @@ Freesurfer ``mgh``/``mgz`` image files.
import os.path as op
import pathlib
import six
import numpy as np
import nibabel as nib
......@@ -47,7 +47,7 @@ class MGHImage(fslimage.Image):
All other arguments are passed through to :meth:`Image.__init__`
"""
if isinstance(image, six.string_types):
if isinstance(image, (str, pathlib.Path)):
filename = op.abspath(image)
name = op.basename(filename)
image = nib.load(image)
......
......@@ -11,9 +11,14 @@
looksLikeVestLutFile
loadVestLutFile
loadVestFile
generateVest
"""
import textwrap as tw
import io
import numpy as np
......@@ -76,3 +81,70 @@ def loadVestLutFile(path, normalise=True):
else:
return colours
def loadVestFile(path, ignoreHeader=True):
"""Loads numeric data from a VEST file, returning it as a ``numpy`` array.
:arg ignoreHeader: if ``True`` (the default), the matrix shape specified
in the VEST header information is ignored, and the shape
inferred from the data. Otherwise, if the number of
rows/columns specified in the VEST header information
does not match the matrix shape, a ``ValueError`` is
raised.
:returns: a ``numpy`` array containing the matrix data in the
VEST file.
"""
data = np.loadtxt(path, comments=['#', '/'])
if not ignoreHeader:
nrows, ncols = None, None
with open(path, 'rt') as f:
for line in f:
if 'NumWaves' in line: ncols = int(line.split()[1])
elif 'NumPoints' in line: nrows = int(line.split()[1])
else: continue
if (ncols is not None) and (nrows is not None):
break
if tuple(data.shape) != (nrows, ncols):
raise ValueError(f'Invalid VEST file ({path}) - data shape '
f'({data.shape}) does not match header '
f'({nrows}, {ncols})')
return data
def generateVest(data):
"""Generates VEST-formatted text for the given ``numpy`` array.
:arg data: A 1D or 2D numpy array.
:returns: A string containing a VEST header, and the ``data``.
"""
data = np.asanyarray(data)
if len(data.shape) not in (1, 2):
raise ValueError(f'unsupported number of dimensions: {data.shape}')
data = np.atleast_2d(data)
if np.issubdtype(data.dtype, np.integer): fmt = '%d'
else: fmt = '%0.12f'
sdata = io.StringIO()
np.savetxt(sdata, data, fmt=fmt)
sdata = sdata.getvalue()
nrows, ncols = data.shape
vest = tw.dedent(f"""
/NumWaves {ncols}
/NumPoints {nrows}
/Matrix
""").strip() + '\n' + sdata
return vest.strip()
#!/usr/bin/env python
#
# Text2Vest.py - Convert an ASCII text matrix file into a VEST file.
#
# Author: Paul McCarthy <pauldmccarthy@gmail.com>
#
"""``Text2Vest`` simply takes a plain text ASCII text matrix file, and
adds a VEST header.
"""
import sys
import numpy as np
import fsl.data.vest as fslvest
usage = "Usage: Text2Vest <text_file> <vest_file>"
def main(argv=None):
"""Convert a plain text file to a VEST file. """
if argv is None:
argv = sys.argv[1:]
if len(argv) != 2:
print(usage)
return 0
infile, outfile = argv
data = np.loadtxt(infile, ndmin=2)
vest = fslvest.generateVest(data)
with open(outfile, 'wt') as f:
f.write(vest)
return 0
if __name__ == '__main__':
sys.exit(main())
This diff is collapsed.
#!/usr/bin/env python
#
# __init__.py - The fsl.scripts package.
#
# Author: Paul McCarthy <pauldmccarthy@gmail.com>
#
"""The ``fsl.scripts`` package contains all of the executable scripts provided
by ``fslpy``.
"""
This diff is collapsed.
This diff is collapsed.
......@@ -55,7 +55,7 @@ def parseArgs(args):
choices=('nearest', 'linear', 'cubic'),
default='linear'),
'ref' : dict(help=helps['ref'],
type=ft.partial(parse_data.Image, loadData=False)),
type=parse_data.Image),
}
parser.add_argument(*flags['input'], **opts['input'])
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.