NIPY logo

Site Navigation

NIPY Community

Table Of Contents

Previous topic

io.imageformats.minc

This Page

io.imageformats.nifti1

Module: io.imageformats.nifti1

Inheritance diagram for nipy.io.imageformats.nifti1:

Header reading / writing functions for nifti1 image format

Author: Matthew Brett

Classes

Nifti1Extension

class nipy.io.imageformats.nifti1.Nifti1Extension(code, content)

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
__init__(code, content)
Parameters :

code : int|str

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

content : str

Extension content as read from the NIfTI file header. This content is converted into a runtime representation.

get_code()

Return the canonical extension type code.

get_content()

Return the extension content in its runtime representation.

get_sizeondisk()

Return the size of the extension in the NIfTI file.

write_to(fileobj)

Write header extensions to fileobj

Write starts at fileobj current file position.

Parameters :

fileobj : file-like object

Should implement write method

Returns :

None :

Nifti1Extensions

class nipy.io.imageformats.nifti1.Nifti1Extensions

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

x.__init__(...) initializes x; see help(type(x)) for signature

append

L.append(object) – append object to end

count(ecode)

Returns the number of extensions matching a given ecode.

extend

L.extend(iterable) – extend list by appending elements from the iterable

classmethod from_fileobj(klass, fileobj, size)

Read header extensions from a fileobj

Parameters :

fileobj : file-like object

It is assumed to be positions right after the NIfTI magic field.

size : int

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

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.

index

L.index(value, [start, [stop]]) -> integer – return first index of value. Raises ValueError if the value is not present.

insert

L.insert(index, object) – insert object before index

pop

L.pop([index]) -> item – remove and return item at index (default last). Raises IndexError if list is empty or index is out of range.

remove

L.remove(value) – remove first occurrence of value. Raises ValueError if the value is not present.

reverse

L.reverse() – reverse IN PLACE

sort

L.sort(cmp=None, key=None, reverse=False) – stable sort IN PLACE; cmp(x, y) -> -1, 0, 1

write_to(fileobj)

Write header extensions to fileobj

Write starts at fileobj current file position.

Parameters :

fileobj : file-like object

Should implement write method

Returns :

None :

Nifti1Header

class nipy.io.imageformats.nifti1.Nifti1Header(binaryblock=None, endianness=None, check=True)

Bases: nipy.io.imageformats.spm99analyze.SpmAnalyzeHeader

Class for NIFTI1 header

Methods

as_byteswapped
check_fix
copy Generic (shallow and deep) copying operations.
diagnose_binaryblock
for_file_pair
from_fileobj
from_mapping
get_axis_renames
get_base_affine
get_best_affine
get_data_dtype
get_data_offset
get_data_shape
get_datatype
get_dim_info
get_intent
get_intent_code
get_qform
get_qform_code
get_qform_quaternion
get_sform
get_sform_code
get_slice_code
get_slice_duration
get_slice_times
get_slope_inter
get_zooms
items
keys
set_data_dtype
set_data_shape
set_dim_info
set_dim_info_from_names
set_intent
set_qform
set_sform
set_slice_duration
set_slice_times
set_slope_inter
set_zooms
values
write_to
__init__(binaryblock=None, endianness=None, check=True)

Initialize header from binary data block

Parameters :

binaryblock : {None, string} optional

binary block to set into header. By default, None, in which case we insert the default empty header block

endianness : {None, ‘<’,’>’, other endian code} string, optional

endianness of the binaryblock. If None, guess endianness from the data.

check : bool, optional

Whether to check content of header in initialization. Default is True.

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
as_byteswapped(endianness=None)

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

endian code to which to swap. None means swap from current endianness, and is the default

Returns :

hdr : header object

hdr object with given endianness

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
binaryblock

binary block of data as string

Returns :

binaryblock : string

string giving binary data block

Examples

>>> # Make default empty header
>>> hdr = AnalyzeHeader()
>>> len(hdr.binaryblock)
348
check_fix(logger=<logging.Logger object at 0x950fcac>, error_level=40)

