Skip to content

brainhops.io.images

Readers and writers for image file formats.

Classes

ImageFormat

Bases: FileBasedModelMixin, DataModelBase, FileFormat

Format dispatcher and common base for stored images.

ImageFormat is the common base of the image formats, and it chooses which format reads a given file. A concrete reader inherits from this class and registers itself with @register_format, so that load finds the reader without a hand-maintained table of formats.

The consolidate method of an image format, and each method that writes a file, take an error policy as their on_error= and on_loss= keywords (see ErrorPolicy), which decides what happens to what the file cannot hold. A format overrides the hook _consolidate, around which the base class applies the policy, and puts the decorator takes_error_policy above each writer that it defines, which applies the policy around the writer. Neither the hook nor a writer declares these keywords.

Attributes

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

File extensions that the format handles, such as (".mgh", ".mgz").

A matching extension keeps the format among the candidates even if its sniffer declines, and the extension match is the next ranking criterion after the sniffer score. The longest matching extension wins, so .note.txt beats .txt. Every format may be compressed, so the extensions leave out compression suffixes: a name that ends with .gz, .bz2 or .xz also matches the extensions of the name without that suffix, and x.nii.gz matches .nii. An extension that implies compression without such a suffix, such as .mgz, is listed.

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

Required file name prefixes, such as ("y_", "iy_").

An empty tuple means that any name is accepted. When prefixes are declared, a file name matches the format only if it starts with one of them, and a format with a matching prefix is more specific and wins ties. Extensions and prefixes are declared separately, and every prefix combines with every extension, as file naming conventions usually do: the four names of SPM deformation fields are {y_, iy_} times {.nii, .nii.gz}.

PRIORITY class-attribute
PRIORITY: int = 10

Precedence of images over other kinds of object, used to break ties.

When a file could be read as several kinds of object, the readers that score their input, for example by the NIfTI intent code, normally decide first, and this priority matters only when nothing else does. A NIfTI file, for instance, is both an image and a set of affines, and it is read as an image when nothing else separates the two.

Methods:

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

Identify the registered format of a file or its content.

The result is the registered format that would read the input.

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

Same as sniff, for a path or an open file.

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

Identify the registered format that matches a path.

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

Same as sniff, for an open file object.

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

Same as sniff, for text or binary content.

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

Same as sniff, for binary content.

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

Same as sniff, for text.

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

Same as sniff, for lines of text.

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

Same as sniff, for a single line.

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

Read an object from a file or its content.

The input is read with the best-matching registered format. A SourceSpec is read with from_spec.

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

Read a structured source specification.

The specification's path is read with its hints and options.

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

Read an object from a path or an open file.

The file is read with the best-matching registered format.

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

Same as from_file, for a path.

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

Same as from_file, for an open file object.

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

Same as from_file, for text or binary content.

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

Same as from_file, for binary content.

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

Same as from_file, for text.

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

Same as from_file, for lines of text.

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

Same as from_file, for a single line.

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

Build an instance from a mapping.

Only keys that can be passed to the constructor are used. Other keys are ignored, unlike in from_any

A key that corresponds to a fixed attribute (that is, an attribute that cannot be set by the constructor) is checked against its value.

Extra arguments (*args and **kwargs) are passed to the constructor and take precedence over the mapping.

Raises:

Type Description
ValueError

If a fixed attribute is given a value other than None or the value that the class fixes.

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

Copy an instance, resetting fields that belong to another format.

The data model copies the fields of other by name. Fields declared by a file format, such as the rawdata array and the metadata of NIfTI and MGH, are copied only from an object of the same format; otherwise the class default is kept, because the same field name holds something different. Converting NIfTI to MGH on save therefore converts the data model only, and the writer rebuilds the format state.

A format that decodes its data or its transformations from its file stores them in the private fields _data and _transformations, where None means that they are decoded. Within the format, the stored values are copied, so a copy of an image whose data was not assigned holds the same rawdata as other, which stays lazy if it is a proxy, and decodes the same record. From another class, the data, the levels of a pyramid and the transformations that other reports are copied, decoded if need be, because its rawdata and its record mean nothing to this format. A format that takes metadata over receives the metadata of other, which its field converts into the metadata of the format, without the record of other.

