Skip to content

brainhops.io.images.nifti

Readers and writers for images stored in NIfTI files.

Classes

NiftiImage

NiftiImage(
    image: Nifti1Image | None = None,
    _header: Nifti1Header | None = None,
)

Bases: NiftiParser, WritableFileBasedImage, SingleScaleImage

An image that is encoded by a NIfTI file.

Why the bases are in this order

SingleScaleImage.data has no default, while NiftiParser contributes image and _header, which do. Struct fields are collected in reverse MRO order, so SingleScaleImage has to come last or data ends up behind a defaulted field and bagof rejects the signature. Leading with NiftiParser also lets its lazy data/system properties -- which pull from the nibabel image on demand -- 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.

data property writable
data: ArrayProtocol | None

The image data, read lazily from image and cached, unless it has been set explicitly.

The axes that the intent code marks as irrelevant, such as a singleton axis before a vector's components, are dropped.

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

The NIfTI header associated with this object.

If a header was explicitly set by the user (at construction or later), this will be pointing to that header.

Otherwise, if the object was created from a NIfTI header, this will be pointing to that header.

Otherwise, if the object was created from a NIfTI image, this will be pointing to the header of that image.

Example

    import nibabel as nb
    image1 = nb.load("image1.nii")
    image2 = nb.load("image2.nii")
    NiftiParser(image1).header                        # `image1.header`
    NiftiParser(header=image2.header).header          # `image2.header`
    NiftiParser(image1, header=image2.header).header  # `image2.header`
    obj = NiftiParser(image1)
    obj.header = image2.header
    obj.header                                        # `image2.header`
system property writable
system: CoordinateSystem | None

The voxel coordinate system, derived from header, unless it has been set explicitly.

The axes that the intent code marks as irrelevant are dropped. None when there is no header to derive it from.

transformations property writable
transformations: list[Transformation]

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

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

The decoded transformations are kept for as long as the image holds the same header object, so each access hands back the same transformations (in a new list): img.transformation is img.transformation, and a transformation composed with the inverse of the very same one cancels without being computed. Setting another header decodes it anew. A header changed in place is not noticed: assign a new header object (a copy, say) to decode it anew.

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,
    *,
    version: int | None = None,
    **kwargs,
) -> float

Score how confident the class is that an open file object holds a NIfTI-1 or NIfTI-2 header, or a header of the given version when one is passed.

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(
    data: bytes,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Score how confident the class is that bytes hold a NIfTI-1 or NIfTI-2 header.

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 NIfTI file.

A local path is handed to nibabel by name, so that it owns the file handle and can memory-map the voxels: its array proxy reads them lazily, long after the call returns. A remote path is opened through its own backend instead, since nibabel would take its name for a local file. See _load_nifti.

from_filename classmethod
from_filename(filename: FilenameLike, **kwargs) -> Self

Build an object from a filename.

Parameters:

Name Type Description Default
filename FilenameLike

The filename to parse.

required
**kwargs

Parser-specific options.

{}

Returns:

Type Description
obj

The parsed object.

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

Build the object from an open NIfTI file object, image data included when the stream allows reading it.

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(data: bytes, **kwargs) -> Self

Build the object from bytes in NIfTI format.

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 the object to a NIfTI file.

A path is written gzipped when its name ends in .gz: a local path is handed to nibabel by name, and a remote one is opened through its own backend. See _save_nifti. A file-like object is written the uncompressed NIfTI bytes.

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

Write the object to a filename.

Parameters:

Name Type Description Default
filename FilenameLike

The filename to write to.

required
**kwargs

Parser-specific options.

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

Write the uncompressed NIfTI-1 encoding of the object to an open file object.

to_bytes
to_bytes(**kwargs) -> bytes

Return the uncompressed NIfTI-1 encoding of the object.

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.

from_nibabel classmethod
from_nibabel(nifti: _NiftiObject, **kwargs) -> Self

Build the object from an already-loaded nibabel header or image.

sniff_nibabel classmethod
sniff_nibabel(
    nifti: _NiftiObject,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Score how confident the class is that an already-loaded nibabel header or image matches this format.

The header's magic number is checked first. A header that passes is then scored for how well it matches this particular format, as opposed to another kind of NIfTI-based format.

to_nibabel
to_nibabel(
    like: Any = None, **overrides
) -> Nifti1Image | Nifti2Image

Build the nibabel image that encodes this image.

The image data becomes the NIfTI data array. The preferred transformation becomes the sform, and a rigid transformation among the others, or the rigid part of the sform, becomes the qform. A large array is written as NIfTI-2, and a smaller one as NIfTI-1.

A preferred transformation that is not an affine, such as a displacement field, cannot describe NIfTI geometry, and raises UnrepresentableTransformationError.

When like is given, non-encoding header fields such as the description and the intent are copied from it. The template may be a path to a NIfTI file, a nibabel image or header, or another object read from NIfTI. The geometry always comes from this image, never from the template.

Keyword arguments override header fields after the derived values and after like, so an explicit value always wins. dtype sets the stored data type, intent the intent code, and descrip the description. The array's own data type is kept unless dtype is given.