Example #1
0
def _test_Image_atts(imgtype):
    """Test that basic Nifti/Image attributes are correct. """

    testdir = tempfile.mkdtemp()
    allowedExts = fslimage.ALLOWED_EXTENSIONS
    fileGroups = fslimage.FILE_GROUPS

    # (file, dims, pixdims, dtype)
    dtypes = [np.uint8, np.int16, np.int32, np.float32, np.double]
    dims = [(1, 1, 1), (10, 1, 1), (1, 10, 1), (1, 1, 10), (10, 10, 1),
            (10, 1, 10), (1, 10, 10), (10, 10, 10), (1, 1, 1, 1),
            (10, 1, 1, 1), (1, 10, 1, 1), (1, 1, 10, 1), (10, 10, 1, 1),
            (10, 10, 1, 5), (10, 1, 10, 5), (1, 10, 10, 5), (10, 10, 10, 5)]
    pixdims = [(0.5, 0.5, 0.5, 2), (1.0, 1.0, 1.0, 2), (2.0, 2.0, 2.0, 2),
               (1.0, 5.0, 1.0, 3)]

    tests = it.product(dims, pixdims, dtypes)
    tests = list(tests)
    paths = ['test{:03d}'.format(i) for i in range(len(tests))]

    for path, atts in zip(paths, tests):

        dims, pixdims, dtype = atts

        ndims = len(dims)
        pixdims = pixdims[:ndims]

        path = op.abspath(op.join(testdir, path))
        make_image(path, imgtype, dims, pixdims, dtype)

    try:

        for path, atts in zip(paths, tests):

            dims, pixdims, dtype = atts

            expdims = imagewrapper.canonicalShape(dims)
            expndims = len(expdims)
            ndims = len(dims)
            pixdims = pixdims[:ndims]
            exppixdims = pixdims[:expndims]

            path = op.abspath(op.join(testdir, path))
            i = fslimage.Image(path)

            assert tuple(i.shape) == tuple(expdims)
            assert tuple(i.pixdim) == tuple(exppixdims)
            assert tuple(i.nibImage.shape) == tuple(dims)
            assert tuple(i.nibImage.header.get_zooms()) == tuple(pixdims)

            assert i.ndims == expndims
            assert i.dtype == dtype
            assert i.name == op.basename(path)
            assert i.dataSource == fslpath.addExt(path,
                                                  allowedExts=allowedExts,
                                                  mustExist=True,
                                                  fileGroups=fileGroups)
    finally:
        shutil.rmtree(testdir)
Example #2
0
def findReferenceImage(fname):
    """Attempts to locate the volumetric reference image for (what is
    assumed to be) the given Freesurfer geometry file.
    """

    basedir = op.dirname(op.dirname(op.abspath(fname)))
    t1 = op.join(basedir, 'mri', 'T1.mgz')
    exts = fslimage.ALLOWED_EXTENSIONS + fslmgh.ALLOWED_EXTENSIONS

    try:
        return fslpath.addExt(t1, allowedExts=exts, mustExist=True)
    except fslpath.PathError:
        return None
Example #3
0
    def save(self, cifti_filename, default_axis=None):
        """
        Writes this sparse representation to/from a filename

        :param cifti_filename: output filename
        :param default_axis: What to use as an axis along any undefined dimensions

            - By default an error is raised
            - if set to "scalar" a ScalarAxis is used with names of "default {index}"
            - if set to "series" a SeriesAxis is used
        :return:
        """
        self.to_cifti(default_axis).to_filename(
            addExt(cifti_filename, defaultExt=self.extension, mustExist=False))
Example #4
0
def Mesh(filename):
    """
    Reads in a mesh from either a GIFTI (.surf.gii) or a VTK (.vtk) file

    :param filename: filename provided by the user
    :return: GIFTI or VTK sub-class of fsl.data.mesh.Mesh
    """
    try:
        full_filename = path.addExt(filename, ['.surf.gii', '.vtk'])
    except path.PathError as e:
        raise argparse.ArgumentTypeError(*e.args)
    if path.hasExt(full_filename, '.surf.gii'):
        return gifti.GiftiMesh(full_filename)
    else:
        return vtk.VTKMesh(full_filename)
Example #5
0
def write(filename: str, arr: np.ndarray, axes: Tuple[cifti2.Axis]):
    """
    Writes a CIFTI file guessing the extension of the filename

    :param filename: full filename of basename
    :param arr: array to be stored
    :param axes: CIFTI axes describing the rows/columns of a CIFTI file
    """
    extensions = guess_extension(axes)
    if len(extensions) == 0:
        raise ValueError(
            "No valid extensions found for axes of type {}".format(
                type(a) for a in axes))
    new_filename = path.addExt(filename,
                               allowedExts=extensions,
                               mustExist=False,
                               defaultExt=extensions[0])
    cifti2.write(new_filename, arr, axes)
Example #6
0
def load(filename,
         mask_values=(0, np.nan),
         writable=False) -> Union[DenseCifti, ParcelCifti]:
    """
    Reads CIFTI data from the given file

    File can be:

        - NIFTI file
        - GIFTI file
        - CIFTI file

    :param filename: input filename
    :param mask_values: which values are outside of the mask for NIFTI or GIFTI input
    :param writable: allow to write to disk
    :return: appropriate CIFTI sub-class (parcellated or dense)
    """
    possible_extensions = (tuple(dense_extensions.values()) +
                           tuple(parcel_extensions.values()) +
                           tuple(image.ALLOWED_EXTENSIONS) +
                           ('.shape.gii', '.gii'))
    if isinstance(filename, str):
        filename = addExt(filename,
                          possible_extensions,
                          fileGroups=image.FILE_GROUPS)
        img = nib.load(filename)
    else:
        img = filename

    if isinstance(img, nib.Cifti2Image):
        return Cifti.from_cifti(img, writable=writable)
    if isinstance(img, nib.GiftiImage):
        if writable:
            raise ValueError("Can not open GIFTI file in writable mode")
        return Cifti.from_gifti(img, mask_values)
    try:
        vol_img = image.Image(img)
    except ValueError:
        raise ValueError(
            f"I do not know how to convert {type(img)} into greyordinates (from {filename})"
        )
    if writable:
        raise ValueError("Can not open NIFTI file in writable mode")
    return Cifti.from_image(vol_img, mask_values)
