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:
Calculates a canonical shape, how the given |
|
Returns |
|
Adds a file extension to the given file |
|
Splits the base name and extension for the given |
|
Gets the extension for the given file name. |
|
Removes the extension from the given file name. |
|
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
allowedExtsparameter is not passed to any of the*Extfunctions, or thelooksLikeImage()function.
-
fsl.data.image.EXTENSION_DESCRIPTIONS= ['Compressed NIFTI images', 'NIFTI images', '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 - seefsl.utils.path.addExt().
-
exception
fsl.data.image.PathError[source]¶ Bases:
ExceptionExceptionclass 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.Nifti(*args, **kwargs)[source]¶ Bases:
fsl.utils.notifier.Notifier,fsl.utils.meta.MetaThe
Nifticlass is intended to be used as a base class for things which either are, or are associated with, a NIFTI image. TheNifticlass is intended to represent information stored in the header of a NIFTI file - if you want to load the data from a file, use theImageclass instead.When a
Niftiinstance is created, it adds the following attributes to itself:headerThe
nibabelNIFTI1/NIFTI2/Analyze header object.shapeA list/tuple containing the number of voxels along each image dimension.
pixdimA list/tuple containing the length of one voxel along each image dimension.
voxToWorldMatA 4*4 array specifying the affine transformation for transforming voxel coordinates into real world coordinates.
worldToVoxMatA 4*4 array specifying the affine transformation for transforming real world coordinates into voxel coordinates.
intentThe NIFTI intent code specified in the header (or
constants.NIFTI_INTENT_NONEfor Analyze images).The
headerfield may either be anifti1,nifti2, oranalyzeheader object. Make sure to take this into account if you are writing code that should work with all three. Use theniftiVersion()property if you need to know what type of image you are dealing with.The
shapeattribute may not precisely match the image shape as reported in the NIFTI header, because trailing dimensions of size 1 are squeezed out. See the__determineShape()andmapIndices()methods.Affine transformations
The
Nifticlass is aware of three coordinate systems:The
voxelcoordinate system, used to access image dataThe
worldcoordinate system, where voxel coordinates are transformed into a millimetre coordinate system, defined by thesformand/orqformelements of the NIFTI header.The
fslcoordinate system, where voxel coordinates are scaled by thepixdimvalues in the NIFTI header, and the X axis is inverted if the voxel-to-world affine has a positive determinant.
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
fslcoordinate system..The
Nifticlass follows the same process asnibabelin determining thevoxeltoworldaffine (see http://nipy.org/nibabel/nifti_images.html#the-nifti-affines):If
sform_code != 0(“unknown”) use the sform affine; elseIf
qform_code != 0(“unknown”) use the qform affine; elseUse the fall-back affine.
However, the fall-back affine used by the
Nifticlass differs to that used bynibabel. Innibabel, the origin (world coordinates (0, 0, 0)) is set to the centre of the image. Here in theNifticlass, 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
voxToWorldMatof aNiftiinstance (unless it is an Analyze image). When you do so:Only the
sformof the underlyingNifti1Headerobject is changedThe
qformis not modified.If the
sform_codewas previously set toNIFTI_XFORM_UNKNOWN, it is changed toNIFTI_XFORM_ALIGNED_ANAT. Otherwise, thesform_codeis not modified.
ANALYZE support
A
Niftiinstance expects to be passed either anibabel.nifti1.Nifti1Headeror anibabel.nifti2.Nifti2Header, but can also encapsulate anibabel.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
originfields. Construction of the affine is handled bynibabel.The
niftiVersion()method will return0.The
getXFormCode()method will returnconstants.NIFTI_XFORM_ANALYZE.
Metadata
The
Imageclass inherits from theMetaclass - its methods can be used to store and query any meta-data associated with the image.Notification
The
Nifticlass implements theNotifierinterface - 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
Niftiobject.- Parameters
header – A
nibabel.nifti1.Nifti1Header,nibabel.nifti2.Nifti2Header, ornibabel.analyze.AnalyzeHeaderto be used as the image header.
-
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 thisNiftiinstance.
-
static
generateAffines(voxToWorldMat, shape, pixdim)[source]¶ Called by
__init__(), and thevoxToWorldMat()setter. Generates and returns a dictionary containing affine transformations between thevoxel,fsl, andworldcoordinate systems. These affines are accessible via thegetAffine()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
Trueif the image is to be considered “neurological”,Falseotherwise - see theisNeurological()method.
-
static
identifyAffine(image, xform, from_=None, to=None)[source]¶ Attempt to identify the source or destination space for the given affine.
xformis assumed to be an affine transformation which can be used to transform coordinates between two coordinate systems associated withimage.If one of
from_ortois provided, the other will be derived. If neither are provided, both will be derived. See theNifti.getAffine()method for details on the valild values thatfrom_andtomay take.- Parameters
image –
Niftiinstance associated with the affine.xform –
(4, 4)numpyarray encoding an affine transformationfrom – Label specifying the coordinate system which
xformtakes as inputto – Label specifying the coordinate system which
xformproduces as output
- Returns
A tuple containing: - A label for the
from_coordinate system - A label for thetocoordinate system
-
strval(key)[source]¶ Returns the specified NIFTI header field, converted to a python string, correctly null-terminated, and 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
nibabelheader object.
-
property
niftiVersion¶ Returns the NIFTI file version:
0for ANALYZE1for NIFTI12for NIFTI2
-
property
shape¶ Returns a tuple containing the image data shape.
-
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
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_toto.Valid values for the
from_andtoarguments 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)
- Parameters
from – Source coordinate system
to – Destination coordinate system
- Returns
A
numpyarray of shape(4, 4)
-
property
worldToVoxMat¶ Returns a
numpyarray of shape(4, 4)containing an affine transformation from world coordinates to voxel coordinates.
-
property
voxToWorldMat¶ Returns a
numpyarray 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 scaled voxel 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 scaled voxels into voxels, the inverse of the
voxToScaledVoxMat()transform.
-
mapIndices(sliceobj)[source]¶ Adjusts the given slice object so that it may be used to index the underlying
nibabelNIFTI image object.See the
__determineShape()method.- Parameters
sliceobj – Something that can be used to slice a multi-dimensional array, e.g.
arr[sliceobj].
-
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
codeparameter may be eithersform(the default) orqformin 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_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
Trueif it looks like thisNiftiobject has a neurological voxel orientation,Falseotherwise. 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
Truefor images with an unknown orientation (e.g. the
sform_codeandqform_codeare both set to0). Therefore, you must check the orientation via thegetXFormCode()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
- ..warning:: This method will return
-
sameSpace(other)[source]¶ Returns
Trueif theotherimage (assumed to be aNiftiinstance) 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 rightORIENT_R2L: Right to leftORIENT_A2P: Anterior to posteriorORIENT_P2A: Posterior to anteriorORIENT_I2S: Inferior to superiorORIENT_S2I: Superior to inferiorORIENT_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 returnORIENT_UNKNOWNfor 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
Niftiobject with the specifiedpixdimorshape. The affine of the newNiftiis adjusted accordingly.Only one of
pixdimorshapecan be specified.See
affine.rescale()for the meaning of theoriginargument.Only the spatial dimensions may be adjusted - use the functions in the
image.resamplemodule 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
Niftiobject based on this one, with adjusted pixdims, shape and affine.
-
__module__= 'fsl.data.image'¶
-
class
fsl.data.image.Image(*args, **kwargs)[source]¶ Bases:
fsl.data.image.NiftiClass which represents a NIFTI image. Internally, the image is loaded/stored using a
nibabel.nifti1.Nifti1Imageornibabel.nifti2.Nifti2Image, and data access managed by aImageWrapper.In addition to the attributes added by the
Nifti.__init__()method, the following attributes/properties are present on anImageinstance as properties (https://docs.python.org/2/library/functions.html#property):nameThe name of this
Image- defaults to the image file name, sans-suffix.dataSourceThe data source of this
Image- the name of the file from where it was loaded, or some other string describing its origin.nibImageA reference to the
nibabelNIFTI image object.saveStateA boolean value which is
Trueif this image is saved to disk,Falseif it is in-memory, or has been edited.dataRangeThe minimum/maximum values in the image. Depending upon the value of the
calcRangeparameter to__init__(), this may be calculated when theImageis created, or may be incrementally updated as more image data is loaded from disk.The
Imageclass adds someNotifiertopics to those which are already provided by theNifticlass - listeners may register to be notified of changes to the above properties, by registering on the following _topic_ names (see theNotifierclass 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 (seeNotifier.notify()).'saveState'This topic is notified whenever the saved state of the image changes (i.e. data or
voxToWorldMatis edited, or the image saved to disk).'dataRange'This topic is notified whenever the image data range is changed/adjusted.
-
__init__(image, name=None, header=None, xform=None, loadData=True, calcRange=True, threaded=False, dataSource=None, loadMeta=False, **kwargs)[source]¶ Create an
Imageobject with the given image data or file name.- Parameters
image – A string containing the name of an image file to load, or a
numpyarray, or anibabelimage object, or anImageobject.name – A name for the image.
header – If not
None, assumed to be anibabel.nifti1.Nifti1Headerornibabel.nifti2.Nifti2Headerto be used as the image header. Not applied to images loaded from file, or existingnibabelimages.xform – A \(4\times 4\) affine transformation matrix which transforms voxel coordinates into real world coordinates. If not provided, and a
headeris provided, the transformation in the header is used. If neither axformnor aheaderare provided, an identity matrix is used. If both axformand aheaderare provided, thexformis used in preference to the header transformation.loadData – If
True(the default) the image data is loaded in to memory. Otherwise, only the image header information is read, and the image data is kept from disk. In either case, the image data is accessed through anImageWrapperinstance. The data may be loaded into memory later on via theloadData()method.calcRange – If
True(the default), the image range is calculated immediately (vi a call tocalcRange()). Otherwise, the image range is incrementally updated as more data is read from memory or disk.threaded – If
True, theImageWrapperwill use a separate thread for data range calculation. Defaults toFalse. Ignored ifloadDataisTrue.dataSource – If
imageis 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 thisImagevia theMetainterface. ifFalse, metadata can be loaded at a later stage via theloadMeta()function. Defaults toFalse.
All other arguments are passed through to the
nibabel.loadfunction (if it is called).
-
__hash__()[source]¶ Returns a number which uniquely idenfities this
Imageinstance (the result ofid(self)).
-
getImageWrapper()[source]¶ Returns the
ImageWrapperinstance used to manage access to the image data.
-
property
dataSource¶ Returns the data source (e.g. file name) that this
Imagewas loaded from (Noneif this image only exists in memory).
-
property
nibImage¶ Returns a reference to the
nibabelNIFTI image instance. Note that if the image data has been modified through thisImage, it will be out of sync with what is returned by thenibabelobject, until a call tosave()is made.
-
property
data¶ Returns the image data as a
numpyarray.Warning
Calling this method will cause the entire image to be loaded into memory.
-
property
saveState¶ Returns
Trueif thisImagehas been saved to disk,Falseotherwise.
-
property
dataRange¶ Returns the image data range as a
(min, max)tuple. If thecalcRangeparameter to__init__()wasFalse, these values may not be accurate, and may change as more image data is accessed.If the data range has not been no data has been accessed,
(None, None)is returned.
-
property
dtype¶ Returns the
numpydata 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_RGB24orNIFTI_TYPE_RGBA32.
-
property
iscomplex¶ Returns
Trueif this image has a complex data type,Falseotherwise.
-
property
voxToWorldMat¶ Returns a
numpyarray of shape(4, 4)containing an affine transformation from voxel coordinates to world coordinates.
-
__headerChanged(*args, **kwargs)¶ Called when header properties of this
Niftiinstance changes. Updates thesaveStateaccordinbgly.
-
__dataRangeChanged(*args, **kwargs)¶ Called when the
ImageWrapperdata range changes. Notifies any listeners of thisImage(registered through theNotifierinterface) on the'dataRange'topic.
-
calcRange(sizethres=None)[source]¶ Forces calculation of the image data range.
- Parameters
sizethres – If not
None, specifies an image size threshold (total number of bytes). If the number of bytes in the image is greater than this threshold, the range is calculated on a sample (the first volume for a 4D image, or slice for a 3D image).
-
loadData()[source]¶ Makes sure that the image data is loaded into memory. See
ImageWrapper.loadData().
-
save(filename=None)[source]¶ Saves this
Imageto the specifed file, or thedataSourceiffilenameisNone.Note that calling
saveon an image with modified data will cause the entire image data to be loaded into memory if it has not already been loaded.
-
__getitem__(sliceobj)[source]¶ Access the image data with the specified
sliceobj.- Parameters
sliceobj – Something which can slice the image data.
-
__setitem__(sliceobj, values)[source]¶ Set the image data at
sliceobjtovalues.- Parameters
sliceobj – Something which can slice the image data.
values – New image data.
Note
Modifying image data will force the entire image to be loaded into memory if it has not already been loaded.
-
__module__= 'fsl.data.image'¶
-
-
fsl.data.image.canonicalShape(shape)[source]¶ Calculates a canonical shape, how the given
shapeshould be presented. The shape is forced to be at least three dimensions, with any other trailing dimensions of length 1 ignored.
-
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
image –
Imageinstance- Returns
Dict containing any metadata that was loaded.
-
fsl.data.image.looksLikeImage(filename, allowedExts=None)[source]¶ Returns
Trueif the given file looks like a NIFTI image,Falseotherwise.Note
The
filenamecannot just be a file prefix - it must include the file suffix (e.g.myfile.nii.gz, notmyfile).- 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. SeeaddExt().
-
fsl.data.image.splitExt(filename)[source]¶ Splits the base name and extension for the given
filename. SeesplitExt().
-
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 actuallyfile.nii, this function will fix the file name.If
filenamealready exists, it is returned unchanged.All other arguments are passed through to
addExt().