fsl.data.image

This module provides the Nifti and Image classes, for representing NIFTI1 and NIFTI2 images. The nibabel package is used for file I/O.

It is very easy to load a NIFTI image:

from fsl.data.image import Image
myimg = Image('MNI152_T1_2mm.nii.gz')

A handful of other functions are also provided for working with image files and file names:

canonicalShape

Calculates a canonical shape, how the given shape should be presented.

looksLikeImage

Returns True if the given file looks like a NIFTI image, False otherwise.

addExt

Adds a file extension to the given file prefix.

splitExt

Splits the base name and extension for the given filename.

getExt

Gets the extension for the given file name.

removeExt

Removes the extension from the given file name.

defaultExt

Returns the default NIFTI file extension that should be used.

fsl.data.image.ALLOWED_EXTENSIONS = ['.nii.gz', '.nii', '.img', '.hdr', '.img.gz', '.hdr.gz']

The file extensions which we understand. This list is used as the default if the allowedExts parameter is not passed to any of the *Ext functions, or the looksLikeImage() function.

fsl.data.image.EXTENSION_DESCRIPTIONS = ['Compressed NIFTI images', 'NIFTI images', 'NIFTI/ANALYZE75 images', 'NIFTI/ANALYZE75 headers', 'Compressed NIFTI/ANALYZE75 images', 'Compressed NIFTI/ANALYZE75 headers']

Descriptions for each of the extensions in ALLOWED_EXTENSIONS.

fsl.data.image.FILE_GROUPS = [('.hdr', '.img'), ('.hdr.gz', '.img.gz')]

File suffix groups used by addExt() to resolve file path ambiguities - see fsl.utils.path.addExt().

exception fsl.data.image.PathError[source]

Bases: Exception

Exception class raised by the functions defined in this module when something goes wrong.

__module__ = 'fsl.utils.path'
__weakref__

list of weak references to the object (if defined)

class fsl.data.image.DataManager[source]

Bases: object

The DataManager defines an interface which may be used by Image instances for managing access and modification of data in a nibabel.Nifti1Image image.

copy(nibImage: Nifti1Image)[source]

Return a copy of this DataManager, associated with the given nibImage,

property dataRange

Return the image minimum/maximum data values as a (min, max) tuple.

property editable

Return True if the image data can be modified, False otherwise. The default implementation returns True.

__getitem__(slc)[source]

Return data at slc.

__setitem__(slc, val)[source]

Set data at slc to val.

__dict__ = mappingproxy({'__module__': 'fsl.data.image', '__doc__': 'The ``DataManager`` defines an interface which may be used by\n    :class:`Image` instances for managing access and modification of\n    data in a ``nibabel.Nifti1Image`` image.\n    ', 'copy': <function DataManager.copy>, 'dataRange': <property object>, 'editable': <property object>, '__getitem__': <function DataManager.__getitem__>, '__setitem__': <function DataManager.__setitem__>, '__dict__': <attribute '__dict__' of 'DataManager' objects>, '__weakref__': <attribute '__weakref__' of 'DataManager' objects>, '__annotations__': {}})
__module__ = 'fsl.data.image'
__weakref__

list of weak references to the object (if defined)

class fsl.data.image.Nifti(*args, **kwargs)[source]

Bases: Notifier, Meta

The Nifti class is intended to be used as a base class for things which either are, or are associated with, a NIFTI image. The Nifti class is intended to represent information stored in the header of a NIFTI file - if you want to load the data from a file, use the Image class instead.

When a Nifti instance is created, it adds the following attributes to itself:

header

The nibabel NIFTI1/NIFTI2/Analyze header object.

shape

A list/tuple containing the number of voxels along each image dimension.

realShape

A list/tuple containing the actual image data shape - see notes below.

pixdim

A list/tuple containing the length of one voxel along each image dimension.

voxToWorldMat

A 4*4 array specifying the affine transformation for transforming voxel coordinates into real world coordinates.

worldToVoxMat

A 4*4 array specifying the affine transformation for transforming real world coordinates into voxel coordinates.

