PyNIfTI - Pythonic access to NIfTI and ANALYZE files

### Navigation

- index
- next |
- previous |
- NIfTI Libraries |
- PyNIfTI Home |
- Documentation »

# Module Reference

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.

## Module `format`

This modules provides a class representation of a NIfTI image header. The interface provides pythonic access to NIfTI properties using Python datatypes.

### `NiftiFormat`

class `nifti.format.``NiftiFormat`(source, header=None, loadmeta=False)

  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:

  - source (str | ndarray) – If source is a string, it is assumed to be a filename and an attempt will be made to open the corresponding NIfTI file. Filenames might be provided as unicode strings. However, as the underlying library does not support unicode, they must be ascii-encodable, i.e. must not contain pure unicode characters. In case of an ndarray the array data will be used for the to be created nifti image and a matching nifti header is generated. If an object of a different type is supplied as ‘source’ a ValueError exception will be thrown.
  - header (dict) – Additional header data might be supplied if image data is not loaded from a file. However, dimensionality and datatype are determined from the ndarray and not taken from a header dictionary.

  `asDict`()

    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

    `updateFromDict()`, `header`

  `description`
  `extent`

    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

    `getVolumeExtent()`, `getTimepoints()`, `extent`

  `filename`

    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

    `filename`

  `getExtent`()

    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

    `getVolumeExtent()`, `getTimepoints()`, `extent`

  `getFilename`()

    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

    `filename`

  `getInverseQForm`()

    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

    `getQForm()`, `qform`, `qform_inv`,

  `getInverseSForm`()

    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

    `getSForm()`, `sform`, `sform_inv`,

  `getPixDims`()

    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

    `getVoxDims()`, `setPixDims()`, `pixdim`

  `getQForm`()

    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

    See also

    `setQForm()`, `setQFormCode()`, `getQFormCode()`, `getQuaternion()`, `getQOffset()`, `setQuaternion()`, `setQOffset()`, `setQFac()`, `qform`, `qform_inv`, `qform_code`, `quatern`, `qoffset`, `qfac`

  `getQFormCode`(as_string=False)

    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

    `getQFormCode()`, `qform_code`

  `getQOffset`()

    Returns a 3-tuple containing (qx, qy, qz).

    See also

    `setQOffset()`, `qform`, `qoffset`

  `getQOrientation`(as_string=False)

    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

    `qform`

  `getQuaternion`()

    Returns a 3-tuple containing (qb, qc, qd).

    See also

    `setQuaternion()`, `qform`, `quatern`

  `getRepetitionTime`()

    Returns the temporal distance between the volumes in a timeseries.

    See also

    `setRepetitionTime()`, `rtime`

  `getSForm`()

    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`

  `getSFormCode`(as_string=False)

    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

    `getSFormCode()`, `sform_code`

  `getSOrientation`(as_string=False)

    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

    `sform`

  `getTimeUnit`(as_string=False)

    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

    `setTimeUnit()`, `time_unit`

  `getTimepoints`()

    Returns the number of timepoints in the image.

    In case of a 3d (or less dimension) image this method returns 1.

    See also

    `timepoints`

  `getVolumeExtent`()

    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

    `getExtent()`, `volextent`

  `getVoxDims`()

    Returns a 3-tuple a voxel dimensions/size in (x,y,z).

    See also

    `setVoxDims()`, `voxdim`

  `getXYZUnit`(as_string=False)

    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

    `setXYZUnit()`, `xyz_unit`

  `header`

    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

    `asDict()`, `updateFromDict()`

  `intercept`
  `max`
  `min`
  `nvox`
  `pixdim`

    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

    `getVoxDims()`, `setPixDims()`, `pixdim`

  `qfac`
  `qform`

    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

    See also

    `setQForm()`, `setQFormCode()`, `getQFormCode()`, `getQuaternion()`, `getQOffset()`, `setQuaternion()`, `setQOffset()`, `setQFac()`, `qform`, `qform_inv`, `qform_code`, `quatern`, `qoffset`, `qfac`

  `qform_code`

    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

    `getQFormCode()`, `qform_code`

  `qform_inv`

    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

    `getQForm()`, `qform`, `qform_inv`,

  `qoffset`

    Returns a 3-tuple containing (qx, qy, qz).

    See also

    `setQOffset()`, `qform`, `qoffset`

  `quatern`

    Returns a 3-tuple containing (qb, qc, qd).

    See also

    `setQuaternion()`, `qform`, `quatern`

  `raw_nimg`
  `rtime`

    Returns the temporal distance between the volumes in a timeseries.

    See also

    `setRepetitionTime()`, `rtime`

  `setDescription`(value)

    Set the description element in the NIfTI header.

    Parameters: | value (str) – Description – must not be longer than 79 characters.

    See also

    `description`

  `setIntercept`(value)

    Set the intercept attribute in the NIfTI header.

    The intercept is only considered for scaling in case of a non-zero slope value.

    See also

    `slope`, `intercept`

  `setPixDims`(value)

    Set the pixel dimensions.

    Parameters: | value (sequence) – Up to 7 values (max. number of dimensions supported by the NIfTI format) are allowed in the sequence. The supplied sequence can be shorter than seven elements. In this case only present values are assigned starting with the first dimension (spatial: x).

    Note

    Calling setPixDims() with a length-3 sequence equals calling setVoxDims().

    See also

    `setVoxDims()`, `getPixDims()`, `pixdim`

  `setQFac`(value, code='scanner')

    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:

    - value (float) – Scaling factor.
    - code (str | NIFTI_XFORM_CODE | int (0..4)) – The type of the coordinate system the corresponding qform matrix is describing. By default this coordinate system is assumed to be the scanner space. Please refer to the `setXFormCode()` method for a full list of possible codes and their meaning.

    See also

    `qform`, `qfac`

  `setQForm`(m, code='scanner')

    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:

    - m (4x4 ndarray) – The qform matrix.
    - code (str | NIFTI_XFORM_CODE | int (0..4)) – The type of the coordinate system the qform matrix is describing. By default this coordinate system is assumed to be the scanner space. Please refer to the `setXFormCode()` method for a full list of possible codes and their meaning.

    See also

    `getQForm()`, `setQFormCode()`, `getQFormCode()`, `getQuaternion()`, `getQOffset()`, `setQuaternion()`, `setQOffset()`, `setQFac()`, `qform`, `qform_inv`, `qform_code`, `quatern`, `qoffset`, `qfac`

  `setQFormCode`(code)

    Set the qform code.

    Note

    This is a convenience frontend for `setXFormCode()`. Please see its documentation for more information.

  `setQOffset`(value, code='scanner')

    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:

    - value (length-3 sequence) – qx, qy and qz offsets.
    - code (str | NIFTI_XFORM_CODE | int (0..4)) – The type of the coordinate system the corresponding qform matrix is describing. By default this coordinate system is assumed to be the scanner space. Please refer to the `setXFormCode()` method for a full list of possible codes and their meaning.

    See also

    `getQOffset()`, `qform`, `qoffset`

  `setQuaternion`(value, code='scanner')

    Set Quaternion from 3-tuple (qb, qc, qd).

    The qform matrix and it’s inverse are re-computed automatically.

    Parameters:

    - value (length-3 sequence) – qb, qc and qd quaternions.
    - code (str | NIFTI_XFORM_CODE | int (0..4)) – The type of the coordinate system the corresponding qform matrix is describing. By default this coordinate system is assumed to be the scanner space. Please refer to the `setXFormCode()` method for a full list of possible codes and their meaning.

    See also

    `getQForm()`, `setQForm()`, `setQFormCode()`, `getQFormCode()`, `getQuaternion()`, `getQOffset()`, `setQOffset()`, `setQFac()`, `qform`, `qform_inv`, `qform_code`, `quatern`, `qoffset`, `qfac`

  `setRepetitionTime`(value)

    Set the repetition time of a NIfTI image (dt).

    See also

    `getRepetitionTime()`, `rtime`

  `setSForm`(m, code='mni152')

    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:

    - m (4x4 ndarray) – The sform matrix.
    - code (str | NIFTI_XFORM_CODE | int (0..4)) – The type of the coordinate system the sform matrix is describing. By default this coordinate system is assumed to be the MNI152 space. Please refer to the `setXFormCode()` method for a full list of possible codes and their meaning.

    See also

    `getSForm()`, `setSFormCode()`, `getSFormCode()`, `sform`, `sform_code`

  `setSFormCode`(code)

    Set the sform code.

    Note

    This is a convenience frontend for `setXFormCode()`. Please see its documentation for more information.

  `setSlope`(value)

    Set the slope attribute in the NIfTI header.

    Setting the slope to zero, will disable scaling.

    See also

    `slope`, `intercept`

  `setTimeUnit`(value)

    Set the unit of the temporal axis (4th).

    Parameters: | value (int | str) – The unit can either be given as a NIfTI unit code or as any of the plain text abbrevations returned by :meth:’~nifti.format.NiftiFormat.getTimeUnit`

    See also

    `getTimeUnit()`, `time_unit`

  `setVoxDims`(value)

    Set voxel dimensions/size.

    The qform matrix and its inverse will be recalculated automatically.

    Parameters: | value (3-tuple of floats) – Have to be given in (x,y,z) order.

    See also

    `getVoxDims()`, `voxdim`

  `setXFormCode`(xform, code)

    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:

    - xform (‘qform’ | ‘q’ | ‘sform’ | ‘s’) – Which of the two NIfTI transformations to set.
    - code (str | NIFTI_XFORM_CODE | int (0..4)) – The Transformation code can be specified either by a string, the NIFTI_XFORM_CODE defined in the nifti1.h header file (accessible via the nifti.clib module, or the corresponding integer value.

    See also

    `setQFormCode()`, `getQFormCode()`, `setSFormCode()`, `getSFormCode()`, `qform_code`, `sform_code`

  `setXYZUnit`(value)

    Set the unit of the spatial axes.

    Parameters: | value (int | str) – The unit can either be given as a NIfTI unit code or as any of the plain text abbrevations returned by :meth:’~nifti.format.NiftiFormat.getXYZUnit`

    See also

    `getXYZUnit()`, `xyz_unit`

  `sform`

    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`

  `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

    `getSFormCode()`, `sform_code`

  `sform_inv`

    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

    `getSForm()`, `sform`, `sform_inv`,

  `slope`
  `time_unit`

    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

    `setTimeUnit()`, `time_unit`

  `timepoints`

    Returns the number of timepoints in the image.

    In case of a 3d (or less dimension) image this method returns 1.

    See also

    `timepoints`

  `updateFromDict`(hdrdict)

    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.

    See also

    `asDict()`, `header`

  `updateQFormFromQuaternion`()

    Only here for backward compatibility.

  `volextent`

    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

    `getExtent()`, `volextent`

  `voxdim`

    Returns a 3-tuple a voxel dimensions/size in (x,y,z).

    See also

    `setVoxDims()`, `voxdim`

  `vx2q`(coord)

    Transform a voxel’s index into coordinates (qform-defined).

    Parameters: | coord (3-tuple) – A voxel’s index in the volume fiven as three positive integers (i, j, k).
    Return type: | vector

    See also

    `setQForm()`, `getQForm()` `qform`

  `vx2s`(coord)

    Transform a voxel’s index into coordinates (sform-defined).

    Parameters: | coord (3-tuple) – A voxel’s index in the volume fiven as three positive integers (i, j, k).
    Return type: | vector

    See also

    `setSForm()`, `getSForm()` `sform`

  `xyz_unit`

    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

    `setXYZUnit()`, `xyz_unit`

## Module `image`

This module provides two classes for accessing NIfTI files.

- `NiftiImage` (traditional load-as-much-as-you-can approach)
- `MemMappedNiftiImage` (memory-mapped access to uncompressed NIfTI files)

### `NiftiImage`

class `nifti.image.``NiftiImage`(source, header=None, load=False, **kwargs)

  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

  `NiftiFormat`, `MemMappedNiftiImage`

  Parameters: |

  source: str | ndarray
    If source is a string, it is assumed to be a filename and an attempt will be made to open the corresponding NIfTI file. In case of an ndarray the array data will be used for the to be created nifti image and a matching nifti header is generated. If an object of a different type is supplied as ‘source’ a ValueError exception will be thrown.
  header: dict
    Additional header data might be supplied. However, dimensionality and datatype are determined from the ndarray and not taken from a header dictionary.
  load: Boolean
    If set to True the image data will be loaded into memory. This is only useful if loading a NIfTI image from file. This flag is almost useless, as the data will be loaded automatically whenever it is accessed.
  **kwargs:
    Additional stuff is passed to `NiftiFormat`.
  `asarray`(copy=True)

    Convert the image data into a ndarray.

    Parameters: | copy (Boolean) – If set to False the array only wraps the image data, while True will return a copy of the data array.

  `bbox`

    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))

    See also

    `nifti.image.NiftiImage.bbox`, `nifti.imgfx.crop()`

  `copy`()

    Return a copy of the image.

  `crop`(nim, bbox=None)

    Crop an image.

    Parameters: | bbox (list(2-tuples) | None) – Each tuple has the (min,max) values for a particular image dimension. If None, the images actual bounding box is used for cropping.

    See also

    `nifti.image.NiftiImage.bbox`, `nifti.imgfx.getBoundingBox()`

  `data`

    Return the NIfTI image data wrapped into a NumPy array.

    See also

    `data`

  `filename`

    Please see `nifti.format.NiftiFormat.getFilename()` for the documentation.

  `getDataArray`()

    Return the NIfTI image data wrapped into a NumPy array.

    See also

    `data`

  `getFilename`()

    Please see `nifti.format.NiftiFormat.getFilename()` for the documentation.

  `getScaledData`()

    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`()

    Load the image data into memory, if it is not already accessible.

    It is save to call this method several times successively.

  `save`(filename=None, filetype='NIFTI', update_minmax=True)

    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:

    - filename (str | None) – The name of the target file (typically including its extension). Filenames might be provided as unicode strings. However, as the underlying library does not support unicode, they must be ascii-encodable, i.e. must not contain pure unicode characters. Usually setting the filename also determines the filetype (NIfTI/ANALYZE). Please see `setFilename()` for some more details. If None, an image loaded from a file will cause the original image to be overwritten.
    - filetype (str) – Provide intented filetype. Please see the documentation of the setFilename() method for some more details.
    - update_minmax (bool) – Whether the image header’s min and max values should be updated according to the current image data.

    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.

  `setDataArray`(data)
  `setFilename`(filename, filetype='NIFTI')

    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

    `getFilename()`, `filename`

  `unload`()

    Unload image data and free allocated memory.

    This methods does nothing in case of memory mapped files.

  `updateCalMinMax`()

    Update the image data maximum and minimum value in the nifti header.

  `updateHeader`(hdrdict)

    Deprecated method only here for backward compatibility.

    Please refer to NiftiFormat.updateFromDict()

### `MemMappedNiftiImage`

class `nifti.image.``MemMappedNiftiImage`(source)

  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: | source (str | ndarray) – If source is a string, it is assumed to be a filename and an attempt will be made to open the corresponding NIfTI file. In case of an ndarray the array data will be used for the to be created nifti image and a matching nifti header is generated. If an object of a different type is supplied as ‘source’ a ValueError exception will be thrown.

  `data`

    Please see `nifti.format.NiftiImage.getDataArray()` for the documentation.

  `filename`

    Please see `nifti.format.NiftiFormat.getFilename()` for the documentation.

  `getDataArray`()

    Please see `nifti.format.NiftiImage.getDataArray()` for the documentation.

  `getFilename`()

    Please see `nifti.format.NiftiFormat.getFilename()` for the documentation.

  `load`()

    Does nothing for memory mapped images.

  `save`()

    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.

  `setFilename`(filename, filetype='NIFTI')

    Does not work for memory mapped images and therefore raises an exception.

  `unload`()

    Does nothing for memory mapped images.

## Module `extensions`

This module provides a container-like interface to NIfTI1 header extensions.

### `NiftiExtensions`

class `nifti.extensions.``NiftiExtensions`(raw_nimg, source=None)

  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: |

  raw_nimg: nifti_image struct
    This is the raw NIfTI image struct pointer. It is typically provided by `nifti.format.NiftiFormat.raw_nimg`.
  source: list(2-tuple)
    This is an optional list for extension tuples (ecode, edata). Each element of this list will be appended as a new extension.
  `append`(extension)

    Append a new extension.

    Parameters: | extension (2-tuple) – An extension is given by a (ecode, edata) tuple, where ecode can be either literal or numerical and edata is any kind of data.

    Note:
      Currently, edata can only be stuff whos len(edata) matches its size in bytes, e.g. str.
  `clear`()

    Remove all extensions.

  `count`(code)

    Returns the number of extensions matching a given ecode.

    Parameters: | code (int | str) – The ecode can be specified either literal or as numerical value.

  `ecodes`

    Returns a list of ecodes for all extensions.

  `iteritems`()

    A generator method that returns a 2-tuple (ecode, edata) on each iteration. It can be used in the same fashion as dict.iteritems().

## Useful Functions

### Utilities from `nifti.utils`

Utility functions for PyNifti

`nifti.utils.``applyFxToVolumes`(ts, vols, fx, **kwargs)

  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.

`nifti.utils.``getPeristimulusTimeseries`(ts, onsetvols, nvols=10, fx=<function mean at 0x7fbd84031e60>)

  Returns 4d array with peristimulus timeseries.

  Parameters:

  - ts – source 4d timeseries
  - onsetvols – sequence of onsetvolumes to be averaged over
  - nvols – length of the peristimulus timeseries in volumes (starting from onsetvol)
  - fx – function to be applied to the list of corresponding volumes. Typically this will be mean(), so it is default, but it could also be var() or something different. The supplied function is to be able to handle an ‘axis=0’ argument similiar to NumPy’s mean(), var(), ...

`nifti.utils.``splitFilename`(filename)

  Split a NIfTI filename into basename and extension.

  Parameters: | filename (str) – Filename to be split.
  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.

`nifti.utils.``time2vol`(t, tr, lag=0.0, decimals=0)

  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().

### Image functions in `nifti.imgfx`

Functions operating on images

`nifti.imgfx.``getBoundingBox`(nim)

  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))

  See also

  `nifti.image.NiftiImage.bbox`, `nifti.imgfx.crop()`

`nifti.imgfx.``crop`(nim, bbox=None)

  Crop an image.

  Parameters: | bbox (list(2-tuples) | None) – Each tuple has the (min,max) values for a particular image dimension. If None, the images actual bounding box is used for cropping.

  See also

  `nifti.image.NiftiImage.bbox`, `nifti.imgfx.getBoundingBox()`

### Navigation

- index
- next |
- previous |
- NIfTI Libraries |
- PyNIfTI Home |
- Documentation »