brainhops.io.images.tiff
TIFF images -- plain TIFF, BigTIFF, OME-TIFF, ImageJ hyperstacks and pyramidal TIFF -- read and written with tifffile.
This reader requires the tiff extra (pip install brainhops[tiff]).
Without tifffile, it is not registered (see
Without tifffile).
from brainhops.io.images import load
from brainhops.io import save
image = load("stack.ome.tif") # TiffImage
image.data.shape # (x, y, z, c)
image.transformation # Scaling onto "physical", in µm
pyramid = load("slide.ome.tif") # TiffMultiScaleImage, if pyramidal
level = load("slide.ome.tif", level=2)
save(image, "copy.ome.tif")
Data
A TIFF file holds one or more series -- an image, a stack or a
hyperstack -- that tifffile assembles from its pages, each with the axes
it reads from the file's metadata (TZCYXS, ...). The reader returns one
series (series=, the first by default) transposed to the brainhops order
-- a view, not a copy -- so that the spatial axes x, y[, z] come first,
then time t, then channels c, then any other axis. An RGB image is
(x, y, c); an ImageJ hyperstack TZCYX is (x, y, z, t, c).
The pixels are read when image.data is first accessed, not when the
image is loaded:
- memory-mapped (copy-on-write) when the file is local and the series is stored uncompressed and contiguously, which is how ImageJ, tifffile and most microscopes write it -- nothing is read until the array is indexed;
- lazily, as a dask array over tifffile's Zarr store, when dask is the
array backend or with
lazy=True(this needs dask and zarr) -- the path for large compressed or tiled files; - in full otherwise.
mmap=False turns memory-mapping off.
Geometry
The index space is 0-based, and an integer index is the centre of a
pixel. The first row of the file is the top of the picture, so y points
down; this is not encoded as an orientation.
The image carries one transformation, a scaling from its "pixel" (or
"voxel") coordinate system to a "physical" one. Its sizes come from
the first of these that records them, axis by axis:
- OME-XML:
PhysicalSizeX/Y/Zin their units (micrometres when the unit is absent, as the schema says), andTimeIncrement(seconds). The position of the first plane (PositionX/Y/Zof the plane whose Z, C and T indices are all 0) is the origin: the transformation is an affine with that translation. A position with no unit (or in OME's"reference frame") is taken in the unit of the pixel size, and a position is used only along an axis whose size is known. - ImageJ: the pixel size is
1 / XResolution(and1 / YResolution) in the hyperstack'sunit("micron","um"and"\u00B5m"are micrometres), the slice step isspacing-- negative when the slices run backwards, which flipsz-- and the frame interval isfinterval. - Resolution tags:
XResolutionandYResolutionperResolutionUnit-- inch (also when the unit tag is absent), centimetre, or tifffile's millimetre and micrometre. A unit of 1 (none) gives an aspect ratio only, so the size is unknown.
When none records a size, it is unknown: the scaling is the identity and the physical axes have no unit. Missing resolution tags (which tifffile reports as 1 pixel per inch), and placeholders -- 72 or 96 dpi, or one pixel per inch or centimetre -- are unknown too.
Every part of it can be overridden: pixel_size= (one size, one per
spatial axis, or a mapping by name) and unit= as for every raster image,
and origin= (False to ignore the file's positions).
Pyramids
A pyramidal series -- OME-TIFF or plain TIFF whose levels are stored as
SubIFDs, or any pyramid tifffile recognizes -- is read as a
TiffMultiScaleImage,
whose levels are TiffImages,
finest first, each read only when its data is accessed. load(file,
level=k) reads a single level as a TiffImage instead.
A level's pixel size is the full-resolution pixel size times its
downsampling factor, the ratio of the shapes (not rounded). Levels are
aligned by extent: pixel i of a level downsampled by f is centred on
the full-resolution pixel coordinate f * i + (f - 1) / 2, so the edges
of every level coincide. This is the convention of block-averaged
pyramids, and the one an OME-Zarr pyramid states with a translation of
(f - 1) / 2 pixels. Every level maps onto the same "physical" system,
and the pyramid's own transformation is the identity.
Metadata
What the file records besides the pixels is kept on the image, not in the
data model: dialect ("ome", "imagej", or None), ome_xml,
imagej_metadata, tags (resolution, description, software, date,
artist, copyright, ...), series, level, n_series, n_levels and
storage_axes (tifffile's axes of the series, such as "TZCYX").
Writing
An image is written with tifffile, in one of three dialects:
- OME-TIFF when the file name ends in
.ome.tifor.ome.tiff, when the image was read from an OME-TIFF, or when its pixel size is known:PhysicalSizeX/Y/Zin micrometres,TimeIncrement, and plane positions when the transformation has a translation. The image name and channel names of an OME-TIFF it was read from are written back. OME-TIFF stores no flip: a negative scale is written as its magnitude. - ImageJ when the image was read from an ImageJ hyperstack and ImageJ
can store it (axes in the order
TZCYXS,uint8,uint16orfloat32): unit, spacing (signed), frame interval, and the rest of the ImageJ metadata (display ranges, LUTs, labels, ...) when it still applies. - Plain TIFF otherwise, with the axes in tifffile's own metadata and,
if the pixel size is known (with
dialect="plain"), the resolution tags in centimetres.
dialect= chooses one explicitly. When writing OME-TIFF, the resolution
tags are written too, for readers that know no OME. The axes are stored in
the order they were read in, or else TZCYX, with an RGB(A) uint8
channel axis stored as samples (S). The data type is stored as it is.
BigTIFF is used when the data does not fit in 4 GiB (or with
bigtiff=True). Other keywords go to tifffile (compression="zlib",
tile=(256, 256), ...). A TiffMultiScaleImage is written as a pyramid,
its levels as SubIFDs of the first (OME-TIFF or plain TIFF); the placement
of the levels is not stored, and is derived from their shapes again when
the file is read. The software, date, artist, copyright and a few other
tags read from a file are written back.
Without tifffile
When tifffile is not installed, this module is not registered, and a TIFF
file is read by the Pillow raster reader
(PillowImage) instead, if
Pillow is installed: one page (frame=) at a time, with the resolution
tags as the pixel size only with dpi=True. OME-XML, ImageJ metadata,
stacks and pyramids need tifffile.
Classes
TiffImage
magic
TiffImage(
dialect: str | None = None,
ome_xml: str | None = None,
imagej_metadata: dict[str, Any] | None = None,
tags: dict[str, Any] | None = None,
series: int | None = None,
level: int | None = None,
n_series: int | None = None,
n_levels: int | None = None,
storage_axes: str | None = None,
)
Bases: _TiffMixin, BinaryFileParserWriter, WritableFileBasedImage, SingleScaleImage
One image of a TIFF file -- plain TIFF, BigTIFF, OME-TIFF or an ImageJ hyperstack -- read and written with tifffile.
The data is one level (by default, the full resolution) of one series
(by default, the first) of the file, F-ordered: the spatial axes
x, y[, z] first, then time, then channels, then anything else.
The only transformation is a scaling
(with a translation when the file records an origin) from the pixel
system to a "physical" system; it is the identity, in no unit, when
the pixel size is unknown.
The pixels are read when data is first accessed: memory-mapped when
the file is local and uncompressed, as a dask array when dask is the
array backend, and in full otherwise.
What the file records beyond the pixels is kept on the object --
dialect, ome_xml, imagej_metadata, tags, series, level,
n_series, n_levels and storage_axes -- and is written back, as
far as it still applies, when the image is saved.
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.
grid
property
grid: CartesianField
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.
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
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 |
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: BinaryContentLike,
error: bool | Type[Exception] = False,
**kwargs,
) -> float
Score how confident the class is that bytes hold a TIFF file.
sniff_text
classmethod
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
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
On a dispatcher, pick the best-matching registered format and build an instance of it from the file (path or file-like object). On a concrete format, build an instance of this class from the file.
from_filename
classmethod
from_filename(filename: FilenameLike, **kwargs) -> Self
Read the image from a file.
A local file is reopened by name when the pixels are read, so they
can be memory-mapped. A remote file is read into memory. See
from_source for the options.
from_fileobj
classmethod
Read the image from an open binary file, which is read into
memory and left where it was. See from_source for the
options.
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: BinaryContentLike, **kwargs) -> Self
Read the image from the bytes of a file. See from_source for
the options.
from_text
classmethod
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
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
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 file (path or file-like object).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
FileLike
|
The file to write to. |
required |
**kwargs
|
Parser-specific options. |
{}
|
to_filename
to_filename(filename: FilenameLike, **kwargs) -> None
Write the image to a file. A name ending in .ome.tif or
.ome.tiff asks for OME-TIFF. See to_bytes for the options.
What will be written is worked out before the file is opened, so an image that cannot be written leaves no file behind. A local file is written by tifffile directly.
to_fileobj
to_fileobj(file: IO, **kwargs) -> None
Write the image to an open binary file. Its name, if it has one,
chooses the dialect as in to_bytes.
to_bytes
to_bytes(**kwargs) -> bytes
Encode the image as a TIFF file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dialect
|
(ome, imagej, plain)
|
The metadata to write. By default: OME-TIFF if |
"ome"
|
name
|
str
|
The name of the file, which may ask for OME-TIFF. |
required |
bigtiff
|
bool
|
Write a BigTIFF file. By default, only when the data is too large for a classic TIFF file (4 GiB). |
required |
**options
|
Passed on to tifffile's |
required |
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
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
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
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
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. |
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 If it is |
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
|
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 |
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.
sniff_fileobj
classmethod
Score how confident the class is that an open file holds a TIFF
image: LIKELY for any TIFF or BigTIFF header. A pyramidal series
is claimed more confidently by
TiffMultiScaleImage,
unless a level is asked for.
from_source
classmethod
from_source(
source: TiffSource,
series: int = 0,
level: int | None = None,
pixel_size: Any = None,
unit: Any = None,
origin: Any = None,
mmap: bool = True,
lazy: bool | None = None,
**kwargs,
) -> Self
Read one level of one series of a TIFF file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
TiffSource
|
Where the file is. |
required |
series
|
int
|
The series to read (default: the first). Negative values count from the end. |
0
|
level
|
int
|
The pyramid level to read: 0 (the default) is the full
resolution. A level is placed so that it covers the same extent
as the full-resolution one (see |
None
|
pixel_size
|
float | Sequence[float] | Mapping[str, float]
|
The pixel size, which overrides the file's: one size, one per
spatial axis ( |
None
|
unit
|
str | Unit
|
The unit of |
None
|
origin
|
bool | float | Sequence[float] | Mapping[str, float]
|
The position of the first pixel, in the unit of the pixel size,
which overrides the file's (OME plane positions). |
None
|
mmap
|
bool
|
Memory-map the pixels when the file is local and uncompressed (the default). |
True
|
lazy
|
bool
|
Read the pixels as a dask array over tifffile's Zarr store (this needs dask and zarr). By default, only when dask is the array backend. |
None
|
Raises:
| Type | Description |
|---|---|
ParserContentError
|
If the file cannot be read as a TIFF file. |
IndexError
|
If it has no such series or level. |
TiffMultiScaleImage
magic
TiffMultiScaleImage(
dialect: str | None = None,
ome_xml: str | None = None,
imagej_metadata: dict[str, Any] | None = None,
tags: dict[str, Any] | None = None,
series: int | None = None,
n_series: int | None = None,
storage_axes: str | None = None,
)
Bases: _TiffMixin, BinaryFileParserWriter, WritableFileBasedImage, MultiScaleImage
A pyramidal TIFF series -- OME-TIFF or plain TIFF with SubIFDs, or any
pyramid tifffile recognizes (series.levels) -- as a multiscale image.
Each level is a TiffImage,
finest first, whose pixels are read when its data is first accessed.
Every level maps its pixels onto the same "physical" system, so the
pyramid's own transformations are empty (the identity), as for an
OME-Zarr pyramid that declares no common transformation.
A level's pixel size is the base pixel size times its downsampling
factor, the ratio of the base shape to its own along each axis. Levels
are aligned by their extent: the edges of a level's first and last
pixels coincide with those of the base level, so pixel i of a level
downsampled by f is centred on the base level's pixel coordinate
f * i + (f - 1) / 2, the centre of the block of base pixels it
summarizes. This is the convention of block-averaged pyramids (and of
OME-Zarr pyramids whose levels carry the matching translation).
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.
grid
property
grid: CartesianField
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
The geometry of the highest-resolution image in the pyramid.
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.
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
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 |
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: BinaryContentLike,
error: bool | Type[Exception] = False,
**kwargs,
) -> float
Score how confident the class is that bytes hold a TIFF file.
sniff_text
classmethod
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
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
On a dispatcher, pick the best-matching registered format and build an instance of it from the file (path or file-like object). On a concrete format, build an instance of this class from the file.
from_filename
classmethod
from_filename(filename: FilenameLike, **kwargs) -> Self
Read the image from a file.
A local file is reopened by name when the pixels are read, so they
can be memory-mapped. A remote file is read into memory. See
from_source for the options.
from_fileobj
classmethod
Read the image from an open binary file, which is read into
memory and left where it was. See from_source for the
options.
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: BinaryContentLike, **kwargs) -> Self
Read the image from the bytes of a file. See from_source for
the options.
from_text
classmethod
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
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
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 file (path or file-like object).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
FileLike
|
The file to write to. |
required |
**kwargs
|
Parser-specific options. |
{}
|
to_filename
to_filename(filename: FilenameLike, **kwargs) -> None
Write the image to a file. A name ending in .ome.tif or
.ome.tiff asks for OME-TIFF. See to_bytes for the options.
What will be written is worked out before the file is opened, so an image that cannot be written leaves no file behind. A local file is written by tifffile directly.
to_fileobj
to_fileobj(file: IO, **kwargs) -> None
Write the image to an open binary file. Its name, if it has one,
chooses the dialect as in to_bytes.
to_bytes
to_bytes(**kwargs) -> bytes
Encode the image as a TIFF file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dialect
|
(ome, imagej, plain)
|
The metadata to write. By default: OME-TIFF if |
"ome"
|
name
|
str
|
The name of the file, which may ask for OME-TIFF. |
required |
bigtiff
|
bool
|
Write a BigTIFF file. By default, only when the data is too large for a classic TIFF file (4 GiB). |
required |
**options
|
Passed on to tifffile's |
required |
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
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
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
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
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. |
to_singlescale
to_singlescale(index: int = 0) -> SingleScaleImage
Return one of the levels as a single-resolution image.
reslice
reslice(
geometry: Image
| 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 highest-resolution level 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 If it is |
None
|
intrinsic
|
Geometry | Transformation | None
|
An optional transformation that defines the intrinsic geometry of the highest-resolution image in the output pyramid. If provided, it is used to compute the geometry of each level in the output pyramid. If not provided, this function returns a single-scale image instead. |
required |
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
|
False
|
Returns:
| Type | Description |
|---|---|
SingleScaleImage
|
The resliced image. |
__call__
__call__(transform: Transformation) -> Self
Apply a transformation to the multi-scale image.
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 "intrinsic-to-world"
transformation is defined as
|
required |
Returns:
| Type | Description |
|---|---|
MultiScaleImage
|
The transformed image. |
sniff_fileobj
classmethod
sniff_fileobj(
file: IO,
error: bool | Type[Exception] = False,
series: int = 0,
level: int | None = None,
**kwargs,
) -> float
Score how confident the class is that an open file holds a
pyramid: CERTAIN when the series asked for (the first by
default) has several levels and no level is asked for, and NO
otherwise.
A whole-slide image of a microscope vendor (Aperio SVS, Hamamatsu
NDPI, Philips, Leica SCN, Ventana BIF) scores a little less than
CERTAIN (still more than a single-scale
TiffImage), so that the
dedicated OpenSlide reader of that vendor, when it is installed,
takes it (see brainhops.io.images.openslide).
from_source
classmethod
from_source(
source: TiffSource,
series: int = 0,
pixel_size: Any = None,
unit: Any = None,
origin: Any = None,
mmap: bool = True,
lazy: bool | None = None,
**kwargs,
) -> Self
Read every level of one series of a TIFF file. The options are
those of TiffImage
.from_source, but for level.