intent

The NIFTI intent code specified in the header (or constants.NIFTI_INTENT_NONE for Analyze images).

The header field may either be a nifti1, nifti2, or analyze header object. Make sure to take this into account if you are writing code that should work with all three. Use the niftiVersion() property if you need to know what type of image you are dealing with.

Image dimensionality

By default, the Nifti and Image classes “normalise” the dimensionality of an image to always have at least 3 dimensions, and so that trailing dimensions of length 1 are removed. Therefore, the shape attribute may not precisely match the image shape as reported in the NIFTI header, because trailing dimensions of size 1 are squeezed out. The actual image data shape can be queried via the realShape() property. Note also that the Image class expects data access/slicing to be with respect to the normalised shape, not the real shape. See the __determineShape() method and the canonicalSliceObj() function for more details.

Affine transformations

The Nifti class is aware of three coordinate systems:

  • The voxel coordinate system, used to access image data

  • The world coordinate system, where voxel coordinates are transformed into a millimetre coordinate system, defined by the sform and/or qform elements of the NIFTI header.

  • The fsl coordinate system, where voxel coordinates are scaled by the pixdim values in the NIFTI header, and the X axis is inverted if the voxel-to-world affine has a positive determinant. The coordinates (0, 0, 0) correspond to the corner of voxel (0, 0, 0).

  • The scaled coordinate system, where voxel coordinates are scaled by the pixdim values in the NIFTI header.

The getAffine() method is a simple means of acquiring an affine which will transform between any of these coordinate systems.

See here for more details on the fsl coordinate system.

