def getfmt(arg, fname, exist): ext = op.splitext(fname)[1] if ext in ('.mat', '.x5'): return ext[1:] fname = fslimage.addExt(fname, mustExist=exist) if fslimage.looksLikeImage(fname): return 'nii' parser.error('Could not infer format from ' 'filename: {}'.format(args.input))
def test_looksLikeImage(): """Test the looksLikeImage function. """ # (file, expected) tests = [ ('blah', False), ('blah.moo', False), ('blah.nii', True), ('blah.nii.gz', True), ('blah.hdr', True), ('blah.img', True), ('blah.hdr.gz', True), ('blah.img.gz', True), ] for path, expected in tests: assert fslimage.looksLikeImage(path) == expected
def invert(infile): if fslimage.looksLikeImage(infile): basename = fslimage.removeExt(op.basename(infile)) img = fslimage.Image(infile) data = img.data dmin, dmax = data.min(), data.max() data = dmin + (dmax - data) outfile = '{}_inverted.nii.gz'.format(basename) fslimage.Image(data, header=img.header).save(outfile) # assume text file else: basename, ext = op.split(infile) data = np.loadtxt(infile) dmin, dmax = data.min(), data.max() data = dmin + (dmax - data) outfile = '{}_inverted.{}'.format(basename, ext) np.savetxt(outfile, data) return outfile
def load(name, path): if not fslimage.looksLikeImage(path): return None # create an independent in-memory # copy of the image file img = nib.load(path, mmap=False) data = np.asanyarray(img.dataobj) # if any arguments were fsl images, # that takes precedence. if fslimage.Image in intypes: return fslimage.Image(data, header=img.header, name=name) # but if all inputs were file names, # nibabel takes precedence elif nib.nifti1.Nifti1Image in intypes or len(intypes) == 0: return nib.nifti1.Nifti1Image(data, None, img.header) # this function should not be called # under any other circumstances else: raise RuntimeError('Cannot handle type: {}'.format(intypes))
def saveOverlay(overlay, display=None): """Saves the currently selected overlay (only if it is a :class:`.Image`), by a call to :meth:`.Image.save`. If a ``display`` is provided, the :attr:`.Display.name` may be updated to match the new overlay file name. :arg overlay: The :class:`.Image` overlay to save :arg display: The :class:`.Display` instance associated with the overlay. """ import wx # TODO support for other overlay types if not isinstance(overlay, fslimage.Image): raise RuntimeError('Non-volumetric types not supported yet') # If this image has been loaded from a file, # ask the user whether they want to overwrite # that file, or save the image to a new file. # if overlay.dataSource is not None: # If the data source is not nifti (e.g. # mgz), we are not going to overwrite it, # so we don't ask. if fslimage.looksLikeImage(overlay.dataSource): msg = strings.messages['SaveOverlayAction.overwrite'].format( overlay.dataSource) title = strings.titles['SaveOverlayAction.overwrite'].format( overlay.dataSource) dlg = wx.MessageDialog(wx.GetTopLevelWindows()[0], message=msg, caption=title, style=(wx.ICON_WARNING | wx.YES_NO | wx.CANCEL | wx.NO_DEFAULT)) dlg.SetYesNoCancelLabels( strings.labels['SaveOverlayAction.overwrite'], strings.labels['SaveOverlayAction.saveNew'], strings.labels['SaveOverlayAction.cancel']) response = dlg.ShowModal() # Cancel == cancel the save # Yes == overwrite the existing file # No == save to a new file (prompt the user for the file name) if response == wx.ID_CANCEL: return if response == wx.ID_YES: doSave(overlay) return fromDir = op.dirname(overlay.dataSource) filename = fslimage.removeExt(op.basename(overlay.dataSource)) filename = '{}_copy'.format(filename) else: fromDir = fslsettings.read('loadSaveOverlayDir', os.getcwd()) if display is not None: filename = display.name else: filename = overlay.name filename = filename.replace('/', '_') filename = filename.replace('\\', '_') # Ask the user where they # want to save the image msg = strings.titles['SaveOverlayAction.saveFile'] dlg = wx.FileDialog(wx.GetApp().GetTopWindow(), message=msg, defaultDir=fromDir, defaultFile=filename, style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) if dlg.ShowModal() != wx.ID_OK: return # Make sure that the user chose a supported # extension. If not, use the default extension. savePath = dlg.GetPath() prefix, suffix = fslimage.splitExt(savePath) if suffix == '': savePath = '{}{}'.format(prefix, fslimage.defaultExt()) oldPath = overlay.dataSource saveDir = op.dirname(savePath) if doSave(overlay, savePath): # Cache the save directory for next time. fslsettings.write('loadSaveOverlayDir', saveDir) # If image was in memory, or its old # name equalled the old datasource # base name, update its name. if oldPath is None or \ fslimage.removeExt(op.basename(oldPath)) == overlay.name: overlay.name = fslimage.removeExt(op.basename(savePath)) if display is not None: display.name = overlay.name
def guessDataSourceType(path): """A convenience function which, given the name of a file or directory, figures out a suitable overlay type. Returns a tuple containing two values - a type which should be able to load the path, and the path itself, possibly adjusted. If the type is unrecognised, the first tuple value will be ``None``. """ import fsl.data.vtk as fslvtk import fsl.data.gifti as fslgifti import fsl.data.freesurfer as fslfs import fsl.data.mghimage as fslmgh import fsl.data.featimage as featimage import fsl.data.melodicimage as melimage import fsl.data.dtifit as dtifit import fsl.data.melodicanalysis as melanalysis import fsl.data.featanalysis as featanalysis # Support files opened via fsleyes:// URL if path.startswith('fsleyes://'): path = path[10:] path = op.abspath(path) # Accept images sans-extension try: path = fslimage.addExt(path, mustExist=True) except fslimage.PathError: pass if op.isfile(path): # Some types are easy - just check the extensions if fslpath.hasExt(path, fslvtk.ALLOWED_EXTENSIONS): return fslvtk.VTKMesh, path elif fslpath.hasExt(path, fslgifti.ALLOWED_EXTENSIONS): return fslgifti.GiftiMesh, path elif fslfs.isGeometryFile(path): return fslfs.FreesurferMesh, path elif fslpath.hasExt(path, fslmgh.ALLOWED_EXTENSIONS): return fslmgh.MGHImage, path # Other specialised image types elif melanalysis.isMelodicImage(path): return melimage.MelodicImage, path elif featanalysis.isFEATImage(path): return featimage.FEATImage, path elif fslimage.looksLikeImage(path): return fslimage.Image, path # Analysis directory? elif op.isdir(path): if melanalysis.isMelodicDir(path): return melimage.MelodicImage, path elif featanalysis.isFEATDir(path): return featimage.FEATImage, path elif dtifit.isDTIFitPath(path): return dtifit.DTIFitTensor, path # Otherwise, I don't # know what to do return None, path