Neuroimaging in Python — NiBabel 5.4.0.dev1+g3b1c7b37 documentation (original) (raw)

nifti1

Read / write access to NIfTI1 image format

NIfTI1 format defined at http://nifti.nimh.nih.gov/nifti-1/

Nifti1DicomExtension(code[, content, parent_hdr]) NIfTI1 DICOM header extension
Nifti1Extension(code[, content, object]) Baseclass for NIfTI1 header extensions.
Nifti1Extensions([iterable]) Simple extension collection, implemented as a list-subclass.
Nifti1Header([binaryblock, endianness, ...]) Class for NIfTI1 header
Nifti1Image(dataobj, affine[, header, ...]) Class for single file NIfTI1 format image
Nifti1Pair(dataobj, affine[, header, extra, ...]) Class for NIfTI1 format image, header pair
Nifti1PairHeader([binaryblock, endianness, ...]) Class for NIfTI1 pair header
NiftiExtension(code[, content, object]) Base class for NIfTI header extensions.
load(filename) Load NIfTI1 single or pair from filename
save(img, filename) Save NIfTI1 single or pair to filename

Nifti1DicomExtension

class nibabel.nifti1.Nifti1DicomExtension(code: int | str, content: bytes | Dataset | None = None, parent_hdr: Nifti1Header | None = None)

Bases: Nifti1Extension[Dataset]

NIfTI1 DICOM header extension

This class is a thin wrapper around pydicom to read a binary DICOM byte string. If pydicom is available, content is exposed as a Dicom Dataset. Otherwise, this silently falls back to the standard NiftiExtension class and content is the raw bytestring loaded directly from the nifti file header.

Parameters:

codeint or str

Canonical extension code as defined in the NIfTI standard, given either as integer or corresponding label (see extension_codes)

contentbytes or pydicom Dataset or None

Extension content - either a bytestring as read from the NIfTI file header or an existing pydicom Dataset. If a bystestring, the content is converted into a Dataset on initialization. If None, a new empty Dataset is created.

parent_hdrNifti1Header, optional

If a dicom extension belongs to an existingNifti1Header, it may be provided here to ensure that the DICOM dataset is written with correctly corresponding endianness; otherwise it is assumed the dataset is little endian.

Notes

code should always be 2 for DICOM.

__init__(code: int | str, content: bytes | Dataset | None = None, parent_hdr: Nifti1Header | None = None) → None

Parameters:

codeint or str

Canonical extension code as defined in the NIfTI standard, given either as integer or corresponding label (see extension_codes)

contentbytes or pydicom Dataset or None

Extension content - either a bytestring as read from the NIfTI file header or an existing pydicom Dataset. If a bystestring, the content is converted into a Dataset on initialization. If None, a new empty Dataset is created.

parent_hdrNifti1Header, optional

If a dicom extension belongs to an existingNifti1Header, it may be provided here to ensure that the DICOM dataset is written with correctly corresponding endianness; otherwise it is assumed the dataset is little endian.

Notes

code should always be 2 for DICOM.

code_: int_ = 2

Nifti1Extension

class nibabel.nifti1.Nifti1Extension(code: int | str, content: bytes = b'', object: T | None = None)

Bases: NiftiExtension[T]

Baseclass for NIfTI1 header extensions.

This class is sufficient to handle very simple text-based extensions, such as comment. More sophisticated extensions should/will be supported by dedicated subclasses.

Parameters:

codeint or str

Canonical extension code as defined in the NIfTI standard, given either as integer or corresponding label (see extension_codes)

contentbytes, optional

Extension content as read from the NIfTI file header.

objectoptional

Extension content in runtime form.

__init__(code: int | str, content: bytes = b'', object: T | None = None) → None

Parameters:

codeint or str

Canonical extension code as defined in the NIfTI standard, given either as integer or corresponding label (see extension_codes)

contentbytes, optional

Extension content as read from the NIfTI file header.

objectoptional

Extension content in runtime form.

code_: int_ = 0

Nifti1Extensions

class nibabel.nifti1.Nifti1Extensions(iterable=(), /)

Bases: list

Simple extension collection, implemented as a list-subclass.

