nifti1
¶
Read / write access to NIfTI1 image format
NIfTI1 format defined at http://nifti.nimh.nih.gov/nifti-1/
|
NIfTI1 DICOM header extension |
|
Baseclass for NIfTI1 header extensions. |
|
Simple extension collection, implemented as a list-subclass. |
|
Class for NIfTI1 header |
|
Class for single file NIfTI1 format image |
|
Class for NIfTI1 format image, header pair |
|
Class for NIfTI1 pair header |
|
Base class for NIfTI header extensions. |
|
Load NIfTI1 single or pair from 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_hdr
Nifti1Header
, optional If a dicom extension belongs to an existing
Nifti1Header
, 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_hdr
Nifti1Header
, optional If a dicom extension belongs to an existing
Nifti1Header
, 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.
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.
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
Nifti1Header
¶
- class nibabel.nifti1.Nifti1Header(binaryblock=None, endianness=None, check=True, extensions=())¶
Bases:
SpmAnalyzeHeader
Class for NIfTI1 header
The NIfTI1 header has many more coded fields than the simpler Analyze variants. NIfTI1 headers also have extensions.
Nifti allows the header to be a separate file, as part of a nifti image / header pair, or to precede the data in a single file. The object needs to know which type it is, in order to manage the voxel offset pointing to the data, extension reading, and writing the correct magic string.
This class handles the header-preceding-data case.
Initialize header from binary data block and extensions
- __init__(binaryblock=None, endianness=None, check=True, extensions=())¶
Initialize header from binary data block and extensions
- copy()¶
Return copy of header
Take reference to extensions as well as copy of header contents
- classmethod default_structarr(endianness=None)¶
Create empty header binary block with given endianness
- exts_klass¶
alias of
Nifti1Extensions
- classmethod from_fileobj(fileobj, endianness=None, check=True)¶
Return read structure with given or guessed endiancode
- Parameters:
- fileobjfile-like object
Needs to implement
read
method- endiannessNone or endian code, optional
Code specifying endianness of read data
- Returns:
- wstrWrapStruct object
WrapStruct object initialized from data in fileobj
- classmethod from_header(header=None, check=True)¶
Class method to create header from another header
Extend Analyze header copy by copying extensions from other Nifti types.
- Parameters:
- header
Header
instance or mapping a header of this class, or another class of header for conversion to this type
- check{True, False}
whether to check header for integrity
- header
- Returns:
- hdrheader instance
fresh header instance of our own class
- get_best_affine()¶
Select best of available transforms
- get_data_shape()¶
Get shape of data
Notes
Applies freesurfer hack for large vectors described in issue 100 and save_nifti.m.
Allows for freesurfer hack for 7th order icosahedron surface described in issue 309, load_nifti.m, and save_nifti.m.
Examples
>>> hdr = Nifti1Header() >>> hdr.get_data_shape() (0,) >>> hdr.set_data_shape((1,2,3)) >>> hdr.get_data_shape() (1, 2, 3)
Expanding number of dimensions gets default zooms
>>> hdr.get_zooms() (1.0, 1.0, 1.0)
- get_dim_info()¶
Gets NIfTI MRI slice etc dimension information
- Returns:
- freq{None,0,1,2}
Which data array axis is frequency encode direction
- phase{None,0,1,2}
Which data array axis is phase encode direction
- slice{None,0,1,2}
Which data array axis is slice encode direction
- where
data array
is the array returned byget_data
- Because NIfTI1 files are natively Fortran indexed:
0 is fastest changing in file 1 is medium changing in file 2 is slowest changing in file
None
means the axis appears not to be specified.
Examples
See set_dim_info function
- get_intent(code_repr='label')¶
Get intent code, parameters and name
- Parameters:
- code_reprstring
string giving output form of intent code representation. Default is ‘label’; use ‘code’ for integer representation.
- Returns:
- codestring or integer
intent code, or string describing code
- parameterstuple
parameters for the intent
- namestring
intent name
Examples
>>> hdr = Nifti1Header() >>> hdr.set_intent('t test', (10,), name='some score') >>> hdr.get_intent() ('t test', (10.0,), 'some score') >>> hdr.get_intent('code') (3, (10.0,), 'some score')
- get_n_slices()¶
Return the number of slices
- 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.
- get_qform_quaternion()¶
Compute quaternion from b, c, d of quaternion
Fills a value by assuming this is a unit quaternion
- 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. If coded is True, return None if sform code is 0, else return the affine.
- codeint
Sform code. Only returned if coded is True.
- get_slice_duration()¶
Get slice duration
- Returns:
- slice_durationfloat
time to acquire one slice
Notes
The NIfTI1 spec appears to require the slice dimension to be defined for slice_duration to have meaning.
Examples
>>> hdr = Nifti1Header() >>> hdr.set_dim_info(slice=2) >>> hdr.set_slice_duration(0.3) >>> print("%0.1f" % hdr.get_slice_duration()) 0.3
- get_slice_times()¶
Get slice times from slice timing information
- Returns:
- slice_timestuple
Times of acquisition of slices, where 0 is the beginning of the acquisition, ordered by position in file. nifti allows slices at the top and bottom of the volume to be excluded from the standard slice timing specification, and calls these “padding slices”. We give padding slices
None
as a time of acquisition
Examples
>>> hdr = Nifti1Header() >>> hdr.set_dim_info(slice=2) >>> hdr.set_data_shape((1, 1, 7)) >>> hdr.set_slice_duration(0.1) >>> hdr['slice_code'] = slice_order_codes['sequential increasing'] >>> slice_times = hdr.get_slice_times() >>> np.allclose(slice_times, [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6]) True
- get_slope_inter()¶
Get data scaling (slope) and DC offset (intercept) from header data
- Returns:
- slopeNone or float
scaling (slope). None if there is no valid scaling from these fields
- interNone or float
offset (intercept). None if there is no valid scaling or if offset is not finite.
Examples
>>> hdr = Nifti1Header() >>> hdr.get_slope_inter() (1.0, 0.0) >>> hdr['scl_slope'] = 0 >>> hdr.get_slope_inter() (None, None) >>> hdr['scl_slope'] = np.nan >>> hdr.get_slope_inter() (None, None) >>> hdr['scl_slope'] = 1 >>> hdr['scl_inter'] = 1 >>> hdr.get_slope_inter() (1.0, 1.0) >>> hdr['scl_inter'] = np.inf >>> hdr.get_slope_inter() Traceback (most recent call last): ... HeaderDataError: Valid slope but invalid intercept inf
- get_xyzt_units()¶
- has_data_intercept = True¶
- has_data_slope = True¶
- is_single = True¶
- classmethod may_contain_header(binaryblock)¶
- pair_magic = b'ni1'¶
- pair_vox_offset = 0¶
- quaternion_threshold = 3.5762787e-07¶
- set_data_dtype(datatype)¶
Set numpy dtype for data from code or dtype or type
Using
int
or"int"
is disallowed, as these types will be interpreted asnp.int64
, which is almost never desired.np.int64
is permitted for those intent on making poor choices.Examples
>>> hdr = Nifti1Header() >>> hdr.set_data_dtype(np.uint8) >>> hdr.get_data_dtype() dtype('uint8') >>> hdr.set_data_dtype(np.dtype(np.uint8)) >>> hdr.get_data_dtype() dtype('uint8') >>> hdr.set_data_dtype('implausible') Traceback (most recent call last): ... nibabel.spatialimages.HeaderDataError: data dtype "implausible" not recognized >>> hdr.set_data_dtype('none') Traceback (most recent call last): ... nibabel.spatialimages.HeaderDataError: data dtype "none" known but not supported >>> hdr.set_data_dtype(np.void) Traceback (most recent call last): ... nibabel.spatialimages.HeaderDataError: data dtype "<class 'numpy.void'>" known but not supported >>> hdr.set_data_dtype('int') Traceback (most recent call last): ... ValueError: Invalid data type 'int'. Specify a sized integer, e.g., 'uint8' or numpy.int16. >>> hdr.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. >>> hdr.set_data_dtype('int64') >>> hdr.get_data_dtype() == np.dtype('int64') True
- set_data_shape(shape)¶
Set shape of data # noqa
If
ndims == len(shape)
then we set zooms for dimensions higher thanndims
to 1.0Nifti1 images can have up to seven dimensions. For FreeSurfer-variant Nifti surface files, the first dimension is assumed to correspond to vertices/nodes on a surface, and dimensions two and three are constrained to have depth of 1. Dimensions 4-7 are constrained only by type bounds.
- Parameters:
- shapesequence
sequence of integers specifying data array shape
Notes
Applies freesurfer hack for large vectors described in issue 100 and save_nifti.m.
Allows for freesurfer hack for 7th order icosahedron surface described in issue 309, load_nifti.m, and save_nifti.m.
The Nifti1 standard header allows for the following “point set” definition of a surface, not currently implemented in nibabel.
To signify that the vector value at each voxel is really a spatial coordinate (e.g., the vertices or nodes of a surface mesh): - dataset must have a 5th dimension - intent_code must be NIFTI_INTENT_POINTSET - dim[0] = 5 - dim[1] = number of points - dim[2] = dim[3] = dim[4] = 1 - dim[5] must be the dimensionality of space (e.g., 3 => 3D space). - intent_name may describe the object these points come from (e.g., "pial", "gray/white" , "EEG", "MEG").
- set_dim_info(freq=None, phase=None, slice=None)¶
Sets nifti MRI slice etc dimension information
- Parameters:
- freq{None, 0, 1, 2}
axis of data array referring to frequency encoding
- phase{None, 0, 1, 2}
axis of data array referring to phase encoding
- slice{None, 0, 1, 2}
axis of data array referring to slice encoding
- ``None`` means the axis is not specified.
Notes
This is stored in one byte in the header
Examples
>>> hdr = Nifti1Header() >>> hdr.set_dim_info(1, 2, 0) >>> hdr.get_dim_info() (1, 2, 0) >>> hdr.set_dim_info(freq=1, phase=2, slice=0) >>> hdr.get_dim_info() (1, 2, 0) >>> hdr.set_dim_info() >>> hdr.get_dim_info() (None, None, None) >>> hdr.set_dim_info(freq=1, phase=None, slice=0) >>> hdr.get_dim_info() (1, None, 0)
- set_intent(code, params=(), name='', allow_unknown=False)¶
Set the intent code, parameters and name
If parameters are not specified, assumed to be all zero. Each intent code has a set number of parameters associated. If you specify any parameters, then it will need to be the correct number (e.g the “f test” intent requires 2). However, parameters can also be set in the file data, so we also allow not setting any parameters (empty parameter tuple).
- Parameters:
- codeinteger or string
code specifying nifti intent
- paramslist, tuple of scalars
parameters relating to intent (see intent_codes) defaults to (). Unspecified parameters are set to 0.0
- namestring
intent name (description). Defaults to ‘’
- allow_unknown{False, True}, optional
Allow unknown integer intent codes. If False (the default), a KeyError is raised on attempts to set the intent to an unknown code.
- Returns:
- None
Examples
>>> hdr = Nifti1Header() >>> hdr.set_intent(0) # no intent >>> hdr.set_intent('z score') >>> hdr.get_intent() ('z score', (), '') >>> hdr.get_intent('code') (5, (), '') >>> hdr.set_intent('t test', (10,), name='some score') >>> hdr.get_intent() ('t test', (10.0,), 'some score') >>> hdr.set_intent('f test', (2, 10), name='another score') >>> hdr.get_intent() ('f test', (2.0, 10.0), 'another score') >>> hdr.set_intent('f test') >>> hdr.get_intent() ('f test', (0.0, 0.0), '') >>> hdr.set_intent(9999, allow_unknown=True) # unknown code >>> hdr.get_intent() ('unknown code 9999', (), '')
- set_qform(affine, code=None, strip_shears=True)¶
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, optional
String or integer giving meaning of transform in affine. The default is None. If code is None, then:
If affine is None, code-> 0
If affine not None and existing qform code in header == 0, code-> 2 (aligned)
If affine not None and existing qform code in header != 0, code-> existing qform code in header
- strip_shearsbool, optional
Whether to strip shears in affine. If True, shears will be silently stripped. If False, the presence of shears will raise a
HeaderDataError
Notes
The qform transform only encodes translations, rotations and zooms. If there are shear components to the affine transform, and strip_shears is True (the default), the written qform gives the closest approximation where the rotation matrix is orthogonal. This is to allow quaternion representation. The orthogonal representation enforces orthogonal axes.
Examples
>>> hdr = Nifti1Header() >>> int(hdr['qform_code']) # gives 0 - unknown 0 >>> affine = np.diag([1,2,3,1]) >>> np.all(hdr.get_qform() == affine) False >>> hdr.set_qform(affine) >>> np.all(hdr.get_qform() == affine) True >>> int(hdr['qform_code']) # gives 2 - aligned 2 >>> hdr.set_qform(affine, code='talairach') >>> int(hdr['qform_code']) 3 >>> hdr.set_qform(affine, code=None) >>> int(hdr['qform_code']) 3 >>> hdr.set_qform(affine, code='scanner') >>> int(hdr['qform_code']) 1 >>> hdr.set_qform(None) >>> int(hdr['qform_code']) 0
- set_sform(affine, code=None)¶
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, optional
String or integer giving meaning of transform in affine. The default is None. If code is None, then:
If affine is None, code-> 0
If affine not None and existing sform code in header == 0, code-> 2 (aligned)
If affine not None and existing sform code in header != 0, code-> existing sform code in header
Examples
>>> hdr = Nifti1Header() >>> int(hdr['sform_code']) # gives 0 - unknown 0 >>> affine = np.diag([1,2,3,1]) >>> np.all(hdr.get_sform() == affine) False >>> hdr.set_sform(affine) >>> np.all(hdr.get_sform() == affine) True >>> int(hdr['sform_code']) # gives 2 - aligned 2 >>> hdr.set_sform(affine, code='talairach') >>> int(hdr['sform_code']) 3 >>> hdr.set_sform(affine, code=None) >>> int(hdr['sform_code']) 3 >>> hdr.set_sform(affine, code='scanner') >>> int(hdr['sform_code']) 1 >>> hdr.set_sform(None) >>> int(hdr['sform_code']) 0
- set_slice_duration(duration)¶
Set slice duration
- Parameters:
- durationscalar
time to acquire one slice
Examples
See
get_slice_duration
- set_slice_times(slice_times)¶
Set slice times into hdr
- Parameters:
- slice_timestuple
tuple of slice times, one value per slice tuple can include None to indicate no slice time for that slice
Examples
>>> hdr = Nifti1Header() >>> hdr.set_dim_info(slice=2) >>> hdr.set_data_shape([1, 1, 7]) >>> hdr.set_slice_duration(0.1) >>> times = [None, 0.2, 0.4, 0.1, 0.3, 0.0, None] >>> hdr.set_slice_times(times) >>> hdr.get_value_label('slice_code') 'alternating decreasing' >>> int(hdr['slice_start']) 1 >>> int(hdr['slice_end']) 5
- set_slope_inter(slope, inter=None)¶
Set slope and / or intercept into header
Set slope and intercept for image data, such that, if the image data is
arr
, then the scaled image data will be(arr * slope) + inter
(slope, inter) of (NaN, NaN) is a signal to a containing image to set slope, inter automatically on write.
- Parameters:
- slopeNone or float
If None, implies slope of NaN. If slope is None or NaN then inter should be None or NaN. Values of 0, Inf or -Inf raise HeaderDataError
- interNone or float, optional
Intercept. If None, implies inter of NaN. If slope is None or NaN then inter should be None or NaN. Values of Inf or -Inf raise HeaderDataError
- set_xyzt_units(xyz=None, t=None)¶
- single_magic = b'n+1'¶
- single_vox_offset = 352¶
- template_dtype = dtype([('sizeof_hdr', '<i4'), ('data_type', 'S10'), ('db_name', 'S18'), ('extents', '<i4'), ('session_error', '<i2'), ('regular', 'S1'), ('dim_info', 'u1'), ('dim', '<i2', (8,)), ('intent_p1', '<f4'), ('intent_p2', '<f4'), ('intent_p3', '<f4'), ('intent_code', '<i2'), ('datatype', '<i2'), ('bitpix', '<i2'), ('slice_start', '<i2'), ('pixdim', '<f4', (8,)), ('vox_offset', '<f4'), ('scl_slope', '<f4'), ('scl_inter', '<f4'), ('slice_end', '<i2'), ('slice_code', 'u1'), ('xyzt_units', 'u1'), ('cal_max', '<f4'), ('cal_min', '<f4'), ('slice_duration', '<f4'), ('toffset', '<f4'), ('glmax', '<i4'), ('glmin', '<i4'), ('descrip', 'S80'), ('aux_file', 'S24'), ('qform_code', '<i2'), ('sform_code', '<i2'), ('quatern_b', '<f4'), ('quatern_c', '<f4'), ('quatern_d', '<f4'), ('qoffset_x', '<f4'), ('qoffset_y', '<f4'), ('qoffset_z', '<f4'), ('srow_x', '<f4', (4,)), ('srow_y', '<f4', (4,)), ('srow_z', '<f4', (4,)), ('intent_name', 'S16'), ('magic', 'S4')])¶
- write_to(fileobj)¶
Write structure to fileobj
Write starts at fileobj current file position.
- Parameters:
- fileobjfile-like object
Should implement
write
method
- Returns:
- None
Examples
>>> wstr = WrapStruct() >>> from io import BytesIO >>> str_io = BytesIO() >>> wstr.write_to(str_io) >>> wstr.binaryblock == str_io.getvalue() True
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 ashape
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
andqform_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. Theset_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 ashape
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
andqform_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. Theset_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.
- header_class¶
alias of
Nifti1Header
- update_header()¶
Harmonize header with image data and affine
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 ashape
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
andqform_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. Theset_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 ashape
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
andqform_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. Theset_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
andornt[0,1] == -1
, and there’s an arrayarr
of shape shape, the flip would correspond to the effect ofnp.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 andfinalize
isFalse
, return the alias. Iffinalize
isTrue
, 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.
- 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. If coded is True, return None if sform code is 0, else return the affine.
- codeint
Sform code. Only returned if coded is True.
- header_class¶
alias of
Nifti1PairHeader
- 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 asnp.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:
'mask'
- Alias foruint8
'compat'
- The nearest Analyze-compatible datatype (uint8
,int16
,int32
,float32
)'smallest'
- The smallest Analyze-compatible integer (uint8
,int16
,int32
)
Dynamic aliases are resolved when
get_data_dtype()
is called with afinalize=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:
If affine is None, code-> 0
If affine not None and existing qform code in header == 0, code-> 2 (aligned)
If affine not None and existing qform code in header != 0, code-> existing qform code in header
- strip_shearsbool, optional
Whether to strip shears in affine. If True, shears will be silently stripped. If False, the presence of shears will raise a
HeaderDataError
- 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
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:
If affine is None, code-> 0
If affine not None and existing sform code in header == 0, code-> 2 (aligned)
If affine not None and existing sform code in header != 0, code-> existing sform code in header
- 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
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_map
attribute instead- dtypedtype-like, optional
The on-disk data type to coerce the data array.
- update_header()¶
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
Nifti1PairHeader
¶
- class nibabel.nifti1.Nifti1PairHeader(binaryblock=None, endianness=None, check=True, extensions=())¶
Bases:
Nifti1Header
Class for NIfTI1 pair header
Initialize header from binary data block and extensions
- __init__(binaryblock=None, endianness=None, check=True, extensions=())¶
Initialize header from binary data block and extensions
- is_single = False¶
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.
- 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.
- json() Any ¶
Attempt to decode the extension content as JSON.
If the content is not valid JSON, a JSONDecodeError or UnicodeDecodeError will be raised.
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