freesurfer

Reading functions for freesurfer files

Module: freesurfer.io

Read / write FreeSurfer geometry, morphometry, label, annotation formats

read_annot(filepath[, orig_ids]) Read in a Freesurfer annotation from a .annot file.
read_geometry(filepath[, read_metadata, …]) 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 “new-style” Freesurfer annotation file.
write_geometry(filepath, coords, faces[, …]) Write a triangular format Freesurfer surface mesh.
write_morph_data(file_like, values[, fnum]) Write Freesurfer morphometry data values to file-like file_like

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

read_annot

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

Read in a Freesurfer annotation from a .annot file.

An .annot file contains a sequence of vertices with a label (also known as an “annotation value”) associated with each vertex, and then a sequence of colors corresponding to each label.

Annotation file format versions 1 and 2 are supported, corresponding to the “old-style” and “new-style” color table layout.

Note that the output color table ctab is in RGBT form, where T (transparency) is 255 - alpha.

See:
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)

RGBT + label id colortable array.

names : list of str (python 2), list of bytes (python 3)

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

read_geometry

nibabel.freesurfer.io.read_geometry(filepath, read_metadata=False, read_stamp=False)

Read a triangular format Freesurfer surface mesh.

Parameters:

filepath : str

Path to surface file.

read_metadata : bool, optional

If True, read and return metadata as key-value pairs.

Valid keys:

  • ‘head’ : array of int
  • ‘valid’ : str
  • ‘filename’ : str
  • ‘volume’ : array of int, shape (3,)
  • ‘voxelsize’ : array of float, shape (3,)
  • ‘xras’ : array of float, shape (3,)
  • ‘yras’ : array of float, shape (3,)
  • ‘zras’ : array of float, shape (3,)
  • ‘cras’ : array of float, shape (3,)

read_stamp : bool, optional

Return the comment from the 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.

volume_info : OrderedDict

Returned only if read_metadata is True. Key-value pairs found in the geometry file.

create_stamp : str

Returned only if read_stamp is True. The comment added by the program that saved the file.

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, optional

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)

Only returned 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, fill_ctab=True)

Write out a “new-style” Freesurfer annotation file.

Note that the color table ctab is in RGBT form, where T (transparency) is 255 - alpha.

See:
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)

RGBT + label id colortable array.

names : list of str

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

fill_ctab : {True, False} optional

If True, the annotation values for each vertex are automatically generated. In this case, the provided ctab may have shape (n_labels, 4) or (n_labels, 5) - if the latter, the final column is ignored.

write_geometry

