def main(argv=None): """``imln`` - create sym-links to images. """ if argv is None: argv = sys.argv[1:] if len(argv) != 2: print(usage) return 1 target, linkbase = argv target = fslpath.removeExt(target, exts) linkbase = fslpath.removeExt(linkbase, exts) # Target must exist, so we can # infer the correct extension(s). # Error on incomplete file groups # (e.g. a.img without a.hdr). try: targets = fslpath.getFileGroup(target, allowedExts=exts, fileGroups=groups, unambiguous=True) except Exception as e: print(f'Error: {e}') return 1 for target in targets: if not op.exists(target): continue ext = fslpath.getExt(target, exts) link = f'{linkbase}{ext}' try: # emulate old imln behaviour - if # link already exists, it is removed if op.exists(link): os.remove(link) os.symlink(target, link) except Exception as e: print(f'Error: {e}') return 1 return 0
def parseFilename(filename): """Parses a BIDS-like file name, returning the entities and suffix encoded in the name. See the :func:`isBIDSFile` function for an explanation of what is considered to be a valid BIDS file name. .. note:: This function assumes that no period (``.``) characters occur in the body of a BIDS filename. :returns: A tuple containing: - A dict containing the entities - The suffix """ if not isBIDSFile(filename, strict=False): raise ValueError('Does not look like a BIDS ' 'file: {}'.format(filename)) suffix = None entities = [] filename = op.basename(filename) filename = fslpath.removeExt(filename, firstDot=True) parts = filename.split('_') for part in parts[:-1]: entities.append(part.split('-')) suffix = parts[-1] entities = dict(entities) return entities, suffix
def main(argv=None): """Test if an image path exists, and prints ``'1'`` if it does or ``'0'`` if it doesn't. """ if argv is None: argv = sys.argv[1:] # emulate old fslio/imtest - always return 0 if len(argv) != 1: print('0') return 0 path = fslpath.removeExt(argv[0], exts) path = op.realpath(path) # getFileGroup will raise an error # if the image (including all # components - i.e. header and # image) does not exist try: fslpath.getFileGroup(path, allowedExts=exts, fileGroups=groups, unambiguous=True) print('1') except fslpath.PathError: print('0') return 0
def save(self, filename=None): """Overrides :meth:`.Image.save`. If a ``filename`` is not provided, converts the original (MGH) file name into a NIFTI filename, before passing it to the :meth:`.Image.save` method. """ if filename is None: filename = self.dataSource filename = fslpath.removeExt(filename, ALLOWED_EXTENSIONS) return fslimage.Image.save(self, filename)
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 = [] # Build a list of all image files (both # hdr and img and otherwise) that match for path in paths: try: path = fslimage.removeExt(path) imgfiles.extend(fslimage.addExt(path, 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)))
def main(argv=None): """Removes file extensions from all paths which are specified on the command line. """ if argv is None: argv = sys.argv[1:] if len(argv) < 1: print(usage) return 1 removed = [] for path in argv: removed.append(fslpath.removeExt(path, ALLOWED_EXTENSIONS)) print(' '.join(removed)) return 0
def __init__(self, infile, fixWinding=False): """Load the given GIFTI file using ``nibabel``, and extracts surface data using the :func:`loadGiftiSurface` function. :arg infile: A GIFTI surface file (``*.surf.gii``). .. todo:: Allow loading from a ``.topo.gii`` and ``.coord.gii`` file? Maybe. """ surfimg, vertices, indices = loadGiftiSurface(infile) mesh.TriangleMesh.__init__(self, vertices, indices, fixWinding) name = fslpath.removeExt(op.basename(infile), ALLOWED_EXTENSIONS) infile = op.abspath(infile) self.name = name self.dataSource = infile self.surfImg = surfimg
def main(argv=None): """Removes all images which are specified on the command line. """ if argv is None: argv = sys.argv[1:] if len(argv) < 1: print(usage) return 1 prefixes = [fslpath.removeExt(p, exts) for p in argv] for prefix, ext in it.product(prefixes, exts): path = f'{prefix}{ext}' if op.exists(path): os.remove(path) return 0
def parseFilename(filename): """Parses a BIDS-like file name. The file name must consist of zero or more "entities" (alpha-numeric ``name-value`` pairs), a "suffix", all separated by underscores, and a regular file extension. For example, the following file:: sub-01_ses-01_task-stim_bold.nii.gz has suffix ``bold``, entities ``sub=01``, ``ses=01`` and ``task=stim``, and extension ``.nii.gz``. .. note:: This function assumes that no period (``.``) characters occur in the body of a BIDS filename. :returns: A tuple containing: - A dict containing the entities - The suffix """ if not isBIDSFile(filename, strict=False): raise ValueError('Does not look like a BIDS ' 'file: {}'.format(filename)) suffix = None entities = [] filename = op.basename(filename) filename = fslpath.removeExt(filename, firstDot=True) parts = filename.split('_') for part in parts[:-1]: entities.append(part.split('-')) suffix = parts[-1] entities = dict(entities) return entities, suffix
def __init__(self, infile, fixWinding=False, loadAll=False): """Load the given GIFTI file using ``nibabel``, and extracts surface data using the :func:`loadGiftiMesh` function. If the file contains more than one set of vertices, the additional ones are added with keys of the form ``infile_i``, where ``infile`` is the absolute path to the file, and ``i`` is an index number, starting from 1. See the :meth:`.addVertices` method. :arg infile: A GIFTI file (``*.gii``) which contains a surface definition. :arg fixWinding: Passed through to the :meth:`addVertices` method for the first vertex set. :arg loadAll: If ``True``, the ``infile`` directory is scanned for other surface files which are then loaded as additional vertex sets. .. todo:: Allow loading from a ``.topo.gii`` and ``.coord.gii`` file? Maybe. """ name = fslpath.removeExt(op.basename(infile), ALLOWED_EXTENSIONS) infile = op.abspath(infile) surfimg, indices, vertices, vdata = loadGiftiMesh(infile) fslmesh.Mesh.__init__(self, indices, name=name, dataSource=infile) for i, v in enumerate(vertices): if i == 0: key = infile else: key = '{}_{}'.format(infile, i) self.addVertices(v, key, select=(i == 0), fixWinding=fixWinding) self.setMeta(infile, surfimg) if vdata is not None: self.addVertexData(infile, vdata) # Find and load all other # surfaces in the same directory # as the specfiied one. if loadAll: # Only attempt to auto-load sensibly # named gifti files (i.e. *.surf.gii, # rather than *.gii). surfFiles = relatedFiles(infile, [ALLOWED_EXTENSIONS[0]]) nvertices = vertices[0].shape[0] for sfile in surfFiles: try: surfimg, _, vertices, _ = loadGiftiMesh(sfile) except Exception: continue if vertices[0].shape[0] != nvertices: continue self.addVertices(vertices[0], sfile, select=False) self.setMeta(sfile, surfimg)