__init__(*args, **kwargs)

count(ecode)

Returns the number of extensions matching a given ecode.

Parameters:

codeint | str

The ecode can be specified either literal or as numerical value.

classmethod from_fileobj(fileobj, size, byteswap)

Read header extensions from a fileobj

Parameters:

fileobjfile-like object

We begin reading the extensions at the current file position

sizeint

Number of bytes to read. If negative, fileobj will be read till its end.

byteswapboolean

Flag if byteswapping the read data is required.

Returns:

An extension list. This list might be empty in case not extensions

were present in fileobj.

get_codes()

Return a list of the extension code of all available extensions

get_sizeondisk()

Return the size of the complete header extensions in the NIfTI file.

write_to(fileobj, byteswap)

Write header extensions to fileobj

Write starts at fileobj current file position.

Parameters:

fileobjfile-like object

Should implement write method

byteswapboolean

Flag if byteswapping the data is required.

Returns:

None

Nifti1Image

class nibabel.nifti1.Nifti1Image(dataobj, affine, header=None, extra=None, file_map=None, dtype=None)

Bases: Nifti1Pair, SerializableImage

Class for single file NIfTI1 format image

Initialize image

The image is a combination of (array-like, affine matrix, header), with optional metadata in extra, and filename / file-like objects contained in the file_map mapping.

Parameters:

dataobjobject

Object containing image data. It should be some object that returns an array from np.asanyarray. It should have a shape attribute or property

affineNone or (4,4) array-like

homogeneous affine giving relationship between voxel coordinates and world coordinates. Affine can also be None. In this case,obj.affine also returns None, and the affine as written to disk will depend on the file format.

headerNone or mapping or header instance, optional

metadata for this image format

extraNone or mapping, optional

metadata to associate with image that cannot be stored in the metadata of this image type

file_mapmapping, optional

mapping giving file information for this image format

Notes

If both a header and an affine are specified, and the affine does not match the affine that is in the header, the affine will be used, but the sform_code and qform_code fields in the header will be re-initialised to their default values. This is performed on the basis that, if you are changing the affine, you are likely to be changing the space to which the affine is pointing. The set_sform() andset_qform() methods can be used to update the codes after an image has been created - see those methods, and the manual for more details.

__init__(dataobj, affine, header=None, extra=None, file_map=None, dtype=None)

Initialize image

The image is a combination of (array-like, affine matrix, header), with optional metadata in extra, and filename / file-like objects contained in the file_map mapping.

Parameters:

dataobjobject

Object containing image data. It should be some object that returns an array from np.asanyarray. It should have a shape attribute or property

affineNone or (4,4) array-like

homogeneous affine giving relationship between voxel coordinates and world coordinates. Affine can also be None. In this case,obj.affine also returns None, and the affine as written to disk will depend on the file format.

headerNone or mapping or header instance, optional

metadata for this image format

extraNone or mapping, optional

metadata to associate with image that cannot be stored in the metadata of this image type

file_mapmapping, optional

mapping giving file information for this image format

Notes

If both a header and an affine are specified, and the affine does not match the affine that is in the header, the affine will be used, but the sform_code and qform_code fields in the header will be re-initialised to their default values. This is performed on the basis that, if you are changing the affine, you are likely to be changing the space to which the affine is pointing. The set_sform() andset_qform() methods can be used to update the codes after an image has been created - see those methods, and the manual for more details.

files_types_: tuple[tuple[str, str], ...]_ = (('image', '.nii'),)

alias of Nifti1Header

Harmonize header with image data and affine

valid_exts_: tuple[str, ...]_ = ('.nii',)

Nifti1Pair

class nibabel.nifti1.Nifti1Pair(dataobj, affine, header=None, extra=None, file_map=None, dtype=None)

Bases: AnalyzeImage

Class for NIfTI1 format image, header pair

Initialize image

The image is a combination of (array-like, affine matrix, header), with optional metadata in extra, and filename / file-like objects contained in the file_map mapping.

Parameters:

dataobjobject

Object containing image data. It should be some object that returns an array from np.asanyarray. It should have a shape attribute or property

affineNone or (4,4) array-like

