Skip to content

brainhops.io.images.mrtrix

Readers and writers for images stored in MRtrix files.

MrtrixImage reads and writes the three variants of the MRtrix image format, with no dependency beyond numpy:

Extension Content
.mif text header and voxel data in one file
.mif.gz the same, gzip-compressed
.mih text header only; the data are in the file it names (.dat)

The header format, and every convention checked against the MRtrix3 sources, is described in brainhops.io.base.mrtrix, which the image reader shares with the MRtrix transformation formats.

import brainhops.io as io

image = io.load("dwi.mif")        # an MrtrixImage
image.data                        # [x, y, z, volume], a memory-mapped view
image.transformation              # voxel -> scanner RAS+ mm (Affine)
image.header.keyval["dw_scheme"]  # free-form keys, one line per row
image.save("dwi.mih")             # header + dwi.dat
io.save(image, "dwi.nii.gz")      # or any other image format

Data. The array is indexed in the order of the header's axes (x, y, z, ...), in F order, whatever layout the values are stored in. A negative axis (-0) is stored in decreasing order of its index, and a permuted layout (+1,+2,+3,+0, volume-contiguous, as MRtrix stores DWI data) changes which axis is fastest in the file. Both are undone by an array view, so the data of an uncompressed local .mif or .mih stay memory-mapped until they are indexed. A .mif.gz, a stream and Bit data are read into memory. The intensity scaling of the header, if any, is applied when data is first accessed; dataobj holds the stored values.

Coordinate systems. The transformations are, in order:

  1. voxel -> physical: a Scaling by the voxel sizes (vox); a non-finite size, common on the volume axis, is a scale of 1;
  2. voxel -> scanner: the Affine to scanner RAS+ millimetres.

The voxel axes are x, y, z (spatial), then dim3, dim4, ..., which MRtrix gives no meaning of their own. The scanner space has the three RAS+ axes. MRtrix's transform maps voxel coordinates multiplied by the voxel sizes, so the voxel-to-scanner matrix is transform @ diag(vox). A header without a transform is given MRtrix's default, which centres the field of view on the origin (-0.5 * (size - 1) * vox): it is not the identity.