Example #7
0
def imglob(paths, output=None):
    """Given a list of file names, identifies and returns the unique
    NIFTI/ANALYZE image files that exist.

    :arg paths:  Sequence of paths/prefixes to glob.

    :arg output: One of ``'prefix'`` (the default), ``'all'``, or
                 ``'primary'``:

                  - ``'prefix'``:  Returns the files without extensions.
                  - ``'all'``:     Returns all files that match (e.g. both
                                   ``.img`` and ``.hdr`` files will be
                                   returned).
                  - ``'primary'``: Returns only the primary file of each
                                   matching file group, e.g. only the
                                   ``.hdr`` file would be returned from
                                   an ``.img``/``.hdr`` pair.

    :returns: A sequence of resolved path names, in the form specified
              by the ``output`` parameter.
    """

    if output is None:
        output = 'prefix'

    if output not in ('prefix', 'all', 'primary'):
        raise ValueError('Unsupported output format: {}'.format(output))

    imgfiles = []

    # Expand any wildcard paths if provided.
    # Depending on the way that imglob is
    # invoked, this may not get done by the
    # calling shell.
    expanded = []
    for path in paths:
        if any(c in path for c in '*?[]'):
            expanded.extend(glob.glob(path))
        else:
            expanded.append(path)

    paths = expanded

    # Build a list of all image files (both
    # hdr and img and otherwise) that match
    for path in paths:
        try:
            path = fslpath.removeExt(path, allowedExts=exts)
            imgfiles.extend(
                fslpath.addExt(path, allowedExts=exts, unambiguous=False))
        except fslpath.PathError:
            continue

    if output == 'prefix':
        imgfiles = fslpath.removeDuplicates(imgfiles,
                                            allowedExts=exts,
                                            fileGroups=groups)
        imgfiles = [fslpath.removeExt(f, exts) for f in imgfiles]

    elif output == 'primary':
        imgfiles = fslpath.removeDuplicates(imgfiles,
                                            allowedExts=exts,
                                            fileGroups=groups)

    return list(sorted(set(imgfiles)))
Example #8
0
def _test_Image_atts(imgtype):
    """Test that basic Nifti/Image attributes are correct. """

    allowedExts = fslimage.ALLOWED_EXTENSIONS
    fileGroups = fslimage.FILE_GROUPS
    typeMap = {
        np.uint8: constants.NIFTI_DT_UINT8,
        np.int16: constants.NIFTI_DT_INT16,
        np.int32: constants.NIFTI_DT_INT32,
        np.float32: constants.NIFTI_DT_FLOAT32,
        np.float64: constants.NIFTI_DT_FLOAT64
    }

    # (file, dims, pixdims, dtype)
    dtypes = [np.uint8, np.int16, np.int32, np.float32, np.double]
    dims = [(1, 1, 1), (10, 1, 1), (1, 10, 1), (1, 1, 10), (10, 10, 1),
            (10, 1, 10), (1, 10, 10), (10, 10, 10), (1, 1, 1, 1),
            (10, 1, 1, 1), (1, 10, 1, 1), (1, 1, 10, 1), (10, 10, 1, 1),
            (10, 10, 1, 5), (10, 1, 10, 5), (1, 10, 10, 5), (10, 10, 10, 5)]
    pixdims = [(0.5, 0.5, 0.5, 2), (1.0, 1.0, 1.0, 2), (2.0, 2.0, 2.0, 2),
               (1.0, 5.0, 1.0, 3)]

    tests = it.product(dims, pixdims, dtypes)
    tests = list(tests)
    paths = ['test{:03d}'.format(i) for i in range(len(tests))]

    with tempdir() as testdir:

        for path, atts in zip(paths, tests):

            dims, pixdims, dtype = atts

            ndims = len(dims)
            pixdims = pixdims[:ndims]

            path = op.abspath(op.join(testdir, path))
            make_image(path, imgtype, dims, pixdims, dtype)

        for path, atts in zip(paths, tests):

            dims, pixdims, dtype = atts

            expdims = fslimage.canonicalShape(dims)
            expndims = len(expdims)
            ndims = len(dims)
            pixdims = pixdims[:ndims]
            exppixdims = pixdims[:expndims]

            path = op.abspath(op.join(testdir, path))
            i = fslimage.Image(path)

            assert not i.iscomplex
            assert tuple(i.shape) == tuple(expdims)
            assert tuple(i.data.shape) == tuple(expdims)
            assert tuple(i.pixdim) == tuple(exppixdims)
            assert tuple(i.nibImage.shape) == tuple(dims)
            assert tuple(i.nibImage.header.get_zooms()) == tuple(pixdims)

            assert i.nvals == 1
            assert i.ndim == expndims
            assert i.dtype == dtype
            assert i.niftiDataType == typeMap[dtype]
            assert i.name == op.basename(path)
            assert i.dataSource == fslpath.addExt(path,
                                                  allowedExts=allowedExts,
                                                  mustExist=True,
                                                  fileGroups=fileGroups)
            i = None