Skip to content

brainhops.io.images.nrrd

Readers and writers for images stored in NRRD files.

NRRD ("Nearly Raw Raster Data", https://teem.sourceforge.net/nrrd/) is the native format of 3D Slicer and teem, and is read and written by ITK. It is parsed by brainhops.io.base.nrrd, with no dependency beyond numpy:

Class Extension Hints
AttachedNrrdImage .nrrd nrrd, nrrd.attached
DetachedNrrdImage .nhdr nrrd, nhdr, nrrd.nhdr

Both derive from NrrdImage, read either kind of file (the content decides which class does: a header that names a data file is detached), and write the kind the file name asks for.

import brainhops.io as io

image = io.load("dwi.nhdr")            # a DetachedNrrdImage
image.data                             # [x, y, z, c], F order, a view
image.transformation                   # index -> LPS mm (Affine)
image.header.keyvalue["DWMRI_b-value"] # key/value pairs, as text
image.save("dwi.nrrd")                 # attached, gzip by default
io.save(image, "dwi.nii.gz")           # or any other image format

Axes. NRRD stores its first axis fastest, so the values are read in F order. The image axes are the spatial axes first (x, y, z), then the time (t), channel (c) and other (dim<i>) axes, each group in the order of the file; this is a transposed view of the stored values (dataobj). An axis is spatial when it has a space direction (or, in a header without them, when its kind is domain or space, or, when the header has no kinds, when it is one of the first three). A time axis is temporal. An axis of kind vector, list, point, covariant-vector, normal, N-vector, RGB-color (and the other colours), complex, quaternion or a matrix kind is a channel axis. Any other (scalar, stub, none) is an untyped axis.

Coordinate systems. The transformations are, in order:

  1. index -> "physical": a Scaling by the length of each space direction (and the spacings of the other axes);
  2. index -> world: the Affine whose columns are the space directions, and whose translation is the space origin.

The world space follows space: right-anterior-superior ("RAS"), left-anterior-superior ("LAS") and left-posterior-superior ("LPS", what 3D Slicer and ITK write) have anatomically oriented axes, so they convert to one another (and to NIfTI's RAS) from the axes alone; scanner-xyz and 3D-right-handed / 3D-left-handed have unoriented ones; the -time variants add a time axis. Their unit is the space units, or millimetres (but for the 3D-*-handed spaces). A header with only a space dimension has an unoriented "world". A header with no world space has a single index -> "physical" map from the spacings, axis mins / axis maxs and units of its axes.

Index space and centering. An integer index is the centre of a sample, as everywhere in brainhops. NRRD's space origin is the position of the centre of the first sample, whatever the axis centers, so the world Affine needs no shift. The centers only matter for the axis mins / axis maxs fallback: a cell-centred axis (the default, as in teem) spans size samples from the edge of the first to the edge of the last, so its first sample is centred at min + spacing / 2; a node-centred axis has samples at min and max exactly.

Writing. The preferred transformation becomes space directions and space origin. When its world is anatomical, it is written in the space of the source header, else in the one it maps to (RAS, LAS or LPS), else in RAS; the space writer option chooses one. An unoriented world is written with a space dimension, but a scaling onto unoriented axes of an image whose source had no world space goes back to spacings and axis mins. An image read from NRRD whose shape has not changed is written in the axis order, and with the kinds, of its file; any other in its own order, with kinds domain, time, vector and none. The writer options are encoding (default: the source's, else gzip), endian, datatype, space, keyvalue (merged into the source's; a value of None removes a key) and data_file (the data file of a detached header; default: the header's name with .raw, .raw.gz, .raw.bz2, .txt or .hex). The source header's key/value pairs, content, measurement frame (converted to the new space), sample units, old min / old max, and its centers, labels, thicknesses and the units, spacings and axis mins / maxs of the non-spatial axes, are written back.

Classes

AttachedNrrdImage

AttachedNrrdImage(
    _header: NrrdHeader | None = None,
    dataobj: Any | None = None,
)

Bases: NrrdImage

An image that is encoded by a NRRD file whose header and data are in the same file (.nrrd). See NrrdImage.

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.

data property writable
data: Any | None

The image data, [x, y, z, ...], unless set explicitly.

transformations property writable
transformations: list[Transformation]

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

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: NrrdHeader | None

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

system property writable
system: CoordinateSystem | None

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

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 a NRRD file of its own kind.

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 a NRRD file of its own kind.

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 a NRRD 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 .nrrd or .nhdr file.

The values of a raw local data file are memory-mapped unless mmap is false. Detached data files are found relative to the header's directory.

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

Build the object from an open NRRD file object.

Detached data files are 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 an attached NRRD file.

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,
    data_file: str | None = None,
    **kwargs,
) -> None

Write to a path: an attached file, or, for a .nhdr name (or when data_file is given), a detached header and its data file.

The data file of a detached header is named after it, with an extension that says its encoding (.raw, .raw.gz, .raw.bz2, .txt, .hex), unless data_file names it (relative to the header's directory).

to_fileobj
to_fileobj(file: IO, **kwargs) -> None

Write an attached NRRD file to a stream.

to_bytes
to_bytes(**kwargs) -> bytes

The bytes of an attached NRRD file.

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.

DetachedNrrdImage

DetachedNrrdImage(
    _header: NrrdHeader | None = None,
    dataobj: Any | None = None,
)

Bases: NrrdImage

An image that is encoded by a detached NRRD header (.nhdr) and the data file(s) it names. See NrrdImage.

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.

data property writable
data: Any | None

The image data, [x, y, z, ...], unless set explicitly.

transformations property writable
transformations: list[Transformation]

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

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: NrrdHeader | None

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

system property writable
system: CoordinateSystem | None

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

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 a NRRD file of its own kind.

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 a NRRD file of its own kind.

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 a NRRD 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 .nrrd or .nhdr file.

The values of a raw local data file are memory-mapped unless mmap is false. Detached data files are found relative to the header's directory.

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

Build the object from an open NRRD file object.

Detached data files are 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 an attached NRRD file.

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,
    data_file: str | None = None,
    **kwargs,
) -> None

Write to a path: an attached file, or, for a .nhdr name (or when data_file is given), a detached header and its data file.

The data file of a detached header is named after it, with an extension that says its encoding (.raw, .raw.gz, .raw.bz2, .txt, .hex), unless data_file names it (relative to the header's directory).

to_fileobj
to_fileobj(file: IO, **kwargs) -> None

Write an attached NRRD file to a stream.

to_bytes
to_bytes(**kwargs) -> bytes

The bytes of an attached NRRD file.

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.

NrrdImage

NrrdImage(
    _header: NrrdHeader | None = None,
    dataobj: Any | None = None,
)

Bases: NrrdParser, WritableFileBasedImage, SingleScaleImage

An image that is encoded by a NRRD file, attached (.nrrd) or detached (.nhdr and its data files).

It is the shared base of AttachedNrrdImage and DetachedNrrdImage, which answer to its hint "nrrd"; it is not registered itself, so that it does not compete with them. Either one reads both kinds of file, and writes the kind the file name asks for.

The data are indexed [x, y, z, t, c, ...], F order: the spatial axes first, then the time, channel and other axes, each group in the order of the file (whose first axis is the fastest). This is a view of the stored values (dataobj, in the file's axis order), so the values of a raw local file stay memory-mapped.

The transformations are an index -> "physical" Scaling, then, when the header has a world space, the index -> world Affine built from space directions and space origin (preferred). The world is named after the space ("RAS", "LPS", "LAS", "scanner-xyz", ...; "world" for a bare space dimension). Header fields and key/value pairs that the data model has no slot for are kept in header 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

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

File extensions handled by this parser, e.g. (".nii", ".nii.gz").

Used as a first, cheap dispatch pass. When several parsers match, the longest matching extension wins, so a parser declaring ".nii.gz" takes precedence over one declaring ".gz".

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: NrrdHeader | None

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

data property writable
data: Any | None

The image data, [x, y, z, ...], unless set explicitly.

system property writable
system: CoordinateSystem | None

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

transformations property writable
transformations: list[Transformation]

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

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 a NRRD file of its own kind.

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 a NRRD file of its own kind.

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 a NRRD 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 .nrrd or .nhdr file.

The values of a raw local data file are memory-mapped unless mmap is false. Detached data files are found relative to the header's directory.

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

Build the object from an open NRRD file object.

Detached data files are 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 an attached NRRD file.

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,
    data_file: str | None = None,
    **kwargs,
) -> None

Write to a path: an attached file, or, for a .nhdr name (or when data_file is given), a detached header and its data file.

The data file of a detached header is named after it, with an extension that says its encoding (.raw, .raw.gz, .raw.bz2, .txt, .hex), unless data_file names it (relative to the header's directory).

to_fileobj
to_fileobj(file: IO, **kwargs) -> None

Write an attached NRRD file to a stream.

to_bytes
to_bytes(**kwargs) -> bytes

The bytes of an attached NRRD file.

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.