Writing. The preferred transformation is converted to voxel-to-RAS+ (an LPS world is flipped) and split into unit direction cosines and voxel sizes, as MRtrix stores them. A writer option may set the layout (default: the layout the image was read with, else +0,+1,+2,...), the datatype (default: the data's own type, with an explicit byte order), an intensity scaling, and extra or removed header keys (keyval). The keys read from the source header (dw_scheme, command_history, ...) are written back.

Classes

MrtrixImage

MrtrixImage(
    _header: MrtrixHeader | None = None,
    dataobj: Any | None = None,
)

Bases: MrtrixParser, WritableFileBasedImage, SingleScaleImage

An image that is encoded by an MRtrix image file (.mif, .mif.gz, or .mih with its data file).

The data are indexed in the order of the header's axes ([x, y, z, ...], F order), whatever the layout they are stored in: a negative or permuted layout is undone by a view, so the data of an uncompressed local file stay memory-mapped. Intensity scaling, when the header has one, is applied on access; dataobj holds the stored values.

The voxel-to-world transformations are:

  1. voxel -> physical: a Scaling by the voxel sizes (vox);
  2. voxel -> scanner: the Affine to scanner RAS+ millimetres, transform @ diag(vox). The header's transform maps voxel coordinates multiplied by the voxel sizes, not voxel indices. Without a transform, MRtrix's default is used, which centres the field of view on the origin; it is not the identity.

The last one is the preferred transformation. Header keys that the data model has no slot for (dw_scheme, command_history, ...) are kept in header.keyval and written back.

Why the bases are in this order

As for NiftiImage: SingleScaleImage comes last so that its data field follows the defaulted fields of the parser, and the lazy properties of this class take precedence over the plain fields.

Attributes

PREFIXES class-attribute
PREFIXES: tuple[str, ...] = ()

Filename prefixes required by this parser, e.g. ("y_", "iy_").

An empty tuple means "no constraint". A parser that constrains the prefix is more specific than one that does not, and wins ties.

Declaring EXTENSIONS and PREFIXES separately states the cross-product implicitly, which is how these conventions actually work: SPM's four names are {y_, iy_} x {.nii, .nii.gz}.

PRIORITY class-attribute
PRIORITY: int = 10

Kind precedence, used only to break ties that confidence could not.

A NIfTI file is legitimately both an image and a set of affines, so when nothing else separates them the image wins. Scoring sniffers (e.g. NIfTI intent codes) normally decide well before this matters.

shape property
shape: tuple[int, ...]

The shape of the image data.

ndim property
ndim: int

The number of dimensions of the image data.

dtype property
dtype: dtype

The data type of the image data.

grid property

The Cartesian field that defines the sampling grid of the image.

This is the grid of the image's geometry.

transformation property writable
transformation: Transformation

The preferred transformation.

It is always the last transformation in the list.

Assigning a transformation appends it as the new preferred transformation. Assigning an integer or a string selects an existing transformation by position or by output-space name and moves it to the end. Assigning a transformation that is already in the list moves it to the end instead of adding a copy.

A transformation is recognized as already present by identity (transformations compare by identity): a distinct transformation with the same parameters is appended as a new preferred transformation.

geometry property
geometry: Geometry

A transformation that is the composition of the preferred voxel-to-world transformation and the cartesian field corresponding to the image's shape.

This transformation can be used to reslice any image onto the same grid as this image.

header property writable
header: MrtrixHeader | None

The MRtrix header this object was read from, if any.

data property writable
data: Any | None

The image data, scaled, unless set explicitly.

system property writable
system: CoordinateSystem | None

The voxel coordinate system, derived from the header, unless set explicitly. None when there is no header.

transformations property writable
transformations: list[Transformation]

The voxel-to-world transformations recorded by the header, decoded on access unless set explicitly.

An image built from data alone has no header, so it records no transformation and the list is empty.

Methods:

sniff classmethod
sniff(
    file: FileOrContentLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> type | None

On a dispatcher, identify which registered format would read file. On a concrete format, score how confident it is that file, in any supported form, is its own.

sniff_file classmethod
sniff_file(
    file: FileLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> type | None

On a dispatcher, identify which registered format would read the file (path or file-like object). On a concrete format, score how confident it is that the file is its own.

sniff_filename classmethod
sniff_filename(
    filename: FilenameLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Determine if the given filename is of the type that this parser can handle.

Parameters:

Name Type Description Default
filename FilenameLike

The filename to sniff.

required
error bool | type[Exception]

If not False, raise an error if the filename cannot be sniffed.

False
**kwargs

Parser-specific options.

{}

Returns:

Type Description
float

Confidence that the filename is of this type, in [0, 1].

sniff_fileobj classmethod
sniff_fileobj(
    file: IO,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Score how confident the class is that a stream holds an MRtrix image, gzipped or not.

sniff_content classmethod
sniff_content(
    content: ContentLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> type | None

On a dispatcher, identify which registered format would read the content (text or bytes). On a concrete format, score how confident it is that the content is its own.

sniff_bytes classmethod
sniff_bytes(
    content: bytes,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Score how confident the class is that bytes hold an MRtrix image, gzipped or not.

sniff_text classmethod
sniff_text(
    text: str,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> type | None

On a dispatcher, identify which registered format would read the text. On a concrete format, score how confident it is that the text is its own.

sniff_lines classmethod
sniff_lines(
    lines: Iterable[str],
    error: bool | Type[Exception] = False,
    **kwargs,
) -> type | None

On a dispatcher, identify which registered format would read the lines. On a concrete format, score how confident it is that the lines are its own.

sniff_line classmethod
sniff_line(
    line: str,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> type | None

On a dispatcher, identify which registered format would read the line. On a concrete format, score how confident it is that the line is its own.

load classmethod
load(other: FileOrContentLike, **kwargs) -> Self

On a dispatcher, pick the best-matching registered format and build an instance of it from other. On a concrete format, build an instance of this class from other, in any supported form.

from_spec classmethod
from_spec(spec: SourceSpec, **kwargs) -> Self

Load a structured source specification through this dispatcher.

from_file classmethod
from_file(file: FileLike, **kwargs) -> Self

Build the object from an MRtrix file (path or file object).

from_filename classmethod
from_filename(
    filename: FilenameLike, mmap: bool = True, **kwargs
) -> Self

Build the object from the path of a .mif, .mih or .mif.gz.

The data of an uncompressed local file are memory-mapped unless mmap is false. A .mih header is followed to the data file it names, relative to the header's directory.

from_fileobj classmethod
from_fileobj(file: BinaryIO, **kwargs) -> Self

Build the object from an open MRtrix file object, gzipped or not.

The data of a single-file image are read from the stream. A header that names a separate data file is resolved against the stream's name, when it has one.

from_content classmethod
from_content(content: ContentLike, **kwargs) -> Self

On a dispatcher, pick the best-matching registered format and build an instance of it from the content (text or bytes). On a concrete format, build an instance of this class from the content.

from_bytes classmethod
from_bytes(content: bytes, **kwargs) -> Self

Build the object from the bytes of a single-file MRtrix image (gzipped or not).

from_text classmethod
from_text(text: str, **kwargs) -> Self

On a dispatcher, pick the best-matching registered format and build an instance of it from the text. On a concrete format, build an instance of this class from the text.

from_lines classmethod
from_lines(lines: Iterable[str], **kwargs) -> Self

On a dispatcher, pick the best-matching registered format and build an instance of it from the lines. On a concrete format, build an instance of this class from the lines.

from_line classmethod
from_line(line: str, **kwargs) -> Self

On a dispatcher, pick the best-matching registered format and build an instance of it from the line. On a concrete format, build an instance of this class from the line.

save
save(file: FileLike, **kwargs) -> None

Write the object to a file (path or file-like object).

This is the generic front door to the to_* family. It is named save rather than to because to already means something else on the data models these parsers are mixed into: Transformation.to converts an object to another type. A writer's to was shadowed by it on every writable transformation.

Parameters:

Name Type Description Default
file FileLike

The file to write to.

required
**kwargs

Parser-specific options.

{}
to_file
to_file(file: FileLike, **kwargs) -> None

Write to a path (variant chosen by extension) or a stream.

to_filename
to_filename(filename: FilenameLike, **kwargs) -> None

Write to a path, in the variant its extension names.

  • .mif: header and data in one file;
  • .mif.gz: the same, gzip-compressed;
  • .mih: the header, and the data in a .dat file next to it (named after the header), which the header points to.
to_fileobj
to_fileobj(file: IO, **kwargs) -> None

Write a single-file, uncompressed .mif to a stream.

to_bytes
to_bytes(**kwargs) -> bytes

The bytes of a single-file, uncompressed .mif.

to_text
to_text(**kwargs) -> str

Return a text version of the file.

Parameters:

Name Type Description Default
**kwargs

Parser-specific options.

{}

Returns:

Type Description
str

A text version of the file.

to_lines
to_lines(**kwargs) -> Iterator[str]

Return a text version of the file as an iterable of lines.

Parameters:

Name Type Description Default
**kwargs

Parser-specific options.

{}

Returns:

Type Description
Iterator[str]

An iterable of lines representing the object.

to_line
to_line(**kwargs) -> str

Return a line representing the object.

Parameters:

Name Type Description Default
**kwargs

Parser-specific options.

{}

Returns:

Type Description
str

A line representing the object.

from_dict classmethod
from_dict(other: Mapping, *args, **kwargs) -> Self

Create an instance of the class from a dictionary-like object.

Only keys in the dictionary that match keyword-like fields of this class, or the keywords its constructor takes without storing them (its InitVars, such as the matrix= of an Affine), will be used. Other keys are ignored, but see from_other, which refuses them.

Additional positional and/or keyword arguments can be provided, and will take precedence over the values in the dictionary.

A key naming a field that this class fixes (a field that cannot be passed to its constructor) is checked instead of used: a dictionary that sets it to anything other than None or the value of this class is refused with a ValueError.

from_instance classmethod
from_instance(other: Any, *args, **kwargs) -> Self

Create an instance from an instance of a similar class.

The data model copies the fields both classes share, by name. A field that a file format declares for its own use -- such as the nibabel image and header of the NIfTI and MGH formats -- is only copied from an object of that same format: from any other object, a field of the same name holds something else (a NIfTI image is no MGH image), so this class's default is kept instead. Saving a NIfTI image to MGH, or the converse, therefore converts the data model only, and the format-specific state is rebuilt by the writer.

from_other classmethod
from_other(other: Any, *args, **kwargs) -> Self

Create an instance from a file, or from anything the data model reads.

A path (str or os.PathLike), an open file, bytes or a structured source (SourceSpec) is read with load: on a dispatcher such as FileBasedImage, the best-matching registered format reads it, and on a concrete format, that format does. Any other value is handed to the data model's own from_other, which reads a mapping field by field, copies an instance of a similar class, and passes anything else to the constructor.

Parameters:

Name Type Description Default
other Any

A file, its content, a mapping, or an instance of a similar class.

required
*args

Constructor arguments. A file is read with keyword options only.

()
**kwargs

Format-specific options when reading a file, and field values otherwise.

{}

Returns:

Type Description
obj

The object that was built.

Raises:

Type Description
TypeError

If positional arguments come with a file to read.

__array__
__array__(dtype: DTypeLike | None = None) -> ndarray

Return the image data as an array.

reslice
reslice(
    geometry: Self
    | Geometry
    | Transformation
    | None = None,
    degree: int = 1,
    bound: str = "reflect",
    coeff: bool = False,
    copy: bool = False,
) -> Self

Apply transformations to current data and return new image.

Parameters:

Name Type Description Default
geometry Image | Geometry | Transformation

Geometry of the output image.

The geometry is a voxel-to-world transformation that defines the grid onto which the image will be resliced.

If it is a Geometry, then it also defines the shape of the output image. Otherwise, the current shape of the image is used.

If it is None, the image is resampled onto its own grid.

None
degree 0..5

The spline degree. 0=nearest, 1=linear, 2=quadratic, etc.

0..5
bound (nearest, reflect, mirror, grid - wrap, wrap)

The boundary condition. If a string, one of: - 'nearest': nearest edge value (a a a a | a b c d | d d d d) - 'reflect': reflect at edge (d c b a | a b c d | d c b a) - 'mirror': mirror at edge (d c b | a b c d | c b a) - 'grid-wrap': wrap around (a b c d | a b c d | a b c d) - 'wrap': wrap around with shift (d b c d | a b c d | b c a b) If a float, the constant value to use beyond the edge.

'nearest'
coeff bool

If True, the input image is assumed to already contain spline coefficients. If False, the input image is prefiltered before interpolation.

False
copy bool

Whether the output data must be a fresh array. As with torch.Tensor.to, when False the output data may share memory with the input data: a reslice that only gathers (a flip, a permutation, or a unit-step slice, such as a reslice onto the image's own grid) can return a view of it. When True the output data never shares memory with the input data. A dask array is never copied: it is immutable, and writing into the output rebinds the output's own graph, never the input's, so the lazy output is returned as is.

False

Returns:

Type Description
Image

The resliced image.

__call__
__call__(transform: Transformation) -> SingleScaleImage

Apply a transformation to the image, but do not compute.

Parameters:

Name Type Description Default
transform Transformation

The transformation to apply.

The output space of this transformation should match (or be compatible with) the output space of the preferred transformation. That is, the new "voxel-to-world" transformation is defined as self.transformation @ transform.inverse().

required

Returns:

Type Description
Image

The updated (not-yet-resliced) image.

__getitem__
__getitem__(
    index: tuple[int | slice | None, ...],
) -> SingleScaleImage

Index into the image data while preserving the geometry of the image.