nibabel.freesurfer.io.write_geometry(filepath, coords, faces, create_stamp=None, volume_info=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, optional

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

volume_info : dict-like or None, optional

Key-value pairs to encode at the end of the file.

Valid keys:

  • ‘head’ : array of int
  • ‘valid’ : str
  • ‘filename’ : str
  • ‘volume’ : array of int, shape (3,)
  • ‘voxelsize’ : array of float, shape (3,)
  • ‘xras’ : array of float, shape (3,)
  • ‘yras’ : array of float, shape (3,)
  • ‘zras’ : array of float, shape (3,)
  • ‘cras’ : array of float, shape (3,)

write_morph_data

nibabel.freesurfer.io.write_morph_data(file_like, values, fnum=0)

Write Freesurfer morphometry data values to file-like file_like

Equivalent to FreeSurfer’s write_curv.m

See also: http://www.grahamwideman.com/gw/brain/fs/surfacefileformats.htm#CurvNew

Parameters:

file_like : file-like

String containing path of file to be written, or file-like object, open in binary write (‘wb’ mode, implementing the write method)

values : array-like

Surface morphometry values. Shape must be (N,), (N, 1), (1, N) or (N, 1, 1)

fnum : int, optional

Number of faces in the associated surface.

MGHError

class nibabel.freesurfer.mghformat.MGHError

Bases: Exception

Exception for MGH format related problems.

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

__init__($self, /, *args, **kwargs)

Initialize self. See help(type(self)) for accurate signature.

MGHHeader

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

Bases: nibabel.wrapstruct.LabeledWrapStruct

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.

as_byteswapped(endianness=None)

Return new object with given endianness

If big endian, returns a copy of the object. Otherwise raises ValueError.

Parameters:

endianness : None or string, optional

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

Returns:

wstr : MGHHeader

MGHHeader object

static chk_version(hdr, fix=False)
copy()

Return copy of structure

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

Return header data for empty header

Ignores byte order; always big endian

classmethod diagnose_binaryblock(binaryblock, endianness=None)
classmethod from_fileobj(fileobj, check=True)

classmethod for loading a MGH fileobject

classmethod from_header(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 the spacing of voxels in the x, y, and z dimensions. For four-dimensional files, a fourth zoom is included, equal to the repetition time (TR) in ms (see The MGH/MGZ Volume Format).

To access only the spatial zooms, use hdr[‘delta’].

Returns:

z : tuple

tuple of header zoom values

classmethod guessed_endian(mapping)

MGHHeader data must be big-endian

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

Sets the spacing of voxels in the x, y, and z dimensions. For four-dimensional files, a temporal zoom (repetition time, or TR, in ms) may be provided as a fourth sequence element.

Parameters:

zooms : sequence

sequence of floats specifying spatial and (optionally) temporal zooms

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,)), ('tr', '>f4'), ('flip_angle', '>f4'), ('te', '>f4'), ('ti', '>f4'), ('fov', '>f4')])
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

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

alias of ArrayProxy

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

Check for compressed .mgz format, then .mgh format

classmethod from_file_map(file_map, mmap=True, keep_file_open=None)

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.

keep_file_open : { None, ‘auto’, True, False }, optional, keyword only

keep_file_open controls whether a new file handle is created every time the image is accessed, or a single file handle is created and used for the lifetime of this ArrayProxy. If True, a single file handle is created and used. If False, a new file handle is created every time the image is accessed. If 'auto', and the optional indexed_gzip dependency is present, a single file handle is created and persisted. If indexed_gzip is not available, behaviour is the same as if keep_file_open is False. If file_map refers to an open file handle, this setting has no effect. The default value (None) will result in the value of nibabel.arrayproxy.KEEP_FILE_OPEN_DEFAULT being used.

classmethod from_filename(filename, mmap=True, keep_file_open=None)

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.

keep_file_open : { None, ‘auto’, True, False }, optional, keyword only

keep_file_open controls whether a new file handle is created every time the image is accessed, or a single file handle is created and used for the lifetime of this ArrayProxy. If True, a single file handle is created and used. If False, a new file handle is created every time the image is accessed. If 'auto', and the optional indexed_gzip dependency is present, a single file handle is created and persisted. If indexed_gzip is not available, behaviour is the same as if keep_file_open is False. The default value (None) will result in the value of nibabel.arrayproxy.KEEP_FILE_OPEN_DEFAULT being used.

Returns:

img : MGHImage instance

header_class

alias of MGHHeader

classmethod load(filename, mmap=True, keep_file_open=None)

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.

keep_file_open : { None, ‘auto’, True, False }, optional, keyword only

keep_file_open controls whether a new file handle is created every time the image is accessed, or a single file handle is created and used for the lifetime of this ArrayProxy. If True, a single file handle is created and used. If False, a new file handle is created every time the image is accessed. If 'auto', and the optional indexed_gzip dependency is present, a single file handle is created and persisted. If indexed_gzip is not available, behaviour is the same as if keep_file_open is False. The default value (None) will result in the value of nibabel.arrayproxy.KEEP_FILE_OPEN_DEFAULT being used.

Returns:

img : MGHImage instance

makeable = True
rw = True
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

valid_exts = ('.mgh', '.mgz')