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. |
loadIndexedImageFile |
Loads the given image file using nibabel and indexed_gzip . |
-
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 functions below.
-
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
¶ Bases:
Exception
Exception
class raised by the functions defined in this module when something goes wrong.
-
class
fsl.data.image.
Nifti
(header)¶ Bases:
fsl.utils.notifier.Notifier
,fsl.utils.meta.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. TheNifti
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 theImage
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. 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 anifti1
,nifti2
, oranalyze
header 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
shape
attribute 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.The affine transformation
The
voxToWorldMat()
andworldToVoxMat()
attributes contain transformation matrices for transforming between voxel and world coordinates. TheNifti
class follows the same process asnibabel
in selecting the affine (see http://nipy.org/nibabel/nifti_images.html#the-nifti-affines):- If
sform_code != 0
(“unknown”) use the sform affine; else - If
qform_code != 0
(“unknown”) use the qform affine; else - Use the fall-back affine.
However, the fall-back affine used by the
Nifti
class differs to that used bynibabel
. Innibabel
, the origin (world coordinates (0, 0, 0)) is set to the centre of the image. Here in theNifti
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 aNifti
instance (unless it is an Analyze image). When you do so:- Only the
sform
of the underlyingNifti1Header
object is changed - The
qform
is not modified. - If the
sform_code
was previously set toNIFTI_XFORM_UNKNOWN
, it is changed toNIFTI_XFORM_ALIGNED_ANAT
. Otherwise, thesform_code
is not modified.
ANALYZE support
A
Nifti
instance expects to be passed either anibabel.nifti1.Nifti1Header
or anibabel.nifti2.Nifti2Header
, but can als 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
origin
fields. Construction of the affine is handled bynibabel
. - The
niftiVersion()
method will return0
. - The
getXFormCode()
method will returnconstants.NIFTI_XFORM_ANALYZE
.
Metadata
The
Image
class inherits from theMeta
class - its methods can be used to store and query any meta-data associated with the image.Notification
The
Nifti
class implements theNotifier
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.-
strval
(key)¶ 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.
-
niftiVersion
¶ Returns the NIFTI file version:
0
for ANALYZE1
for NIFTI12
for NIFTI2
-
shape
¶ Returns a tuple containing the image data shape.
-
pixdim
¶ Returns a tuple containing the image pixdims (voxel sizes).
-
intent
¶ Returns the NIFTI intent code of this image.
-
xyzUnits
¶ Returns the NIFTI XYZ dimension unit code.
-
timeUnits
¶ Returns the NIFTI time dimension unit code.
-
worldToVoxMat
¶ Returns a
numpy
array of shape(4, 4)
containing an affine transformation from world coordinates to voxel coordinates.
-
voxToWorldMat
¶ Returns a
numpy
array of shape(4, 4)
containing an affine transformation from voxel coordinates to world coordinates.
-
mapIndices
(sliceobj)¶ Adjusts the given slice object so that it may be used to index the underlying
nibabel
NIFTI image object.See the
__determineShape()
method.Parameters: sliceobj – Something that can be used to slice a multi-dimensional array, e.g. arr[sliceobj]
.
-
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.
-
ndims
¶ Deprecated - use :mod::meth:
ndim
instead.Deprecated in 1.9.0, to be removed in 2.0.0. Use ndim instead
-
is4DImage
()¶ Returns
True
if this image is 4D,False
otherwise.Deprecated in 1.1.0, to be removed in 2.0.0. Use ndims instead
-
getXFormCode
(code=None)¶ 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 eithersform
(the default) orqform
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_ANALYZE
-
axisMapping
(xform)¶ 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
()¶ Returns
True
if it looks like thisNifti
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
andqform_code
are 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
-
voxelsToScaledVoxels
()¶ See
voxToScaledVoxMat()
.Deprecated in 1.2.0, to be removed in 2.0.0. Use voxToScaledVoxMat instead
-
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
-
scaledVoxToVoxMat
¶ Returns a transformation matrix which transforms from scaled voxels into voxels, the inverse of the
voxToScaledVoxMat()
transform.
-
sameSpace
(other)¶ Returns
True
if theother
image (assumed to be aNifti
instance) has the same dimensions and is in the same space as this image.
-
getOrientation
(axis, xform)¶ 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_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).
- If
-
class
fsl.data.image.
Image
(image, name=None, header=None, xform=None, loadData=True, calcRange=True, indexed=False, threaded=False, dataSource=None, **kwargs)¶ Bases:
fsl.data.image.Nifti
Class which represents a NIFTI image. Internally, the image is loaded/stored using a
nibabel.nifti1.Nifti1Image
ornibabel.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 anImage
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.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.dataRange
The minimum/maximum values in the image. Depending upon the value of the calcRange
parameter to__init__()
, this may be calculated when theImage
is created, or may be incrementally updated as more image data is loaded from disk.The
Image
class adds someNotifier
topics to those which are already provided by theNifti
class - listeners may register to be notified of changes to the above properties, by registering on the following _topic_ names (see theNotifier
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 (seeNotifier.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'
This topic is notified whenever the image data range is changed/adjusted. -
getImageWrapper
()¶ Returns the
ImageWrapper
instance used to manage access to the image data.
-
dataSource
¶ Returns the data source (e.g. file name) that this
Image
was loaded from (None
if this image only exists in memory).
-
nibImage
¶ Returns a reference to the
nibabel
NIFTI image instance.
-
data
¶ Returns the image data as a
numpy
array.Warning
Calling this method will cause the entire image to be loaded into memory.
-
saveState
¶ Returns
True
if thisImage
has been saved to disk,False
otherwise.
-
dataRange
¶ Returns the image data range as a
(min, max)
tuple. If thecalcRange
parameter 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.
-
dtype
¶ Returns the
numpy
data type of the image data.
-
voxToWorldMat
¶ Returns a
numpy
array of shape(4, 4)
containing an affine transformation from voxel coordinates to world coordinates.
-
calcRange
(sizethres=None)¶ 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
()¶ Makes sure that the image data is loaded into memory. See
ImageWrapper.loadData()
.
-
save
(filename=None)¶ Saves this
Image
to the specifed file, or thedataSource
iffilename
isNone
.
-
resample
(newShape, sliceobj=None, dtype=None, order=1, smooth=True)¶ Returns a copy of the data in this
Image
, resampled to the specifiedshape
.Parameters: - newShape – Desired shape. May containg floating point values,
in which case the resampled image will have shape
round(newShape)
, but the voxel sizes will have scalesself.shape / newShape
. - sliceobj – Slice into this
Image
. IfNone
, the whole image is resampled, and it is assumed that it has the same number of dimensions asshape
. AValueError
is raised if this is not the case. - dtype –
numpy
data type of the resampled data. IfNone
, thedtype()
of thisImage
is used. - order – Spline interpolation order, passed through to the
scipy.ndimage.affine_transform
function -0
corresponds to nearest neighbour interpolation,1
(the default) to linear interpolation, and3
to cubic interpolation. - smooth – If
True
(the default), the data is smoothed before being resampled, but only along axes which are being down-sampled (i.e. wherenewShape[i] < self.shape[i]
).
Returns: A tuple containing:
- A
numpy
array of shapeshape
, containing an interpolated copy of the data in thisImage
. - A
numpy
array of shape(4, 4)
, containing the adjusted voxel-to-world transformation for the resampled data.
- newShape – Desired shape. May containg floating point values,
in which case the resampled image will have shape
-
-
fsl.data.image.
canonicalShape
(shape)¶ 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.
looksLikeImage
(filename, allowedExts=None)¶ 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
, 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)¶ Adds a file extension to the given file
prefix
. SeeaddExt()
.
-
fsl.data.image.
splitExt
(filename)¶ Splits the base name and extension for the given
filename
. SeesplitExt()
.
-
fsl.data.image.
removeExt
(filename)¶ Removes the extension from the given file name. See
removeExt()
.
-
fsl.data.image.
defaultExt
()¶ 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.
-
fsl.data.image.
loadIndexedImageFile
(filename)¶ Loads the given image file using
nibabel
andindexed_gzip
.Returns a tuple containing the
nibabel
NIFTI image, and the openIndexedGzipFile
handle.If
indexed_gzip
is not present, the image is loaded normally vianibabel.load
.
-
fsl.data.image.
read_segments
(fileobj, segments, n_bytes)¶ - This function is used in place of the
nibabel.fileslice.read_segments
function to ensure thread-safe read access to image data via thenibabel.arrayproxy.ArrayProxy
(thedataobj
attribute of anibabel
image).The
nibabel
implementation uses multiple calls toseek
andread
to read segments of data from the file. When accessed by multiple threads, these seeks and reads can become intertwined, which causes a read from one thread to read data from the seek location requested by the other thread.This implementation protects the seek/read pairs with a
threading.Lock
, which is added toIndexedGzipFile
instances that are created in theloadIndexedImageFile()
function.Note
This patch is not required in nibabel 2.2.0 and newer. It will be removed from
fslpy
in version 2.0.0.
Deprecated in 1.3.0, to be removed in 2.0.0. Upgrade to nibabel 2.2.0