Parameters:

Name Type Description Default
other object

The instance to copy.

required
*args Any

Constructor arguments, which take precedence over the fields of other.

()
**kwargs Any

Constructor arguments, which take precedence over the fields of other.

{}

Returns:

Type Description
Self

The copy.

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

Build an object from a file or any value the data model takes.

A path, an open file (any object with a read method), bytes, bytearray or a SourceSpec is read with load. A dispatcher then chooses the best format, and a concrete format reads the input as an instance of its own class. Any other value is passed to the from_any of the data model, which maps a mapping field by field, copies an instance of a similar class, or calls the constructor.

Parameters:

Name Type Description Default
other object

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

required
*args Any

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

()
**kwargs Any

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

{}

Raises:

Type Description
TypeError

If positional arguments accompany a file.

to
to(
    cls: type | None = None, *, copy: bool = False, **kwargs
) -> Any

Convert the object to another class of its data model.

Without a class, the object keeps its own class, and its attributes may be replaced by the keyword arguments.

Otherwise, the object is converted by cls.from_instance, which copies the attributes of a related class by name. Some subclasses override this method so that it triggers a more specific conversion.

Parameters:

Name Type Description Default
cls type

The class to convert to. By default, the class of the object.

None
copy bool

Whether to return a new object even when nothing changes.

False
**kwargs Any

Fields of the result, which take precedence over those of the object.

{}

Returns:

Type Description
DataModelBase

The converted object, an instance of cls.

Raises:

Type Description
ConversionError

If cls is not related to the class of the object.

consolidate
consolidate(
    *,
    inplace: bool = False,
    on_error: ErrorPolicy = UNSET,
    on_loss: ErrorAction = UNSET,
    **fields: Any,
) -> Self

Encode the object into the record that its file format writes.

An image, a transformation or the metadata of a file format holds the record of its file, such as the header of a NIfTI file, as it was read or as the object was last consolidated. When the object changes, the record no longer describes it, and the consolidation encodes the object into a copy of the record. Every write of the format consolidates the object first, and the method can also be called to see what a write would store. The options that each format takes, and the rules of its encoding, are those of the format.

What the record cannot hold, such as a field of the metadata that the format has no slot for, is reported as lost or approximated, and the error policy of the call decides what happens to the report: by default, the policy in effect warns (see metadata_loss_policy). A format that cannot encode the object at all raises a conversion error, to which the policy applies as well.

Parameters:

Name Type Description Default
inplace bool

Whether to change this object rather than a copy.

False
on_error ErrorPolicy

What to do with a conversion error, including a loss (see ErrorPolicy). A mapping may also name other errors. By default, an error is raised, and a loss follows the policy in effect.

UNSET
on_loss ErrorAction

What to do with a loss, with the same values as a single action of on_error. An entry for a loss in on_error takes precedence over it. By default, a loss falls under on_error.

UNSET
**fields Any

Fields of the metadata to override before the encoding, by name, and the options of the format.

{}

Returns:

Type Description
Self

The consolidated copy, or this object with inplace=True, or the value that the policy returns in its place.

Raises:

Type Description
TypeError

If a keyword names neither a field of the metadata nor an option of the format.

MetadataLossError

If something is lost under the "raise" policy.

Functions:

load

load(
    filelike: FileOrContentLike | ImageSpec,
    brute: bool = False,
    **kwargs,
) -> ImageFormat

Read an image from a file, whatever its format.

Parameters:

Name Type Description Default
filelike (file, content or ImageSpec)

File to read, its content, or a structured image source.

required
brute bool

Whether to try every registered reader when no format recognizes the input.

False
**kwargs Any

Format-specific options.

{}

Returns:

Type Description
ImageFormat

The image that was read.

sniff

sniff(filelike: FileOrContentLike, **kwargs) -> type | None

Predict which image format would read a file.

The file is inspected but never parsed, so the result predicts what load would try first rather than guaranteeing success.

Parameters:

Name Type Description Default
filelike file or content

File to inspect, or its content.

required
**kwargs Any

Format-specific options.

{}

Returns:

Type Description
type or None

The best-matching registered format, or None if no single format stands out.