Check header data with checks

copy()

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
classmethod diagnose_binaryblock(klass, binaryblock, endianness=None)

Run checks over header binary data, return string

endianness

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
for_file_pair(is_pair=True)

Adapt header to separate or same image and header file

Parameters :

is_pair : bool, optional

True if adapting header to file pair state, False for single

Returns :

hdr : Nifti1Header

copied and possibly modified header

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
classmethod from_fileobj(klass, fileobj, endianness=None, check=True)

Return read header with given or guessed endiancode

Parameters :

fileobj : file-like object

Needs to implement read method

endianness : None or endian code, optional

Code specifying endianness of read data

Returns :

hdr : AnalyzeHeader object

AnalyzeHeader object initialized from data in fileobj

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
classmethod from_mapping(klass, field_mapping=None, endianness=None, check=True)

Initialize header from mapping

get_axis_renames()

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

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

Select best of available transforms

get_data_dtype()

Get numpy dtype for data

For examples see set_data_dtype

get_data_offset()

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

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)
get_datatype(code_repr='label')

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

string giving output form of datatype code representation. Default is ‘label’; use ‘code’ for integer representation.

Returns :

datatype_code : string or integer

string label for datatype code or code

Examples

>>> hdr = AnalyzeHeader()
>>> hdr['datatype'] = 4 # int16
>>> hdr.get_datatype()
'int16'
get_dim_info()

Gets nifti MRI slice etc dimension information

Returns :

freq : {None,0,1,2}

Which data array axis is freqency 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 by ``get_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_repr : string

string giving output form of intent code representation. Default is ‘label’; use ‘code’ for integer representation.

Returns :

code : string or integer

intent code, or string describing code

parameters : tuple

parameters for the intent

name : string

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_intent_code(code_repr='label')

Return representation of intent code

Parameters :

code_repr : string

string giving output form of intent code representation. Default is ‘label’; use ‘code’ for integer representation.

Returns :

intent_code : string or integer

string label for intent code or code

Examples

>>> hdr = Nifti1Header()
>>> hdr.set_intent('t test', (10,), name='some score')
>>> hdr.get_intent_code()
't test'
get_qform()

Return 4x4 affine matrix from qform parameters in header

get_qform_code(code_repr='label')

Return representation of qform code

Parameters :

code_repr : string

string giving output form of intent code representation. Default is ‘label’; use ‘code’ for integer representation.

Returns :

qform_code : string or integer

string label for qform code or code

Examples

>>> hdr = Nifti1Header()
>>> hdr['qform_code'] = 3
>>> hdr.get_qform_code()
'talairach'
get_qform_quaternion()

Compute quaternion from b, c, d of quaternion

Fills a value by assuming this is a unit quaternion

get_sform()

Return sform 4x4 affine matrix from header

get_sform_code(code_repr='label')

Return representation of sform code

Parameters :

code_repr : string

string giving output form of intent code representation. Default is ‘label’; use ‘code’ for integer representation.

Returns :

sform_code : string or integer

string label for sform code or code

Examples

>>> hdr = Nifti1Header()
>>> hdr['sform_code'] = 3
>>> hdr.get_sform_code()
'talairach'
get_slice_code(code_repr='label')

Return representation of slice order code

Parameters :

code_repr : string

string giving output form of slice order code representation. Default is ‘label’; use ‘code’ for integer representation.

Returns :

slice_code : string or integer

string label for slice ordering code or code

Examples

>>> hdr = Nifti1Header()
>>> hdr['slice_code'] = 4 # alternating decreasing
>>> hdr.get_slice_code()
'alternating decreasing'
get_slice_duration()

Get slice duration

Returns :

slice_duration : float

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

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)

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

Get data scaling (slope) and DC offset (intercept) from header data

Parameters :

self : header object

Should have fields (keys) * scl_slope - slope * scl_inter - intercept

Returns :

slope : None or float

scaling (slope). None if there is no valid scaling from these fields

inter : None or float

