Inheritance diagram for nipy.io.imageformats.nifti1:
Header reading / writing functions for nifti1 image format
Author: Matthew Brett
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.
Methods
get_code | |
get_content | |
get_sizeondisk | |
write_to |
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
|
---|---|
Returns : | None : |
Bases: list
Simple extension collection, implemented as a list-subclass.
Methods
append | |
count | |
extend | |
from_fileobj | |
get_codes | |
get_sizeondisk | |
index | |
insert | |
pop | |
remove | |
reverse | |
sort | |
write_to |
x.__init__(...) initializes x; see help(type(x)) for signature
L.append(object) – append object to end
Returns the number of extensions matching a given ecode.
L.extend(iterable) – extend list by appending elements from the iterable
Read header extensions from a fileobj
Parameters : | fileobj : file-like object
size : int
|
---|---|
Returns : | An extension list. This list might be empty in case not extensions :
|
Return a list of the extension code of all available extensions
Return the size of the complete header extensions in the NIfTI file.
L.index(value, [start, [stop]]) -> integer – return first index of value. Raises ValueError if the value is not present.
L.insert(index, object) – insert object before index
L.pop([index]) -> item – remove and return item at index (default last). Raises IndexError if list is empty or index is out of range.
L.remove(value) – remove first occurrence of value. Raises ValueError if the value is not present.
L.reverse() – reverse IN PLACE
L.sort(cmp=None, key=None, reverse=False) – stable sort IN PLACE; cmp(x, y) -> -1, 0, 1
Write header extensions to fileobj
Write starts at fileobj current file position.
Parameters : | fileobj : file-like object
|
---|---|
Returns : | None : |
Bases: nipy.io.imageformats.spm99analyze.SpmAnalyzeHeader
Class for NIFTI1 header
Methods
Initialize header from binary data block
Parameters : | binaryblock : {None, string} optional
endianness : {None, ‘<’,’>’, other endian code} string, optional
check : bool, optional
|
---|
Examples
>>> hdr1 = AnalyzeHeader() # an empty header
>>> hdr1.endianness == native_code
True
>>> hdr1.get_data_shape()
(0,)
>>> hdr1.set_data_shape((1,2,3)) # now with some content
>>> hdr1.get_data_shape()
(1, 2, 3)
We can set the binary block directly via this initialization. Here we get it from the header we have just made
>>> binblock2 = hdr1.binaryblock
>>> hdr2 = AnalyzeHeader(binblock2)
>>> hdr2.get_data_shape()
(1, 2, 3)
Empty headers are native endian by default
>>> hdr2.endianness == native_code
True
You can pass valid opposite endian headers with the endianness parameter. Even empty headers can have endianness
>>> hdr3 = AnalyzeHeader(endianness=swapped_code)
>>> hdr3.endianness == swapped_code
True
If you do not pass an endianness, and you pass some data, we will try to guess from the passed data.
>>> binblock3 = hdr3.binaryblock
>>> hdr4 = AnalyzeHeader(binblock3)
>>> hdr4.endianness == swapped_code
True
return new byteswapped header object with given endianness
Guaranteed to make a copy even if endianness is the same as the current endianness.
Parameters : | endianness : None or string, optional
|
---|---|
Returns : | hdr : header object
|
Examples
>>> hdr = AnalyzeHeader()
>>> hdr.endianness == native_code
True
>>> bs_hdr = hdr.as_byteswapped()
>>> bs_hdr.endianness == swapped_code
True
>>> bs_hdr = hdr.as_byteswapped(swapped_code)
>>> bs_hdr.endianness == swapped_code
True
>>> bs_hdr is hdr
False
>>> bs_hdr == hdr
True
If you write to the resulting byteswapped data, it does not change the original.
>>> bs_hdr['dim'][1] = 2
>>> bs_hdr == hdr
False
If you swap to the same endianness, it returns a copy
>>> nbs_hdr = hdr.as_byteswapped(native_code)
>>> nbs_hdr.endianness == native_code
True
>>> nbs_hdr is hdr
False
binary block of data as string
Returns : | binaryblock : string
|
---|
Examples
>>> # Make default empty header
>>> hdr = AnalyzeHeader()
>>> len(hdr.binaryblock)
348
Check header data with checks
Return copy of header
>>> hdr = AnalyzeHeader()
>>> hdr['dim'][0]
0
>>> hdr['dim'][0] = 2
>>> hdr2 = hdr.copy()
>>> hdr2 is hdr
False
>>> hdr['dim'][0] = 3
>>> hdr2['dim'][0]
2
Run checks over header binary data, return string
endian code of binary data
The endianness code gives the current byte order interpretation of the binary data.
Notes
Endianness gives endian interpretation of binary data. It is read only because the only common use case is to set the endianness on initialization, or occasionally byteswapping the data - but this is done via the as_byteswapped method
Examples
>>> hdr = AnalyzeHeader()
>>> code = hdr.endianness
>>> code == native_code
True
Adapt header to separate or same image and header file
Parameters : | is_pair : bool, optional
|
---|---|
Returns : | hdr : Nifti1Header
|
Examples
The header starts off as being for a single file
>>> hdr = Nifti1Header()
>>> str(hdr['magic'])
'n+1'
>>> hdr.get_data_offset()
352
But we can switch it to be for two files (a pair)
>>> pair_hdr = hdr.for_file_pair()
>>> str(pair_hdr['magic'])
'ni1'
>>> pair_hdr.get_data_offset()
0
The original header is not affected (a copy is returned)
>>> hdr.get_data_offset()
352
Back to single again
>>> unpair_hdr = pair_hdr.for_file_pair(False)
>>> str(unpair_hdr['magic'])
'n+1'
>>> unpair_hdr.get_data_offset()
352
Return read header with given or guessed endiancode
Parameters : | fileobj : file-like object
endianness : None or endian code, optional
|
---|---|
Returns : | hdr : AnalyzeHeader object
|
Examples
>>> import StringIO
>>> hdr = AnalyzeHeader()
>>> fileobj = StringIO.StringIO(hdr.binaryblock)
>>> fileobj.seek(0)
>>> hdr2 = AnalyzeHeader.from_fileobj(fileobj)
>>> hdr2.binaryblock == hdr.binaryblock
True
You can write to the resulting object data
>>> hdr2['dim'][1] = 1
Initialize header from mapping
Return axis names based on dim_info specification.
The keys of the axis are in [‘frequency’, ‘phase’ ‘slice’] and its values are integers.
>>> from nipy.testing import funcfile
>>> import nipy.io.imageformats as formats
>>> img = formats.load(funcfile)
>>> hdr = img.get_header()
>>> hdr.get_axis_renames()
{}
>>> hdr.set_dim_info_from_names(('frequency', 'i', 'slice'))
>>> hdr.get_axis_renames()
{'frequency': 0, 'slice': 2}
>>>
Get affine from basic (shared) header fields
Note that we get the translations from the center of the image.
Examples
>>> hdr = AnalyzeHeader()
>>> hdr.set_data_shape((3, 5, 7))
>>> hdr.set_zooms((3, 2, 1))
>>> hdr.default_x_flip
True
>>> hdr.get_base_affine() # from center of image
array([[-3., 0., 0., 3.],
[ 0., 2., 0., -4.],
[ 0., 0., 1., -3.],
[ 0., 0., 0., 1.]])
>>> hdr.set_data_shape((3, 5))
>>> hdr.get_base_affine()
array([[-3., 0., 0., 3.],
[ 0., 2., 0., -4.],
[ 0., 0., 1., -0.],
[ 0., 0., 0., 1.]])
>>> hdr.set_data_shape((3, 5, 7))
>>> hdr.get_base_affine() # from center of image
array([[-3., 0., 0., 3.],
[ 0., 2., 0., -4.],
[ 0., 0., 1., -3.],
[ 0., 0., 0., 1.]])
Select best of available transforms
Get numpy dtype for data
For examples see set_data_dtype
Return offset into data file to read data
Examples
>>> hdr = AnalyzeHeader()
>>> hdr.get_data_offset()
0
>>> hdr['vox_offset'] = 12
>>> hdr.get_data_offset()
12
Get shape of data
Examples
>>> hdr = AnalyzeHeader()
>>> 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)
Return representation of datatype code
This method returns the datatype code, or a string label for the code. Usually you are more interested in the data dtype. To do that more useful thing, use get_data_dtype
Parameters : | code_repr : string
|
---|---|
Returns : | datatype_code : string or integer
|
Examples
>>> hdr = AnalyzeHeader()
>>> hdr['datatype'] = 4 # int16
>>> hdr.get_datatype()
'int16'
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 representation of intent code
Parameters : | code_repr : string
|
---|---|
Returns : | intent_code : string or integer
|
Examples
>>> hdr = Nifti1Header()
>>> hdr.set_intent('t test', (10,), name='some score')
>>> hdr.get_intent_code()
't test'
Return 4x4 affine matrix from qform parameters in header
Return representation of qform code
Parameters : | code_repr : string
|
---|---|
Returns : | qform_code : string or integer
|
Examples
>>> hdr = Nifti1Header()
>>> hdr['qform_code'] = 3
>>> hdr.get_qform_code()
'talairach'
Compute quaternion from b, c, d of quaternion
Fills a value by assuming this is a unit quaternion
Return sform 4x4 affine matrix from header
Return representation of sform code
Parameters : | code_repr : string
|
---|---|
Returns : | sform_code : string or integer
|
Examples
>>> hdr = Nifti1Header()
>>> hdr['sform_code'] = 3
>>> hdr.get_sform_code()
'talairach'
Return representation of slice order code
Parameters : | code_repr : string
|
---|---|
Returns : | slice_code : string or integer
|
Examples
>>> hdr = Nifti1Header()
>>> hdr['slice_code'] = 4 # alternating decreasing
>>> hdr.get_slice_code()
'alternating decreasing'
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)
We need a function to print out the Nones and floating point values in a predictable way, for the tests below.
>>> _stringer = lambda val: val is not None and '%2.1f' % val or None
>>> _print_me = lambda s: map(_stringer, s)
The following examples are from the nifti1.h documentation.
>>> hdr['slice_code'] = slice_order_codes['sequential increasing']
>>> _print_me(hdr.get_slice_times())
['0.0', '0.1', '0.2', '0.3', '0.4', '0.5', '0.6']
>>> hdr['slice_start'] = 1
>>> hdr['slice_end'] = 5
>>> _print_me(hdr.get_slice_times())
[None, '0.0', '0.1', '0.2', '0.3', '0.4', None]
>>> hdr['slice_code'] = slice_order_codes['sequential decreasing']
>>> _print_me(hdr.get_slice_times())
[None, '0.4', '0.3', '0.2', '0.1', '0.0', None]
>>> hdr['slice_code'] = slice_order_codes['alternating increasing']
>>> _print_me(hdr.get_slice_times())
[None, '0.0', '0.3', '0.1', '0.4', '0.2', None]
>>> hdr['slice_code'] = slice_order_codes['alternating decreasing']
>>> _print_me(hdr.get_slice_times())
[None, '0.2', '0.4', '0.1', '0.3', '0.0', None]
>>> hdr['slice_code'] = slice_order_codes['alternating increasing 2']
>>> _print_me(hdr.get_slice_times())
[None, '0.2', '0.0', '0.3', '0.1', '0.4', None]
>>> hdr['slice_code'] = slice_order_codes['alternating decreasing 2']
>>> _print_me(hdr.get_slice_times())
[None, '0.4', '0.1', '0.3', '0.0', '0.2', None]
Get data scaling (slope) and DC offset (intercept) from header data
Parameters : | self : header object
|
---|---|
Returns : | slope : None or float
inter : None or float
|
Examples
>>> fields = {'scl_slope':1,'scl_inter':0}
>>> 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()
(1.0, 0.0)
Get zooms from header
Returns : | z : tuple
|
---|
Examples
>>> hdr = AnalyzeHeader()
>>> hdr.get_zooms()
()
>>> hdr.set_data_shape((1,2))
>>> hdr.get_zooms()
(1.0, 1.0)
>>> hdr.set_zooms((3, 4))
>>> hdr.get_zooms()
(3.0, 4.0)
Return items from header data
Return keys from header data
Set numpy dtype for data from code or dtype or type
Examples
>>> hdr = AnalyzeHeader()
>>> 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):
...
HeaderDataError: data dtype "implausible" not recognized
>>> hdr.set_data_dtype('none')
Traceback (most recent call last):
...
HeaderDataError: data dtype "none" known but not supported
>>> hdr.set_data_dtype(np.void)
Traceback (most recent call last):
...
HeaderDataError: data dtype "<type 'numpy.void'>" known but not supported
Set shape of data
Sets nifti MRI slice etc dimension information
Parameters : | hdr : nifti1 header 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)
Sets nifti dim_info from the names of the first three axes.
Parameters : | axisnames = [str] :
|
---|---|
Returns : | None : |
Examples
>>> from nipy.testing import funcfile
>>> import nipy.io.imageformats as formats
>>> img = formats.load(funcfile)
>>> hdr = img.get_header()
>>> hdr.get_dim_info()
(None, None, None)
>>> hdr.set_dim_info_from_names(('frequency', 'i', 'slice'))
>>> hdr.get_dim_info()
(0, None, 2)
>>>
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 : | hdr : nifti1 header affine : 4x4 array
code : None, string or integer
|
---|
Notes
The qform transform only encodes translations, rotations and zooms. If there are shear components to the affine transform, 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 1 - scanner
1
>>> 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
Set sform transform from 4x4 affine
Parameters : | hdr : nifti1 header affine : 4x4 array
code : None, string or integer
|
---|
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 1 - scanner
1
>>> 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
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_slice_code()
'alternating decreasing'
>>> int(hdr['slice_start'])
1
>>> int(hdr['slice_end'])
5
Set zooms into header fields
See docstring for get_zooms for examples
header data, with data fields
Examples
>>> hdr1 = AnalyzeHeader() # an empty header
>>> sz = hdr1.structarr['sizeof_hdr']
>>> hdr1.structarr = None
Traceback (most recent call last):
...
AttributeError: can't set attribute
Return values from header data
Write header to fileobj
Write starts at fileobj current file position.
Parameters : | fileobj : file-like object
|
---|---|
Returns : | None : |
Examples
>>> hdr = AnalyzeHeader()
>>> import StringIO
>>> str_io = StringIO.StringIO()
>>> hdr.write_to(str_io)
>>> hdr.binaryblock == str_io.getvalue()
True
Bases: nipy.io.imageformats.analyze.AnalyzeImage
Create new instance of own class from img
This is a class method
Parameters : | img : spatialimage instance
|
---|---|
Returns : | cimg : spatialimage instance
|
Lazy load of data
Return header
Update header to match data, affine etc in object
Return image data without image scaling applied
Summary: please use the get_data method instead of this method unless you are sure what you are doing, and that you will only be using image formats for which this method exists and returns sensible results.
Use this method with care; the modified Analyze-type formats such as SPM formats, and nifti1, specify that the image data array, as they are expecting to return it, is given by the raw data on disk, multiplied by a scalefactor and maybe with the addition of a constant. This method returns the data on the disk, without these format-specific scalings applied. Please use this method only if you absolutely need the unscaled data, and the magnitude of the data, as given by the scalefactor, is not relevant to your application. The Analyze-type formats have a single scalefactor +/- offset per image on disk. If you do not care about the absolute values, and will be removing the mean from the data, then the unscaled values will have preserved intensity ratios compared to the mean-centered scaled data. However, this is not necessarily true of other formats with more complicated scaling - such as MINC.
Note that - unlike the scaled get_data method, we do not cache the array, to minimize the memory taken by the object.
Save img in our own format, to name implied by filename
This is a class method
Parameters : | img : spatialimage instance
filename : str
|
---|
Write image to files implied by filename string
Returns : | None : |
---|
Write image to files passed, or self._files