NiBabel

Access a cacophony of neuro-imaging file formats

Table Of Contents

Next topic

minc1

Reggie -- the one

freesurfer

Reading functions for freesurfer files

Module: freesurfer.io

read_annot(filepath[, orig_ids]) Read in a Freesurfer annotation from a .annot file.
read_geometry(filepath) Read a triangular format Freesurfer surface mesh.
read_label(filepath[, read_scalars]) Load in a Freesurfer .label file.
read_morph_data(filepath) Read a Freesurfer morphometry data file.
write_annot(filepath, labels, ctab, names) Write out a Freesurfer annotation file.
write_geometry(filepath, coords, faces[, ...]) Write a triangular format Freesurfer surface mesh.

Module: freesurfer.mghformat

Header and image reading / writing functions for MGH image format

Author: Krish Subramaniam

MGHError Exception for MGH format related problems.
MGHHeader([binaryblock, check]) Class for MGH format header
MGHImage(dataobj, affine[, header, extra, ...]) Class for MGH format image
load class method to create image from filename filename

read_annot

nibabel.freesurfer.io.read_annot(filepath, orig_ids=False)

Read in a Freesurfer annotation from a .annot file.

Parameters:

filepath : str

Path to annotation file.

orig_ids : bool

Whether to return the vertex ids as stored in the annotation file or the positional colortable ids. With orig_ids=False vertices with no id have an id set to -1.

Returns:

labels : ndarray, shape (n_vertices,)

Annotation id at each vertex. If a vertex does not belong to any label and orig_ids=False, its id will be set to -1.

ctab : ndarray, shape (n_labels, 5)

RGBA + label id colortable array.

names : list of str

The names of the labels. The length of the list is n_labels.

read_geometry

nibabel.freesurfer.io.read_geometry(filepath)

Read a triangular format Freesurfer surface mesh.

Parameters:

filepath : str

Path to surface file

Returns:

coords : numpy array

nvtx x 3 array of vertex (x, y, z) coordinates

faces : numpy array

nfaces x 3 array of defining mesh triangles

read_label

nibabel.freesurfer.io.read_label(filepath, read_scalars=False)

Load in a Freesurfer .label file.

Parameters:

filepath : str

Path to label file

read_scalars : bool

If true, read and return scalars associated with each vertex

Returns:

label_array : numpy array

Array with indices of vertices included in label

scalar_array : numpy array (floats)

If read_scalars is True, array of scalar data for each vertex

read_morph_data

nibabel.freesurfer.io.read_morph_data(filepath)

Read a Freesurfer morphometry data file.

This function reads in what Freesurfer internally calls “curv” file types, (e.g. ?h. curv, ?h.thickness), but as that has the potential to cause confusion where “curv” also refers to the surface curvature values, we refer to these files as “morphometry” files with PySurfer.

Parameters:

filepath : str

Path to morphometry file

Returns:

curv : numpy array

Vector representation of surface morpometry values

write_annot

nibabel.freesurfer.io.write_annot(filepath, labels, ctab, names)

Write out a Freesurfer annotation file.

See: https://surfer.nmr.mgh.harvard.edu/fswiki/LabelsClutsAnnotationFiles#Annotation

Parameters:

filepath : str

Path to annotation file to be written

labels : ndarray, shape (n_vertices,)

Annotation id at each vertex.

ctab : ndarray, shape (n_labels, 5)

RGBA + label id colortable array.

names : list of str

The names of the labels. The length of the list is n_labels.

write_geometry

nibabel.freesurfer.io.write_geometry(filepath, coords, faces, create_stamp=None)

Write a triangular format Freesurfer surface mesh.

Parameters:

filepath : str

Path to surface file

coords : numpy array

nvtx x 3 array of vertex (x, y, z) coordinates

faces : numpy array

nfaces x 3 array of defining mesh triangles

create_stamp : str

User/time stamp (default: “created by <user> on <ctime>”)

MGHError

class nibabel.freesurfer.mghformat.MGHError

Bases: exceptions.Exception

Exception for MGH format related problems.

To be raised whenever MGH is not happy, or we are not happy with MGH.

__init__()

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

MGHHeader

class nibabel.freesurfer.mghformat.MGHHeader(binaryblock=None, check=True)

Bases: object

Class for MGH format header

The header also consists of the footer data which MGH places after the data chunk.

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

check : bool, optional

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

