Read / write access to NIfTI1 image format
NIfTI1 format defined at http://nifti.nimh.nih.gov/nifti-1/
Nifti1Extension(code, content) | Baseclass for NIfTI1 header extensions. |
Nifti1Extensions | 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 |
load(filename) | Load NIfTI1 single or pair from filename |
save(img, filename) | Save NIfTI1 single or pair to filename |
Bases: object
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: | code : int|str
content : str
|
---|
Parameters: | code : int|str
content : str
|
---|
Return the canonical extension type code.
Return the extension content in its runtime representation.
Return the size of the extension in the NIfTI file.
Write header extensions to fileobj
Write starts at fileobj current file position.
Parameters: | fileobj : file-like object
byteswap : boolean
|
---|---|
Returns: | None : |
Bases: list
Simple extension collection, implemented as a list-subclass.
x.__init__(...) initializes x; see help(type(x)) for signature
Returns the number of extensions matching a given ecode.
Parameters: | code : int | str
|
---|
Read header extensions from a fileobj
Parameters: | fileobj : file-like object
size : int
byteswap : boolean
|
---|---|
Returns: | An extension list. This list might be empty in case not extensions : were present in fileobj. : |
Return a list of the extension code of all available extensions
Return the size of the complete header extensions in the NIfTI file.
Write header extensions to fileobj
Write starts at fileobj current file position.
Parameters: | fileobj : file-like object
byteswap : boolean
|
---|---|
Returns: | None : |
Bases: nibabel.spm99analyze.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
Initialize header from binary data block and extensions
Return copy of header
Take reference to extensions as well as copy of header contents
Create empty header binary block with given endianness
alias of Nifti1Extensions
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
check : {True, False}
|
---|---|
Returns: | hdr : header instance
|
Select best of available transforms
Get shape of data
Notes
Allows for freesurfer hack for large vectors described in https://github.com/nipy/nibabel/issues/100 and https://code.google.com/p/fieldtrip/source/browse/trunk/external/freesurfer/save_nifti.m?spec=svn5022&r=5022#77
Allows for freesurfer hack for 7th order icosahedron surface described in https://github.com/nipy/nibabel/issues/309 https://code.google.com/p/fieldtrip/source/browse/trunk/external/freesurfer/load_nifti.m?r=8776#86 https://code.google.com/p/fieldtrip/source/browse/trunk/external/freesurfer/save_nifti.m?r=8776#50
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)
Gets NIfTI MRI slice etc dimension information
Returns: | freq : {None,0,1,2}
phase : {None,0,1,2}
slice : {None,0,1,2}
where ``data array`` is the array returned by ``get_data`` : Because NIfTI1 files are natively Fortran indexed: :
``None`` means the axis appears not to be specified. : |
---|
Examples
See set_dim_info function
Get intent code, parameters and name
Parameters: | code_repr : string
|
---|---|
Returns: | code : string or integer
parameters : tuple
name : string
|
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')
Return the number of slices
Return 4x4 affine matrix from qform parameters in header
Parameters: | coded : bool, optional
|
---|---|
Returns: | affine : None or (4,4) ndarray
code : int
|
Compute quaternion from b, c, d of quaternion
Fills a value by assuming this is a unit quaternion
Return 4x4 affine matrix from sform parameters in header
Parameters: | coded : bool, optional
|
---|---|
Returns: | affine : None or (4,4) ndarray
code : int
|
Get slice duration
Returns: | slice_duration : float
|
---|
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 from slice timing information
Returns: | slice_times : tuple
|
---|
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 data scaling (slope) and DC offset (intercept) from header data
Returns: | slope : None or float
inter : None or float
|
---|
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
Traceback (most recent call last):
...
HeaderDataError: Valid slope but invalid intercept inf
Set shape of data
If ndims == len(shape) then we set zooms for dimensions higher than ndims to 1.0
Parameters: | shape : sequence
|
---|
Notes
Applies freesurfer hack for large vectors described in https://github.com/nipy/nibabel/issues/100 and https://code.google.com/p/fieldtrip/source/browse/trunk/external/freesurfer/save_nifti.m?spec=svn5022&r=5022#77
Allows for freesurfer hack for 7th order icosahedron surface described in https://github.com/nipy/nibabel/issues/309 https://code.google.com/p/fieldtrip/source/browse/trunk/external/freesurfer/load_nifti.m?r=8776#86 https://code.google.com/p/fieldtrip/source/browse/trunk/external/freesurfer/save_nifti.m?r=8776#50
Sets nifti MRI slice etc dimension information
Parameters: | freq : {None, 0, 1, 2}
phase : {None, 0, 1, 2}
slice : {None, 0, 1, 2}
``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 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: | code : integer or string
params : list, tuple of scalars
name : string
|
---|---|
Returns: | None : |
Examples
>>> hdr = Nifti1Header()
>>> hdr.set_intent(0) # unknown code
>>> 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), '')
Set qform header values from 4x4 affine
Parameters: | affine : None or 4x4 array
code : None, string or integer, optional
strip_shears : bool, optional
|
---|
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 transform from 4x4 affine
Parameters: | affine : None or 4x4 array
code : None, string or integer, optional
|
---|
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
Parameters: | duration : scalar
|
---|
Examples
See get_slice_duration
Set slice times into hdr
Parameters: | slice_times : tuple
|
---|
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 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: | slope : None or float
inter : None or float, optional
|
---|
Bases: nibabel.nifti1.Nifti1Pair
Class for single file NIfTI1 format image
alias of Nifti1Header
Harmonize header with image data and affine
Bases: nibabel.analyze.AnalyzeImage
Class for NIfTI1 format image, header pair
Return 4x4 affine matrix from qform parameters in header
Parameters: | coded : bool, optional
|
---|---|
Returns: | affine : None or (4,4) ndarray
code : int
|
Return 4x4 affine matrix from sform parameters in header
Parameters: | coded : bool, optional
|
---|---|
Returns: | affine : None or (4,4) ndarray
code : int
|
alias of Nifti1PairHeader
Set qform header values from 4x4 affine
Parameters: | affine : None or 4x4 array
code : None, string or integer
strip_shears : bool, optional
update_affine : bool, optional
|
---|
Examples
>>> data = np.arange(24).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 transform from 4x4 affine
Parameters: | affine : None or 4x4 array
code : None, string or integer
update_affine : bool, optional
|
---|
Examples
>>> data = np.arange(24).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
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
Bases: nibabel.nifti1.Nifti1Header
Class for NIfTI1 pair header
Initialize header from binary data block and extensions
Initialize header from binary data block and extensions
Load NIfTI1 single or pair from filename
Parameters: | filename : str
|
---|---|
Returns: | img : Nifti1Image or Nifti1Pair
|
Raises: | ImageFileError :
IOError :
|