offset (intercept). Also None if there is no valid scaling, offset

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

Get zooms from header

Returns :

z : tuple

tuple of header zoom values

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

Return items from header data

keys()

Return keys from header data

set_data_dtype(datatype)

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_data_shape(shape)

Set shape of data

set_dim_info(freq=None, phase=None, slice=None)

Sets nifti MRI slice etc dimension information

Parameters :

hdr : nifti1 header

freq : {None, 0, 1, 2}

axis of data array refering to freqency encoding

phase : {None, 0, 1, 2}

axis of data array refering to phase encoding

slice : {None, 0, 1, 2}

axis of data array refering 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_dim_info_from_names(axisnames)

Sets nifti dim_info from the names of the first three axes.

Parameters :

axisnames = [str] :

Names of up to the first three axes

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_intent(code, params=(), name='')

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

code specifying nifti intent

params : list, tuple of scalars

parameters relating to intent (see intent_codes) defaults to (). Unspecified parameters are set to 0.0

name : string

intent name (description). Defaults to ‘’

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(affine, code=None)

Set qform header values from 4x4 affine

Parameters :

hdr : nifti1 header

affine : 4x4 array

affine transform to write into qform

code : None, string or integer

String or integer giving meaning of transform in affine. The default is None. If code is None, then {if current qform code is not 0, leave code as it is in the header; else set to 1 (‘scanner’)}.

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(affine, code=None)

Set sform transform from 4x4 affine

Parameters :

hdr : nifti1 header

affine : 4x4 array

affine transform to write into sform

code : None, string or integer

String or integer giving meaning of transform in affine. The default is None. If code is None, then {if current sform code is not 0, leave code as it is in the header; else set to 1 (‘scanner’)}.

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

Set slice duration

Parameters :

duration : scalar

time to acquire one slice

Examples

See get_slice_duration

set_slice_times(slice_times)

Set slice times into hdr

Parameters :

slice_times : tuple

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_slice_code()
'alternating decreasing'
>>> int(hdr['slice_start'])
1
>>> int(hdr['slice_end'])
5
set_slope_inter(slope, inter)
set_zooms(zooms)

Set zooms into header fields

See docstring for get_zooms for examples

structarr

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

Return values from header data

write_to(fileobj)

Write header to fileobj

Write starts at fileobj current file position.

Parameters :

fileobj : file-like object

Should implement write method

Returns :

None :

Examples

>>> hdr = AnalyzeHeader()
>>> import StringIO
>>> str_io = StringIO.StringIO()
>>> hdr.write_to(str_io)
>>> hdr.binaryblock == str_io.getvalue()
True

Nifti1Image

class nipy.io.imageformats.nifti1.Nifti1Image(data, affine, header=None, extra=None)

Bases: nipy.io.imageformats.analyze.AnalyzeImage

__init__(data, affine, header=None, extra=None)
static filespec_to_files(filespec)
classmethod from_filename(klass, filename)
classmethod from_files(klass, files)
classmethod from_filespec(klass, img, filespec)
classmethod from_image(klass, img)

Create new instance of own class from img

This is a class method

Parameters :

img : spatialimage instance

In fact, an object with the API of spatialimage - specifically get_data, get_affine, get_header and extra.

Returns :

cimg : spatialimage instance

Image, of our own class

get_affine()
get_data()

Lazy load of data

get_data_dtype()
get_header()

Return header

Update header to match data, affine etc in object

get_shape()
get_unscaled_data()

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.

classmethod instance_to_filename(klass, img, filename)

Save img in our own format, to name implied by filename

This is a class method

Parameters :

img : spatialimage instance

In fact, an object with the API of spatialimage - specifically get_data, get_affine, get_header and extra.

filename : str

Filename, implying name to which to save image.

classmethod load(klass, filename)
classmethod save(klass, img, filename)
set_data_dtype(dtype)
to_filename(filename)

Write image to files implied by filename string

Returns :None :
to_files(files=None)

Write image to files passed, or self._files

to_filespec(filename)