homogeneous affine giving relationship between voxel coordinates and world coordinates. Affine can also be None. In this case,obj.affine also returns None, and the affine as written to disk will depend on the file format.

headerNone or mapping or header instance, optional

metadata for this image format

extraNone or mapping, optional

metadata to associate with image that cannot be stored in the metadata of this image type

file_mapmapping, optional

mapping giving file information for this image format

Notes

If both a header and an affine are specified, and the affine does not match the affine that is in the header, the affine will be used, but the sform_code and qform_code fields in the header will be re-initialised to their default values. This is performed on the basis that, if you are changing the affine, you are likely to be changing the space to which the affine is pointing. The set_sform() andset_qform() methods can be used to update the codes after an image has been created - see those methods, and the manual for more details.

__init__(dataobj, affine, header=None, extra=None, file_map=None, dtype=None)

Initialize image

The image is a combination of (array-like, affine matrix, header), with optional metadata in extra, and filename / file-like objects contained in the file_map mapping.

Parameters:

dataobjobject

Object containing image data. It should be some object that returns an array from np.asanyarray. It should have a shape attribute or property

affineNone or (4,4) array-like

homogeneous affine giving relationship between voxel coordinates and world coordinates. Affine can also be None. In this case,obj.affine also returns None, and the affine as written to disk will depend on the file format.

headerNone or mapping or header instance, optional

metadata for this image format

extraNone or mapping, optional

metadata to associate with image that cannot be stored in the metadata of this image type

file_mapmapping, optional

mapping giving file information for this image format

Notes

If both a header and an affine are specified, and the affine does not match the affine that is in the header, the affine will be used, but the sform_code and qform_code fields in the header will be re-initialised to their default values. This is performed on the basis that, if you are changing the affine, you are likely to be changing the space to which the affine is pointing. The set_sform() andset_qform() methods can be used to update the codes after an image has been created - see those methods, and the manual for more details.

as_reoriented(ornt)

Apply an orientation change and return a new image

If ornt is identity transform, return the original image, unchanged

Parameters:

ornt(n,2) orientation array