The Nifti class follows the same process as nibabel in determining the voxel to world affine (see http://nipy.org/nibabel/nifti_images.html#the-nifti-affines):

  1. If sform_code != 0 (“unknown”) use the sform affine; else

  2. If qform_code != 0 (“unknown”) use the qform affine; else

  3. Use the fall-back affine.

However, the fall-back affine used by the Nifti class differs to that used by nibabel. In nibabel, the origin (world coordinates (0, 0, 0)) is set to the centre of the image. Here in the Nifti class, we set the world coordinate orign to be the corner of the image, i.e. the corner of voxel (0, 0, 0).

You may change the voxToWorldMat of a Nifti instance (unless it is an Analyze image). When you do so:

  • Only the sform of the underlying Nifti1Header object is changed

  • The qform is not modified.

  • If the sform_code was previously set to NIFTI_XFORM_UNKNOWN, it is changed to NIFTI_XFORM_ALIGNED_ANAT. Otherwise, the sform_code is not modified.

ANALYZE support

A Nifti instance expects to be passed either a nibabel.nifti1.Nifti1Header or a nibabel.nifti2.Nifti2Header, but can also encapsulate a nibabel.analyze.AnalyzeHeader. In this case:

  • The image voxel orientation is assumed to be R->L, P->A, I->S.

  • The affine will be set to a diagonal matrix with the header pixdims as its elements (with the X pixdim negated), and an offset specified by the ANALYZE origin fields. Construction of the affine is handled by nibabel.

  • The niftiVersion() method will return 0.

  • The getXFormCode() method will return constants.NIFTI_XFORM_ANALYZE.

Metadata

The Image class inherits from the Meta class - its methods can be used to store and query any meta-data associated with the image.

Notification

The Nifti class implements the Notifier interface - listeners may register to be notified on the following topics:

'transform'

The affine transformation matrix has changed. This topic will occur when the voxToWorldMat() is changed.

'header'

A header field has changed. This will occur when the intent() is changed.

__init__(header)[source]

Create a Nifti object.

Parameters:

header – A nibabel.nifti1.Nifti1Header, nibabel.nifti2.Nifti2Header, or nibabel.analyze.AnalyzeHeader to be used as the image header.

__del__()[source]

Clears the reference to the nibabel header object.

static determineShape(header)[source]

This method is called by __init__(). It figures out the actual shape of the image data, and the zooms/pixdims for each data axis. Any empty trailing dimensions are squeezed, but the returned shape is guaranteed to be at least 3 dimensions. Returns:

  • A sequence/tuple containing the image shape, as reported in the header.

  • A sequence/tuple containing the effective image shape.

  • A sequence/tuple containing the zooms/pixdims.

static determineAffine(header)[source]

Called by __init__(). Figures out the voxel-to-world coordinate transformation matrix that is associated with this Nifti instance.

static generateAffines(voxToWorldMat, shape, pixdim)[source]

Called by __init__(), and the voxToWorldMat() setter. Generates and returns a dictionary containing affine transformations between the voxel, fsl, scaled, and world coordinate systems. These affines are accessible via the getAffine() method.

Parameters:
  • voxToWorldMat – The voxel-to-world affine transformation

  • shape – Image shape (number of voxels along each dimension

  • pixdim – Image pixdims (size of one voxel along each dimension)

Returns:

A tuple containing:

  • a dictionary of affine transformations between each pair of coordinate systems

  • True if the image is to be considered “neurological”, False otherwise - see the isNeurological() method.

static identifyAffine(image, xform, from_=None, to=None)[source]

Attempt to identify the source or destination space for the given affine.

xform is assumed to be an affine transformation which can be used to transform coordinates between two coordinate systems associated with image.

If one of from_ or to is provided, the other will be derived. If neither are provided, both will be derived. See the Nifti.getAffine() method for details on the valild values that from_ and to may take.

Parameters:
  • imageNifti instance associated with the affine.

  • xform(4, 4) numpy array encoding an affine transformation

  • from – Label specifying the coordinate system which xform takes as input

  • to – Label specifying the coordinate system which xform produces as output

Returns:

A tuple containing: - A label for the from_ coordinate system - A label for the to coordinate system

strval(key)[source]

Returns the specified NIFTI header field, converted to a python string, with non-printable characters removed.

This method is used to sanitise some NIFTI header fields. The default Python behaviour for converting a sequence of bytes to a string is to strip all termination characters (bytes with value of 0x00) from the end of the sequence.

This default behaviour does not handle the case where a sequence of bytes which did contain a long string is subsequently overwritten with a shorter string - the short string will be terminated, but that termination character will be followed by the remainder of the original string.

property header

Return a reference to the nibabel header object.

property niftiVersion

Returns the NIFTI file version:

  • 0 for ANALYZE

  • 1 for NIFTI1

  • 2 for NIFTI2

property shape

Returns a tuple containing the normalised image data shape. The image shape is at least three dimensions, and trailing dimensions of length 1 are squeezed out.

property realShape

Returns a tuple containing the image data shape, as reported in the NIfTI image header.

property ndim

Returns the number of dimensions in this image. This number may not match the number of dimensions specified in the NIFTI header, as trailing dimensions of length 1 are ignored. But it is guaranteed to be at least 3.

property pixdim

Returns a tuple containing the image pixdims (voxel sizes).

property niftiDataType

Returns the NIFTI data type code of this image.

property niftiDataTypeSize

Returns the number of bits per voxel, according to the NIfTI data type. Returns None if the data type is not recognised.

property intent

Returns the NIFTI intent code of this image.

property xyzUnits

Returns the NIFTI XYZ dimension unit code.

property timeUnits

Returns the NIFTI time dimension unit code.

getAffine(from_, to)[source]

Return an affine transformation which can be used to transform coordinates from from_ to to.

Valid values for the from_ and to arguments are:

  • 'voxel': The voxel coordinate system

  • 'world': The world coordinate system, as defined by the image sform/qform

  • 'fsl': The FSL coordinate system (scaled voxels, with a left-right flip if the sform/qform has a positive determinant)

  • 'scaled': Scaled voxel coordinate system (equivalent to 'fsl' without the flip).

Parameters:
  • from – Source coordinate system

  • to – Destination coordinate system

Returns:

A numpy array of shape (4, 4)

property worldToVoxMat

Returns a numpy array of shape (4, 4) containing an affine transformation from world coordinates to voxel coordinates.

property voxToWorldMat

Returns a numpy array of shape (4, 4) containing an affine transformation from voxel coordinates to world coordinates.

property voxToScaledVoxMat

Returns a transformation matrix which transforms from voxel coordinates into fsl coordinates, with a left-right flip if the image appears to be stored in neurological order.

See http://fsl.fmrib.ox.ac.uk/fsl/fslwiki/FLIRT/FAQ#What_is_the _format_of_the_matrix_used_by_FLIRT.2C_and_how_does_it_relate_to _the_transformation_parameters.3F

property scaledVoxToVoxMat

Returns a transformation matrix which transforms from fsl coordinates into voxel coordinates, the inverse of the voxToScaledVoxMat() transform.

mapIndices(sliceobj)[source]

Deprecated - use canonicalSliceObj() instead.

getXFormCode(code=None)[source]

This method returns the code contained in the NIFTI header, indicating the space to which the (transformed) image is oriented.

The code parameter may be either sform (the default) or qform in which case the corresponding matrix is used.

Returns:

one of the following codes: - NIFTI_XFORM_UNKNOWN - NIFTI_XFORM_SCANNER_ANAT - NIFTI_XFORM_ALIGNED_ANAT - NIFTI_XFORM_TALAIRACH - NIFTI_XFORM_MNI_152 - NIFTI_XFORM_TEMPLATE_OTHER - NIFTI_XFORM_ANALYZE

axisMapping(xform)[source]

Returns the (approximate) correspondence of each axis in the source coordinate system to the axes in the destination coordinate system, where the source and destinations are defined by the given affine transformation matrix.

isNeurological()[source]

Returns True if it looks like this Nifti object has a neurological voxel orientation, False otherwise. This test is purely based on the determinant of the voxel-to-mm transformation matrix - if it has a positive determinant, the image is assumed to be in neurological orientation, otherwise it is assumed to be in radiological orientation.

..warning:: This method will return True for images with an

unknown orientation (e.g. the sform_code and qform_code are both set to 0). Therefore, you must check the orientation via the getXFormCode() before trusting the result of this method.

See http://fsl.fmrib.ox.ac.uk/fsl/fslwiki/FLIRT/FAQ#What_is_the _format_of_the_matrix_used_by_FLIRT.2C_and_how_does_it_relate_to _the_transformation_parameters.3F

sameSpace(other)[source]

Returns True if the other image (assumed to be a Nifti instance) has the same dimensions and is in the same space as this image.

getOrientation(axis, xform)[source]

Returns a code representing the orientation of the specified axis in the input coordinate system of the given transformation matrix.

Parameters:

xform

A transformation matrix which is assumed to transform coordinates from some coordinate system (the one which you want an orientation for) into the image world coordinate system.

For example, if you pass in the voxel-to-world transformation matrix, you will get an orientation for axes in the voxel coordinate system.

This method returns one of the following values, indicating the direction in which coordinates along the specified axis increase:

  • ORIENT_L2R: Left to right

  • ORIENT_R2L: Right to left

  • ORIENT_A2P: Anterior to posterior

  • ORIENT_P2A: Posterior to anterior

  • ORIENT_I2S: Inferior to superior

  • ORIENT_S2I: Superior to inferior

  • ORIENT_UNKNOWN: Orientation is unknown

The returned value is dictated by the XForm code contained in the image file header (see the getXFormCode() method). Basically, if the XForm code is unknown, this method will return ORIENT_UNKNOWN for all axes. Otherwise, it is assumed that the image is in RAS orientation (i.e. the X axis increases from left to right, the Y axis increases from posterior to anterior, and the Z axis increases from inferior to superior).

adjust(pixdim=None, shape=None, origin=None)[source]

Return a new Nifti object with the specified pixdim or shape. The affine of the new Nifti is adjusted accordingly.

Only one of pixdim or shape can be specified.

See affine.rescale() for the meaning of the origin argument.

Only the spatial dimensions may be adjusted - use the functions in the image.resample module if you need to adjust non-spatial dimensions.

Parameters:
  • pixdim – New voxel dimensions

  • shape – New image shape

  • origin – Voxel grid alignment - either 'centre' (the default) or 'corner'

Returns:

A new Nifti object based on this one, with adjusted pixdims, shape and affine.

__annotations__ = {}
__module__ = 'fsl.data.image'
class fsl.data.image.Image(*args, **kwargs)[source]

Bases: Nifti

Class which represents a NIFTI image. Internally, the image is loaded/stored using a nibabel.nifti1.Nifti1Image or nibabel.nifti2.Nifti2Image. This class adds functionality for loading metadata from JSON sidecar files, and for keeping track of modifications to the image data.

In addition to the attributes added by the Nifti.__init__() method, the following attributes/properties are present on an Image instance as properties (https://docs.python.org/2/library/functions.html#property):

name

The name of this Image - defaults to the image file name, sans-suffix.

dataSource

The data source of this Image - the name of the file from where it was loaded, or some other string describing its origin.

dataRange

The (min, max) image data values.

nibImage

A reference to the nibabel NIFTI image object.

saveState

A boolean value which is True if this image is saved to disk, False if it is in-memory, or has been edited.

Data access

The Image class supports access to and assignment of the image data via the [] slice operator, e.g.:

img             = Image('image.nii.gz')
val             = img[20, 30, 25]
img[30, 40, 20] = 999

Internally, the image data is managed using one of the following methods:

  1. For read-only access, the Image class delegates to the underlying nibabel.Nifti1Image instance, accessing the data via the Nifti1Image.dataobj attribute. Refer to https://nipy.org/nibabel/nibabel_images.html#the-image-data-array for more details.

  2. As soon as any data is modified, the Image class will load the image data as a numpy array into memory and will maintain its own reference to the array for subsequent access. Note that this array is entirely independent of any array that is cached by the underlying nibabel.Nifti1Image object (refer to https://nipy.org/nibabel/images_and_memory.html)

  3. The nibabel.Nifti1Image class does not support indexing of image data with boolean mask arrays (e.g. image[mask > 0]). If an attempt is made to access image data in this way, the Image class will be loaded into memory in the same way as described in point 2 above.

  4. For more complicated requirements, a DataManager, implementing custom data access management logic, can be provided when an Image is created. If a DataManager is provided, an internal reference to the data (see 2 above) will not be created or maintained.

It is also possible to obtain a reference to a numpy array containing the image data via the data() method. However, modifications to the returned array:

  • will not result in any notifications (described below)

  • will not affect the value of saveState()

  • have undefined semantics when a custom DataManager is in use

Image dimensionality

The Image class abstracts away trailing image dimensions of length 1. This means that if the header for a NIFTI image specifies that the image has four dimensions, but the fourth dimension is of length 1, you do not need to worry about indexing that fourth dimension. However, all NIFTI images will be presented as having at least three dimensions, so if your image header specifies a third dimension of length 1, you will still need provide an index of 0 for that dimensions, for all data accesses.

Notification of changes to an Image

The Image class adds some Notifier topics to those which are already provided by the Nifti class - listeners may register to be notified of changes to the above properties, by registering on the following _topic_ names (see the Notifier class documentation):

'data'

This topic is notified whenever the image data changes (via the __setitem__() method). The indices/ slices of the portion of data that was modified is passed to registered listeners as the notification value (see Notifier.notify()).

'saveState'

This topic is notified whenever the saved state of the image changes (i.e. data or voxToWorldMat is edited, or the image saved to disk).

'dataRange'

Deprecated - No notifications are made on this topic.

__init__(image: str | Path | Nifti1Image | ndarray | Image | None = None, name: str | None = None, header: Nifti1Header | None = None, xform: ndarray | None = None, loadData: bool | None = None, calcRange: bool | None = None, threaded: bool | None = None, dataSource: str | Path | None = None, loadMeta: bool = False, dataMgr: DataManager | None = None, version: int | None = None, **kwargs)[source]

Create an Image object with the given image data or file name.

Parameters:
  • image – A string containing the name of an image file to load, or a Path object pointing to an image file, or a numpy array, or a nibabel image object, or an Image object. If not provided, a header and a dataMgr must be provided.

  • name – A name for the image.

  • header – If not None, assumed to be a nibabel.nifti1.Nifti1Header or nibabel.nifti2.Nifti2Header to be used as the image header. Not applied to images loaded from file, or existing nibabel images.

  • xform – A \(4\times 4\) affine transformation matrix which transforms voxel coordinates into real world coordinates. If not provided, and a header is provided, the transformation in the header is used. If neither a xform nor a header are provided, an identity matrix is used. If both a xform and a header are provided, the xform is used in preference to the header transformation.

  • loadData – Deprecated, has no effect

  • calcRange – Deprecated, has no effect

  • threaded – Deprecated, has no effect

  • dataSource – If image is not a file name, this argument may be used to specify the file from which the image was loaded.

  • loadMeta – If True, any metadata contained in JSON sidecar files is loaded and attached to this Image via the Meta interface. if False, metadata can be loaded at a later stage via the loadMeta() function. Defaults to False.

  • dataMgr – Object implementing the DataManager interface, for managing access to the image data.

  • version – NIfTI version - either 1 or 2. Only used when creating an image from a numpy array, and when a header is not provided. Defaults to the value dictated by the FSLOUTPUTTYPE environment variable.

All other arguments are passed through to the nibabel.load function (if it is called).

__hash__()[source]

Returns a number which uniquely idenfities this Image instance (the result of id(self)).

__str__()[source]

Return a string representation of this Image instance.

__repr__()[source]

See the __str__() method.

__del__()[source]

Closes any open file handles, and clears some references.

getImageWrapper()[source]

Returns the ImageWrapper instance used to manage access to the image data.

property dataManager

Return the DataManager associated with this Image, if one was specified when it was created.

property dataSource

Returns the data source (e.g. file name) that this Image was loaded from (None if this image only exists in memory).

property nibImage

Returns a reference to the nibabel NIFTI image instance. Note that if the image data has been modified through this Image, it will be out of sync with what is returned by the nibabel object, until a call to save() is made.

property data

Returns the image data as a numpy array. The shape of the returned array is normalised - it will have at least three dimensions, and any trailing dimensions of length 1 will be squeezed out. See Nifti.shape() and Nifti.realShape().

Warning

Calling this method may cause the entire image to be loaded into memory.

property inMemory

Returns True if the image data has been loaded into memory, False``otherwise. This does not reflect whether the underlying ``nibabel.Nifti1Image object has loaded the image data into memory. However, if all data access takes place through the Image class, the underlying nibabel image will not use a cache.

If custom DataManager has loaded the data, this method will always return False.

property saveState

Returns True if this Image has been saved to disk, False otherwise.

property dataRange

Returns the minimum/maxmimum image data values.

property dtype

Returns the numpy data type of the image data.

property nvals

Returns the number of values per voxel in this image. This will usually be 1, but may be 3 or 4, for images of type NIFTI_TYPE_RGB24 or NIFTI_TYPE_RGBA32.

property iscomplex

Returns True if this image has a complex data type, False otherwise.

property editable

Return True if the image data can be modified, False otherwise. Delegates to DataManager.editable() if a DataManager is in use.

property voxToWorldMat

Returns a numpy array of shape (4, 4) containing an affine transformation from voxel coordinates to world coordinates.

__headerChanged(*args, **kwargs)

Called when header properties of this Nifti instance changes. Updates the saveState accordinbgly.

calcRange(*args, **kwargs)[source]

Deprecated, has no effect

loadData()[source]

Deprecated, has no effect

save(filename=None)[source]

Saves this Image to the specifed file, or the dataSource if filename is None.

Note that calling save on an image with modified data will cause the entire image data to be loaded into memory if it has not already been loaded.

__getitem__(slc)[source]

Access the image data with the specified slc.

Parameters:

slc – Something which can slice the image data.

__setitem__(slc, values)[source]

Set the image data at slc to values.

Parameters:
  • slc – Something which can slice the image data.

  • values – New image data.

Note

Modifying image data may force the entire image to be loaded into memory if it has not already been loaded.

__annotations__ = {}
__module__ = 'fsl.data.image'
fsl.data.image.canonicalShape(shape)[source]

Calculates a canonical shape, how the given shape should be presented. The shape is forced to be at least three dimensions, with any other trailing dimensions of length 1 ignored.

fsl.data.image.isValidFancySliceObj(sliceobj, shape)[source]

Returns True if the given sliceobj is a valid and fancy slice object.

nibabel refers to slice objects as “fancy” if they comprise anything but tuples of integers and simple slice objects. The Image class supports an additional type of “fancy” slicing, where the sliceobj is a boolean numpy array of the same shape as the image.

This function returns True if the given sliceobj adheres to these requirements, False otherwise.

fsl.data.image.canonicalSliceObj(sliceobj, shape)[source]

Returns a canonical version of the given sliceobj. See the nibabel.fileslice.canonical_slicers function.

fsl.data.image.expectedShape(sliceobj, shape)[source]

Given a slice object, and the shape of an array to which that slice object is going to be applied, returns the expected shape of the result.

Note

It is assumed that the sliceobj has been passed through the canonicalSliceObj() function.

Parameters:
  • sliceobj – Something which can be used to slice an array of shape shape.

  • shape – Shape of the array being sliced.

Returns:

A tuple containing:

  • Expected number of dimensions of the result

  • Expected shape of the result (or None if sliceobj is fancy).

fsl.data.image.loadMetadata(image)[source]

Searches for and loads any sidecar JSON files associated with the given Image.

If the image looks to be part of a BIDS data set, bids.loadMetadata() is used. Otherwise, if a JSON file with the same file prefix is present alongside the image, it is directly loaded.

Parameters:

imageImage instance

Returns:

Dict containing any metadata that was loaded.

fsl.data.image.looksLikeImage(filename, allowedExts=None)[source]

Returns True if the given file looks like a NIFTI image, False otherwise.

Note

The filename cannot just be a file prefix - it must include the file suffix (e.g. myfile.nii.gz, not myfile).

Parameters:
  • filename – The file name to test.

  • allowedExts – A list of strings containing the allowed file extensions - defaults to ALLOWED_EXTENSIONS.

fsl.data.image.addExt(prefix, mustExist=True, unambiguous=True)[source]

Adds a file extension to the given file prefix. See addExt().

fsl.data.image.splitExt(filename)[source]

Splits the base name and extension for the given filename. See splitExt().

fsl.data.image.getExt(filename)[source]

Gets the extension for the given file name. See getExt().

fsl.data.image.removeExt(filename)[source]

Removes the extension from the given file name. See removeExt().

fsl.data.image.fixExt(filename, **kwargs)[source]

Fix the extension of filename.

For example, if a file name is passed in as file.nii.gz, but the file is actually file.nii, this function will fix the file name.

If filename already exists, it is returned unchanged.

All other arguments are passed through to addExt().

class fsl.data.image.FileType(value)[source]

Bases: Enum

Enumeration of supported image file types. The values for each type are the same as defined in the FSL newimage/newimage.h header file.

NIFTI = 1
NIFTI2 = 2
ANALYZE = 10
NIFTI_PAIR = 11
NIFTI2_PAIR = 12
ANALYZE_GZ = 100
NIFTI_GZ = 101
__module__ = 'fsl.data.image'
NIFTI2_GZ = 102
NIFTI_PAIR_GZ = 111
NIFTI2_PAIR_GZ = 112
fsl.data.image.fileType(filename) FileType[source]

Infer an image file type.

fsl.data.image.defaultOutputType() FileType[source]

Return the default output file type. This is based on the $FSLOUTPUTTYPE environment variable.

fsl.data.image.defaultExt() str[source]

Returns the default NIFTI file extension that should be used.

If the $FSLOUTPUTTYPE variable is set, its value is used. Otherwise, .nii.gz is returned.