This module provides Python bindings to the NIfTI data format.
The PyNIfTI module is a Python interface to the NIfTI I/O libraries. Using PyNIfTI, one can easily read and write NIfTI and ANALYZE images from within Python. The NiftiImage class provides pythonic access to the full header information and for a maximum of interoperability the image data is made available via NumPy arrays.
This modules provides a class representation of a NIfTI image header. The interface provides pythonic access to NIfTI properties using Python datatypes.
Bases: object
NIfTI header representation.
NIfTI header can be created by loading information from an existing NIfTI file or by creating a matching NIfTI header for a ndarray.
In addition, a number of methods to manipulate the header information are provided. However, this class is not able to write a NIfTI header back to disk. Please refer to the NIfTIImage class for this functionality.
Note
Handling of NIfTI header extensions is provided by the NiftiExtensions class (see its documentation for more information). Access to an instance of this class is available through the NiftiFormat.extensions attribute.
The constructor decides whether to load a nifti image header from file or create one from ndarray data, depending on the datatype of source.
Parameters: |
|
---|
Returns the header data of the NiftiImage in a dictionary.
Return type: | dict |
---|---|
Returns: | The dictionary contains all NIfTI header information. Additionally, it might also contain a special ‘meta’ item that contains the meta data currently assigned to this instance. |
Note
Modifications done to the returned dictionary do not cause any modifications in the NIfTI image itself. Please use updateFromDict() to apply changes to the image.
See also
Returns the shape of the dataimage.
Return type: | tuple |
---|---|
Returns: | The order of dimensions is (x,y,z,t,u,v,w). If the image has less dimensions than 7 the return tuple will be shortened accordingly. Please note that the order of dimensions is different from the tuple returned by calling NiftiImage.data.shape! |
See also
Returns the filename.
To distinguish ANALYZE from 2-file NIfTI images the image filename is returned for ANALYZE images while the header filename is returned for NIfTI files.
See also
Returns the shape of the dataimage.
Return type: | tuple |
---|---|
Returns: | The order of dimensions is (x,y,z,t,u,v,w). If the image has less dimensions than 7 the return tuple will be shortened accordingly. Please note that the order of dimensions is different from the tuple returned by calling NiftiImage.data.shape! |
See also
Returns the filename.
To distinguish ANALYZE from 2-file NIfTI images the image filename is returned for ANALYZE images while the header filename is returned for NIfTI files.
See also
Returns the inverse qform matrix.
Note
The inverse qform matrix cannot be modified in-place. One needs to set a new qform matrix instead. The corresponding inverse matrix is then re-calculated automatically.
See also
Returns the inverse sform matrix.
Note
The inverse sform matrix cannot be modified in-place. One needs to set a new sform matrix instead. The corresponding inverse matrix is then re-calculated automatically.
See also
Returns the pixel dimensions on all 7 dimensions.
The function is similar to getVoxDims(), but instead of the 3d spatial dimensions of a voxel it returns the dimensions of an image pixel on all 7 dimensions supported by the NIfTI dataformat.
See also
Returns the qform matrix.
Note
The returned qform matrix is not bound to the object. Therefore it cannot be successfully modified in-place. Modifications to the qform matrix can only be done by setting a new qform matrix
Return the qform code.
By default NIfTI xform codes are returned, but if as_string is set to true a string representation ala ‘talairach’ is returned instead.
See also
Returns a 3-tuple containing (qx, qy, qz).
See also
Returns to orientation of the i, j and k axis as stored in the qform matrix.
By default NIfTI orientation codes are returned, but if as_string is set to true a string representation ala ‘Left-to-right’ is returned instead.
Return type: | list |
---|---|
Returns: | orientations fo the x, y and z axis respectively. |
See also
Returns a 3-tuple containing (qb, qc, qd).
See also
Returns the temporal distance between the volumes in a timeseries.
See also
Returns the sform matrix.
Note
The returned sform matrix is not bound to the object. Therefore it cannot be successfully modified in-place. Modifications to the sform matrix can only be done by setting a new sform matrix
See also
setSForm(), setSFormCode(), getSFormCode(), sform, sform_inv, sform_code
Return the sform code.
By default NIfTI xform codes are returned, but if as_string is set to true a string representation ala ‘talairach’ is returned instead.
See also
Returns to orientation of the i, j and k axis as stored in the sform matrix.
By default NIfTI orientation codes are returned, but if as_string is set to true a string representation ala ‘Left-to-right’ is returned instead.
Return type: | list |
---|---|
Returns: | orientations fo the x, y and z axis respectively. |
See also
Return unit of temporal (4th) axis.
By default NIfTI unit codes are returned, but if as_string is set to true a string representation ala ‘s’ is returned instead.
See also
Returns the number of timepoints in the image.
In case of a 3d (or less dimension) image this method returns 1.
See also
Returns the size/shape of the volume(s) in the image as a tuple.
Return type: | tuple |
---|---|
Returns: | Either a 3-tuple or 2-tuple or 1-tuple depending on the available dimensions in the image. The order of dimensions in the tuple is (x [, y [, z ] ] ). |
See also
Returns a 3-tuple a voxel dimensions/size in (x,y,z).
See also
Return 3D-space unit.
By default NIfTI unit codes are returned, but if as_string is set to true a string representation ala ‘mm’ is returned instead.
See also
Access to a dictionary version of the NIfTI header data.
Note
This property cannot be used like this:
nimg.header['something'] = 'new value'
Instead one has to get the header dictionary, modify and later reassign it:
h = nimg.header
h['something'] = 'new value'
nimg.header = h
See also
Returns the pixel dimensions on all 7 dimensions.
The function is similar to getVoxDims(), but instead of the 3d spatial dimensions of a voxel it returns the dimensions of an image pixel on all 7 dimensions supported by the NIfTI dataformat.
See also
Returns the qform matrix.
Note
The returned qform matrix is not bound to the object. Therefore it cannot be successfully modified in-place. Modifications to the qform matrix can only be done by setting a new qform matrix
Return the qform code.
By default NIfTI xform codes are returned, but if as_string is set to true a string representation ala ‘talairach’ is returned instead.
See also
Returns the inverse qform matrix.
Note
The inverse qform matrix cannot be modified in-place. One needs to set a new qform matrix instead. The corresponding inverse matrix is then re-calculated automatically.
See also
Returns a 3-tuple containing (qx, qy, qz).
See also
Returns a 3-tuple containing (qb, qc, qd).
See also
Returns the temporal distance between the volumes in a timeseries.
See also
Set the description element in the NIfTI header.
Parameters: |
|
---|
See also
Set the intercept attribute in the NIfTI header.
The intercept is only considered for scaling in case of a non-zero slope value.
Set the pixel dimensions.
Parameters: |
|
---|
Note
Calling setPixDims() with a length-3 sequence equals calling setVoxDims().
See also
Set qfac (scaling factor of qform matrix).
The qform matrix and its inverse are re-computed automatically.
Besides reading it is also possible to set the qfac by assigning to the qfac property.
Parameters: |
|
---|
Sets the qform matrix.
The supplied value has to be a 4x4 matrix. The matrix will be converted to float.
The inverse qform matrix and the quaternion representation will be automatically recalculated.
Parameters: |
|
---|
Set the qform code.
Note
This is a convenience frontend for setXFormCode(). Please see its documentation for more information.
Set QOffset from 3-tuple (qx, qy, qz).
The qform matrix and its inverse are re-computed automatically.
Besides reading it is also possible to set the qoffset by assigning to the qoffset property.
Parameters: |
|
---|
See also
Set Quaternion from 3-tuple (qb, qc, qd).
The qform matrix and it’s inverse are re-computed automatically.
Parameters: |
|
---|
See also
getQForm(), setQForm(), setQFormCode(), getQFormCode(), getQuaternion(), getQOffset(), setQOffset(), setQFac(), qform, qform_inv, qform_code, quatern, qoffset, qfac
Set the repetition time of a NIfTI image (dt).
See also
Sets the sform matrix.
The supplied value has to be a 4x4 matrix. The matrix elements will be converted to floats. By definition the last row of the sform matrix has to be (0,0,0,1). However, different values can be assigned, but will not be stored when the NIfTI image is saved to a file.
The inverse sform matrix will be automatically recalculated.
Parameters: |
|
---|
See also
getSForm(), setSFormCode(), getSFormCode(), sform, sform_code
Set the sform code.
Note
This is a convenience frontend for setXFormCode(). Please see its documentation for more information.
Set the slope attribute in the NIfTI header.
Setting the slope to zero, will disable scaling.
Set the unit of the temporal axis (4th).
Parameters: |
|
---|
See also
Set voxel dimensions/size.
The qform matrix and its inverse will be recalculated automatically.
Parameters: |
|
---|
See also
Set the type of space described by the NIfTI transformations.
The NIfTI format defines five coordinate system types which are used to describe the target space of a transformation (qform or sform). Please note, that the last four transformation types are only available in the NIfTI format and not when saving into ANALYZE.
- ‘unkown’, NIFTI_XFORM_UNKNOWN, 0:
- Transformation is arbitrary. This is the ANALYZE compatibility mode. In this case no sform matrix will be written, even when stored in NIfTI and not in ANALYZE format. Additionally, only the pixdim parts of the qform matrix will be saved (upper-left 3x3).
- ‘scanner’, NIFTI_XFORM_SCANNER_ANAT, 1:
- Scanner-based anatomical coordinates.
- ‘aligned’, NIFTI_XFORM_ALIGNED_ANAT, 2:
- Coordinates are aligned to another file’s coordinate system.
- ‘talairach’, NIFTI_XFORM_TALAIRACH, 3:
- Coordinate system is shifted to have its origin (0,0,0) at the anterior commissure, as in the Talairach-Tournoux Atlas.
- ‘mni152’, NIFTI_XFORM_MNI_152, 4:
- Coordinates are in MNI152 space.
Parameters: |
|
---|
See also
setQFormCode(), getQFormCode(), setSFormCode(), getSFormCode(), qform_code, sform_code
Set the unit of the spatial axes.
Parameters: |
|
---|
See also
Returns the sform matrix.
Note
The returned sform matrix is not bound to the object. Therefore it cannot be successfully modified in-place. Modifications to the sform matrix can only be done by setting a new sform matrix
See also
setSForm(), setSFormCode(), getSFormCode(), sform, sform_inv, sform_code
Return the sform code.
By default NIfTI xform codes are returned, but if as_string is set to true a string representation ala ‘talairach’ is returned instead.
See also
Returns the inverse sform matrix.
Note
The inverse sform matrix cannot be modified in-place. One needs to set a new sform matrix instead. The corresponding inverse matrix is then re-calculated automatically.
See also
Return unit of temporal (4th) axis.
By default NIfTI unit codes are returned, but if as_string is set to true a string representation ala ‘s’ is returned instead.
See also
Returns the number of timepoints in the image.
In case of a 3d (or less dimension) image this method returns 1.
See also
Update NIfTI header information.
Updated header data is read from the supplied dictionary. One cannot modify dimensionality and datatype of the image data. If such information is present in the header dictionary it is removed before the update. If resizing or datatype casting are required one has to convert the image data into a separate array and perform resize and data manipulations on this array. When finished, the array can be converted into a nifti file by calling the NiftiImage constructor with the modified array as ‘source’ and the nifti header of the original NiftiImage object as ‘header’.
Note
If the provided dictionary contains a ‘meta’ item its content is used to overwrite any potentially existing meta data. dictionary.
The same behavior will be used for ‘extensions’. If extensions are defined in the provided dictionary all currently existing extensions will be overwritten.
Returns the size/shape of the volume(s) in the image as a tuple.
Return type: | tuple |
---|---|
Returns: | Either a 3-tuple or 2-tuple or 1-tuple depending on the available dimensions in the image. The order of dimensions in the tuple is (x [, y [, z ] ] ). |
See also
Returns a 3-tuple a voxel dimensions/size in (x,y,z).
See also
Transform a voxel’s index into coordinates (qform-defined).
Parameters: |
|
---|---|
Return type: | vector |
See also
Transform a voxel’s index into coordinates (sform-defined).
Parameters: |
|
---|---|
Return type: | vector |
See also
Return 3D-space unit.
By default NIfTI unit codes are returned, but if as_string is set to true a string representation ala ‘mm’ is returned instead.
See also
This module provides two classes for accessing NIfTI files.
Bases: nifti.format.NiftiFormat
Wrapper class for convenient access to NIfTI images.
An image can either be loaded from a file or created from a NumPy ndarray. Either way is automatically determined by the type of the ‘source’ argument. If source is a string, it is assumed to be a filename an ndarray is treated as such.
All NIfTI header information is conveniently exposed via Python data types. This functionality is provided by the NiftiFormat base class. Please refer to its documentation for the full list of its methods and properties.
See also
Parameters: |
|
---|
Convert the image data into a ndarray.
Parameters: |
|
---|
Get the bounding box an image.
The bounding box is the smallest box covering all non-zero elements.
Return type: | tuple(2-tuples) | None |
---|---|
Returns: | It returns as many (min, max) tuples as there are image dimensions. The order of dimensions is identical to that in the data array. None is returned of the images does not contain non-zero elements. |
Examples:
>>> from nifti import NiftiImage >>> nim = NiftiImage(N.zeros((12, 24, 32))) >>> nim.bbox is None True>>> nim.data[3,10,13] = 1 >>> nim.data[6,20,26] = 1 >>> nim.bbox ((3, 6), (10, 20), (13, 26))>>> nim.crop() >>> nim.data.shape (4, 11, 14) >>> nim.bbox ((0, 3), (0, 10), (0, 13))
Crop an image.
Parameters: |
|
---|
Returns a scaled copy of the data array.
Scaling is done by multiplying with the slope and adding the intercept that is stored in the NIfTI header. In compliance with the NIfTI standard scaling is only performed in case of a non-zero slope value. The original data array is returned otherwise.
Return type: | ndarray |
---|
Load the image data into memory, if it is not already accessible.
It is save to call this method several times successively.
Save the image to a file.
If the image was created using array data (i.e., not loaded from a file) a filename has to be specified.
If not yet done already, the image data will be loaded into memory before saving the file.
Parameters: |
|
---|
Warning
There will be no exception if writing fails for any reason, as the underlying function nifti_write_hdr_img() from libniftiio does not provide any feedback. Suggestions for improvements are appreciated.
Set the filename for the NIfTI image.
Setting the filename also determines the filetype. If the filename ends with ‘.nii’ the type will be set to NIfTI single file. A ‘.hdr’ extension can be used for NIfTI file pairs. If the desired filetype is ANALYZE the extension should be ‘.img’. However, one can use the ‘.hdr’ extension and force the filetype to ANALYZE by setting the filetype argument to ANALYZE. Setting filetype if the filename extension is ‘.nii’ has no effect, the file will always be in NIFTI format.
If the filename carries an additional ‘.gz’ the resulting file(s) will be compressed.
Uncompressed NIfTI single files are the default filetype that will be used if the filename has no valid extension. The ‘.nii’ extension is appended automatically. The ‘filetype’ argument can be used to force a certain filetype when no extension can be used to determine it. ‘filetype’ can be one of the nifticlibs filtetypes or any of ‘NIFTI’, ‘NIFTI_GZ’, ‘NIFTI_PAIR’, ‘NIFTI_PAIR_GZ’, ‘ANALYZE’, ‘ANALYZE_GZ’.
Setting the filename will cause the image data to be loaded into memory if not yet done already. This has to be done, because without the filename of the original image file there would be no access to the image data anymore. As a side-effect a simple operation like setting a filename may take a significant amount of time (e.g. for a large 4d dataset).
By passing an empty string or none as filename one can reset the filename and detach the NiftiImage object from any file on disk.
Examples:
Filename Output of save() exmpl.nii exmpl.nii (NIfTI) exmpl.hdr exmpl.hdr, exmpl.img (NIfTI) exmpl.img exmpl.hdr, exmpl.img (ANALYZE) exmpl exmpl.nii (NIfTI) exmpl.hdr.gz exmpl.hdr.gz, exmpl.img.gz (NIfTI) exmpl.gz exmpl.gz.nii (uncompressed NIfTI)
Setting the filename is also possible by assigning to the ‘filename’ property.
See also
Unload image data and free allocated memory.
This methods does nothing in case of memory mapped files.
Deprecated method only here for backward compatibility.
Please refer to NiftiFormat.updateFromDict()
Bases: nifti.image.NiftiImage
Memory mapped access to uncompressed NIfTI files.
This access mode might be the prefered one whenever only a small part of the image data has to be accessed or the memory is not sufficient to load the whole dataset.
Please note, that memory-mapping is not required when exclusively header information shall be accessed. The NiftiFormat class and by default also the NiftiImage class will not load any image data into memory.
Note
The class is mostly useful for read-only access to the NIfTI image data. It currently neither supports saving changed header fields nor storing meta data.
Create a NiftiImage object.
This method decides whether to load a nifti image from file or create one from ndarray data, depending on the datatype of source.
Parameters: |
|
---|
Save the image.
This methods does nothing except for syncing the file on the disk.
Please note that the NIfTI header might not be completely up-to-date. For example, the min and max values might be outdated, but this class does not automatically update them, because it would require to load and search through the whole array.
This module provides a container-like interface to NIfTI1 header extensions.
Bases: object
NIfTI1 header extension handler.
This class wraps around a NIfTI1 struct and provides container-like access to NIfTI1 header extensions. It is basically a hibrid between a list and a dictionary. The reason for this is that the NIfTI header allows for a list of extensions, but additionally each extension is associated with some type (ecode or extension code). This is some form of mapping, however, the ecodes are not necessarily unique (e.g. multiple comments).
The current list of known extensions is documented here:
http://nifti.nimh.nih.gov/nifti-1/documentation/faq#Q21
The usage is best explained by a few examples. All examples assume a NIfTI image to be loaded:
>>> from nifti import NiftiImage
>>> nim = NiftiImage('example4d.nii.gz')
Access to the extensions is provided through the extensions attribute of the NiftiImage class:
>>> type(nim.extensions)
<class 'nifti.extensions.NiftiExtensions'>
How many extensions are avialable?
>>> len(nim.extensions)
2
How many comments? Any AFNI extension?
>>> nim.extensions.count('comment')
2
Show me all ecodes of all extensions:
>>> nim.extensions.ecodes
[6, 6]
Add an AFNI extension:
>>> nim.extensions += ('afni', '<xml>Some voodoo</xml>')
>>> nim.extensions.ecodes
[6, 6, 4]
Delete superfluous comment extension:
>>> del nim.extensions[1]
Access the last extension, which should be the AFNI one:
>>> nim.extensions[-1]
'<xml>Some voodoo</xml>'
Wipe them all:
>>> nim.extensions.clear()
>>> len(nim.extensions)
0
Parameters: |
|
---|
Append a new extension.
Parameters: |
|
---|
Returns the number of extensions matching a given ecode.
Parameters: |
|
---|
Utility functions for PyNifti
Apply a function on selected volumes of a timeseries.
‘ts’ is a 4d timeseries. It can be a NiftiImage or a ndarray. In case of a ndarray one has to make sure that the time is on the first axis. ‘ts’ can actually be of any dimensionality, but datasets aka volumes are assumed to be along the first axis.
‘vols’ is either a sequence of sequences or a 2d array indicating which volumes fx should be applied to. Each row defines a set of volumes.
‘fx’ is a callable function to get an array of the selected volumes as argument. Additonal arguments may be specified as keyword arguments and are passed to ‘fx’.
The output will be a 4d array with one computed volume per row in the ‘vols’ array.
Returns 4d array with peristimulus timeseries.
Parameters: |
|
---|
Split a NIfTI filename into basename and extension.
Parameters: |
|
---|---|
Return type: | tuple |
Returns: | The function returns a tuple of basename and extension. If no valid NIfTI filename extension is found, the whole string is returned as basename and the extension string will be empty. |
Translates a time ‘t’ into a volume number. By default function returns the volume number that is closest in time. Volumes are assumed to be recorded exactly (and completely) after tr/2, e.g. if ‘tr’ is 2 secs the first volume is recorded at exactly one second.
‘t’ might be a single value, a sequence or an array.
The repetition ‘tr’ might be specified directly, but can also be a NiftiImage object. In the latter case the value of ‘tr’ is determined from the ‘rtime’ property of the NiftiImage object.
‘t’ and ‘tr’ can be given in an arbitrary unit (but both have to be in the same unit).
The ‘lag’ argument can be used to shift the times by constant offset.
Please note that numpy.round() is used to round to interger value (rounds to even numbers). The ‘decimals’ argument will be passed to numpy.round().
Functions operating on images
Get the bounding box an image.
The bounding box is the smallest box covering all non-zero elements.
Return type: | tuple(2-tuples) | None |
---|---|
Returns: | It returns as many (min, max) tuples as there are image dimensions. The order of dimensions is identical to that in the data array. None is returned of the images does not contain non-zero elements. |
Examples:
>>> from nifti import NiftiImage >>> nim = NiftiImage(N.zeros((12, 24, 32))) >>> nim.bbox is None True>>> nim.data[3,10,13] = 1 >>> nim.data[6,20,26] = 1 >>> nim.bbox ((3, 6), (10, 20), (13, 26))>>> nim.crop() >>> nim.data.shape (4, 11, 14) >>> nim.bbox ((0, 3), (0, 10), (0, 13))
Crop an image.
Parameters: |
|
---|