orientation transform. ornt[N,1]` is flip of axis N of the array implied by `shape`, where 1 means no flip and -1 means flip. For example, if ``N==0 and ornt[0,1] == -1, and there’s an array arr of shape shape, the flip would correspond to the effect of np.flipud(arr). ornt[:,0] is the transpose that needs to be done to the implied array, as inarr.transpose(ornt[:,0])

get_data_dtype(finalize=False)

Get numpy dtype for data

If set_data_dtype() has been called with an alias and finalize is False, return the alias. If finalize is True, determine the appropriate dtype from the image data object and set the final dtype in the header before returning it.

get_qform(coded=False)

Return 4x4 affine matrix from qform parameters in header

Parameters:

codedbool, optional

If True, return {affine or None}, and qform code. If False, just return affine. {affine or None} means, return None if qform code == 0, and affine otherwise.

Returns:

affineNone or (4,4) ndarray

If coded is False, always return affine reconstructed from qform quaternion. If coded is True, return None if qform code is 0, else return the affine.

codeint

Qform code. Only returned if coded is True.

See also

set_qform

get_sform

get_sform(coded=False)

Return 4x4 affine matrix from sform parameters in header

Parameters:

codedbool, optional

If True, return {affine or None}, and sform code. If False, just return affine. {affine or None} means, return None if sform code == 0, and affine otherwise.

Returns:

affineNone or (4,4) ndarray

If coded is False, always return affine from sform fields. Ifcoded is True, return None if sform code is 0, else return the affine.

codeint

Sform code. Only returned if coded is True.

See also

set_sform

get_qform

alias of Nifti1PairHeader

rw_: bool_ = True

set_data_dtype(datatype)

Set numpy dtype for data from code, dtype, type or alias

Using int or "int" is disallowed, as these types will be interpreted as np.int64, which is almost never desired.np.int64 is permitted for those intent on making poor choices.

The following aliases are defined to allow for flexible specification:

Dynamic aliases are resolved when get_data_dtype() is called with a finalize=True flag. Until then, these aliases are not written to the header and will not persist to new images.

Examples

ints = np.arange(24, dtype='i4').reshape((2,3,4))

img = Nifti1Image(ints, np.eye(4)) img.set_data_dtype(np.uint8) img.get_data_dtype() dtype('uint8') img.set_data_dtype('mask') img.get_data_dtype() dtype('uint8') img.set_data_dtype('compat') img.get_data_dtype() 'compat' img.get_data_dtype(finalize=True) dtype('<i4') img.get_data_dtype() dtype('<i4') img.set_data_dtype('smallest') img.get_data_dtype() 'smallest' img.get_data_dtype(finalize=True) dtype('uint8') img.get_data_dtype() dtype('uint8')

Note that floating point values will not be coerced to int

floats = np.arange(24, dtype='f4').reshape((2,3,4)) img = Nifti1Image(floats, np.eye(4)) img.set_data_dtype('smallest') img.get_data_dtype(finalize=True) Traceback (most recent call last): ... ValueError: Cannot automatically cast array (of type float32) to an integer type with fewer than 64 bits. Please set_data_dtype() to an explicit data type.

arr = np.arange(1000, 1024, dtype='i4').reshape((2,3,4)) img = Nifti1Image(arr, np.eye(4)) img.set_data_dtype('smallest') img.set_data_dtype('implausible') Traceback (most recent call last): ... nibabel.spatialimages.HeaderDataError: data dtype "implausible" not recognized img.set_data_dtype('none') Traceback (most recent call last): ... nibabel.spatialimages.HeaderDataError: data dtype "none" known but not supported img.set_data_dtype(np.void) Traceback (most recent call last): ... nibabel.spatialimages.HeaderDataError: data dtype "<class 'numpy.void'>" known but not supported img.set_data_dtype('int') Traceback (most recent call last): ... ValueError: Invalid data type 'int'. Specify a sized integer, e.g., 'uint8' or numpy.int16. img.set_data_dtype(int) Traceback (most recent call last): ... ValueError: Invalid data type <class 'int'>. Specify a sized integer, e.g., 'uint8' or numpy.int16. img.set_data_dtype('int64') img.get_data_dtype() == np.dtype('int64') True

set_qform(affine, code=None, strip_shears=True, **kwargs)

Set qform header values from 4x4 affine

Parameters:

affineNone or 4x4 array

affine transform to write into sform. If None, only set code.

codeNone, string or integer

String or integer giving meaning of transform in affine. The default is None. If code is None, then:

strip_shearsbool, optional

Whether to strip shears in affine. If True, shears will be silently stripped. If False, the presence of shears will raise aHeaderDataError

update_affinebool, optional

Whether to update the image affine from the header best affine after setting the qform. Must be keyword argument (because of different position in set_qform). Default is True

See also

get_qform

set_sform

Examples

data = np.arange(24, dtype='f4').reshape((2,3,4)) aff = np.diag([2, 3, 4, 1]) img = Nifti1Pair(data, aff) img.get_qform() array([[2., 0., 0., 0.], [0., 3., 0., 0.], [0., 0., 4., 0.], [0., 0., 0., 1.]]) img.get_qform(coded=True) (None, 0) aff2 = np.diag([3, 4, 5, 1]) img.set_qform(aff2, 'talairach') qaff, code = img.get_qform(coded=True) np.all(qaff == aff2) True int(code) 3

set_sform(affine, code=None, **kwargs)

Set sform transform from 4x4 affine

Parameters:

affineNone or 4x4 array

affine transform to write into sform. If None, only set code

codeNone, string or integer

String or integer giving meaning of transform in affine. The default is None. If code is None, then:

update_affinebool, optional

Whether to update the image affine from the header best affine after setting the qform. Must be keyword argument (because of different position in set_qform). Default is True

See also

get_sform

set_qform

Examples

data = np.arange(24, dtype='f4').reshape((2,3,4)) aff = np.diag([2, 3, 4, 1]) img = Nifti1Pair(data, aff) img.get_sform() array([[2., 0., 0., 0.], [0., 3., 0., 0.], [0., 0., 4., 0.], [0., 0., 0., 1.]]) saff, code = img.get_sform(coded=True) saff array([[2., 0., 0., 0.], [0., 3., 0., 0.], [0., 0., 4., 0.], [0., 0., 0., 1.]]) int(code) 2 aff2 = np.diag([3, 4, 5, 1]) img.set_sform(aff2, 'talairach') saff, code = img.get_sform(coded=True) np.all(saff == aff2) True int(code) 3

to_file_map(file_map=None, dtype=None)

Write image to file_map or contained self.file_map

Parameters:

file_mapNone or mapping, optional

files mapping. If None (default) use object’s file_mapattribute instead

dtypedtype-like, optional

The on-disk data type to coerce the data array.

Harmonize header with image data and affine

See AnalyzeImage.update_header for more examples

Examples

data = np.zeros((2,3,4)) affine = np.diag([1.0,2.0,3.0,1.0]) img = Nifti1Image(data, affine) hdr = img.header np.all(hdr.get_qform() == affine) True np.all(hdr.get_sform() == affine) True

NiftiExtension

class nibabel.nifti1.NiftiExtension(code: int | str, content: bytes = b'', object: T | None = None)

Bases: Generic[T]

Base class for NIfTI header extensions.

This class provides access to the extension content in various forms. For simple extensions that expose data as bytes, text or JSON, this class is sufficient. More complex extensions should be implemented as subclasses that provide custom serialization/deserialization methods.

Efficiency note:

This class assumes that the runtime representation of the extension content is mutable. Once a runtime representation is set, it is cached and will be serialized on any attempt to access the extension content as bytes, including determining the size of the extension in the NIfTI file.

If the runtime representation is never accessed, the raw bytes will be used without modification. While avoiding unnecessary deserialization, if there are bytestrings that do not produce a valid runtime representation, they will be written as-is, and may cause errors downstream.

Parameters:

codeint or str

Canonical extension code as defined in the NIfTI standard, given either as integer or corresponding label (see extension_codes)

contentbytes, optional

Extension content as read from the NIfTI file header.

objectoptional

Extension content in runtime form.

__init__(code: int | str, content: bytes = b'', object: T | None = None) → None

Parameters:

codeint or str

Canonical extension code as defined in the NIfTI standard, given either as integer or corresponding label (see extension_codes)

contentbytes, optional

Extension content as read from the NIfTI file header.

objectoptional

Extension content in runtime form.

code_: int_

property content_: bytes_

Return the extension content as raw bytes.

encoding_: str | None_ = None

classmethod from_bytes(content: bytes) → Self

Create an extension from raw bytes.

This constructor may only be used in extension classes with a class attribute code to indicate the extension type.

classmethod from_object(obj: T) → Self

Create an extension from a runtime object.

This constructor may only be used in extension classes with a class attribute code to indicate the extension type.

get_code()

Return the canonical extension type code.

get_content() → T

Return the extension content in its runtime representation.

This method may return a different type for each extension type. For simple use cases, consider using .content, .text or .json()instead.

get_object() → T

Return the extension content in its runtime representation.

This method may return a different type for each extension type. For simple use cases, consider using .content, .text or .json()instead.

get_sizeondisk() → int

Return the size of the extension in the NIfTI file.

json() → Any

Attempt to decode the extension content as JSON.

If the content is not valid JSON, a JSONDecodeError or UnicodeDecodeError will be raised.

property text_: str_

Attempt to decode the extension content as text.

The encoding is determined by the encoding attribute, which may be set by the user or subclass. If not set, the default encoding is ‘utf-8’.

write_to(fileobj: BinaryIO, byteswap: bool = False) → None

Write header extensions to fileobj

Write starts at fileobj current file position.

Parameters:

fileobjfile-like object

Should implement write method

byteswapboolean

Flag if byteswapping the data is required.

Returns:

None

load

nibabel.nifti1.load(filename)

Load NIfTI1 single or pair from filename

Parameters:

filenamestr

filename of image to be loaded

Returns:

imgNifti1Image or Nifti1Pair

NIfTI1 single or pair image instance

Raises:

ImageFileError

if filename doesn’t look like NIfTI1;

OSError

if filename does not exist.

save

nibabel.nifti1.save(img, filename)

Save NIfTI1 single or pair to filename

Parameters:

filenamestr

filename to which to save image