__init__(binaryblock=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

check : bool, optional

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

binaryblock

binary block of data as string

Returns:

binaryblock : string

string giving binary data block

check_fix()

Pass. maybe for now

copy()

Return copy of header

data_from_fileobj(fileobj)

Read data array from fileobj

Parameters:

fileobj : file-like

Must be open, and implement read and seek methods

Returns:

arr : ndarray

data array

classmethod from_fileobj(klass, fileobj, check=True)

classmethod for loading a MGH fileobject

classmethod from_header(klass, header=None, check=True)

Class method to create MGH header from another MGH header

get_affine()

Get the affine transform from the header information. MGH format doesn’t store the transform directly. Instead it’s gleaned from the zooms ( delta ), direction cosines ( Mdc ), RAS centers ( Pxyz_c ) and the dimensions.

get_best_affine()

Get the affine transform from the header information. MGH format doesn’t store the transform directly. Instead it’s gleaned from the zooms ( delta ), direction cosines ( Mdc ), RAS centers ( Pxyz_c ) and the dimensions.

get_data_bytespervox()

Get the number of bytes per voxel of the data

get_data_dtype()

Get numpy dtype for MGH data

For examples see set_data_dtype

get_data_offset()

Return offset into data file to read data

get_data_shape()

Get shape of data

get_data_size()

Get the number of bytes the data chunk occupies.

Return offset where the footer resides. Occurs immediately after the data chunk.

get_ras2vox()

return the inverse get_affine()

get_slope_inter()

MGH format does not do scaling?

get_vox2ras()

return the get_affine()

get_vox2ras_tkr()

Get the vox2ras-tkr transform. See “Torig” here: https://surfer.nmr.mgh.harvard.edu/fswiki/CoordinateSystems

get_zooms()

Get zooms from header

Returns:

z : tuple

tuple of header zoom values

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

set_data_shape(shape)

Set shape of data

Parameters:

shape : sequence

sequence of integers specifying data array shape

set_zooms(zooms)

Set zooms into header fields

See docstring for get_zooms for examples

template_dtype = dtype([('version', '>i4'), ('dims', '>i4', (4,)), ('type', '>i4'), ('dof', '>i4'), ('goodRASFlag', '>i2'), ('delta', '>f4', (3,)), ('Mdc', '>f4', (3, 3)), ('Pxyz_c', '>f4', (3,)), ('mrparms', '>f4', (4,))])
values()

Return values from header data

writeftr_to(fileobj)

Write footer to fileobj

Footer data is located after the data chunk. So move there and write.

Parameters:

fileobj : file-like object

Should implement write and seek method

Returns:

None :

writehdr_to(fileobj)

Write header to fileobj

Write starts at the beginning.

Parameters:

fileobj : file-like object

Should implement write and seek method

Returns:

None :

MGHImage

class nibabel.freesurfer.mghformat.MGHImage(dataobj, affine, header=None, extra=None, file_map=None)

Bases: nibabel.spatialimages.SpatialImage

Class for MGH format image

Initialize image

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

Parameters:

dataobj : object

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

affine : None or (4,4) array-like

homogenous 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.

header : None or mapping or header instance, optional

metadata for this image format

extra : None or mapping, optional

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

file_map : mapping, optional

mapping giving file information for this image format

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

Initialize image

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

Parameters:

dataobj : object

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

affine : None or (4,4) array-like

homogenous 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.

header : None or mapping or header instance, optional

metadata for this image format

extra : None or mapping, optional

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

file_map : mapping, optional

mapping giving file information for this image format

ImageArrayProxy

alias of ArrayProxy

files_types = (('image', '.mgh'),)
classmethod filespec_to_file_map(klass, filespec)

Check for compressed .mgz format, then .mgh format

classmethod from_file_map(*args, **kwargs)

Load image from file_map

Parameters:

file_map : None or mapping, optional

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

mmap : {True, False, ‘c’, ‘r’}, optional, keyword only

mmap controls the use of numpy memory mapping for reading image array data. If False, do not try numpy memmap for data array. If one of {‘c’, ‘r’}, try numpy memmap with mode=mmap. A mmap value of True gives the same behavior as mmap='c'. If image data file cannot be memory-mapped, ignore mmap value and read array from file.

classmethod from_filename(*args, **kwargs)

class method to create image from filename filename

Parameters:

filename : str

Filename of image to load

mmap : {True, False, ‘c’, ‘r’}, optional, keyword only

mmap controls the use of numpy memory mapping for reading image array data. If False, do not try numpy memmap for data array. If one of {‘c’, ‘r’}, try numpy memmap with mode=mmap. A mmap value of True gives the same behavior as mmap='c'. If image data file cannot be memory-mapped, ignore mmap value and read array from file.

Returns:

img : MGHImage instance

header_class

alias of MGHHeader

classmethod load(*args, **kwargs)

class method to create image from filename filename

Parameters:

filename : str

Filename of image to load

mmap : {True, False, ‘c’, ‘r’}, optional, keyword only

mmap controls the use of numpy memory mapping for reading image array data. If False, do not try numpy memmap for data array. If one of {‘c’, ‘r’}, try numpy memmap with mode=mmap. A mmap value of True gives the same behavior as mmap='c'. If image data file cannot be memory-mapped, ignore mmap value and read array from file.

Returns:

img : MGHImage instance

to_file_map(file_map=None)

Write image to file_map or contained self.file_map

Parameters:

file_map : None or mapping, optional

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

load

nibabel.freesurfer.mghformat.load(*args, **kwargs)

class method to create image from filename filename

Parameters:

filename : str

Filename of image to load

mmap : {True, False, ‘c’, ‘r’}, optional, keyword only

mmap controls the use of numpy memory mapping for reading image array data. If False, do not try numpy memmap for data array. If one of {‘c’, ‘r’}, try numpy memmap with mode=mmap. A mmap value of True gives the same behavior as mmap='c'. If image data file cannot be memory-mapped, ignore mmap value and read array from file.

Returns:

img : MGHImage instance