brainhops.datamodel.images
Single-scale and multi-scale images, and reslicing them.
Attributes
LabelTable
module-attribute
A table from the values of a label map to their Label.
LabelsLike
module-attribute
LabelsLike: TypeAlias = bool | LabelTable | None
The values that the labels property of an image can take.
Classes
Label
Bases: NamedTuple
The name and the colour of one value of a label map.
A label map is an image whose values are integers that each stand
for a region or a class, such as a segmentation or an atlas. A
LabelTable gives a Label to each value whose name is known.
Example
Image
magic
Image(
*,
metadata: NoRepr[Metadata | None] = None,
labels: NoRepr[LabelsLike] = None,
)
Bases: BackendsMixin, ComparesByIdMixin, DataModelBase
The base class of all images.
Note
Images compare and hash by identity: a == b means a is b,
even for images with the same data and transformations, and
== never raises. Images can therefore be used in sets and as
dictionary keys. To compare the contents of two images, compare
their data explicitly, for example with numpy.array_equal(a, b),
and compare their geometries.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metadata
|
NoRepr[Metadata | None]
|
What describes the image beyond its data and geometry. |
None
|
labels
|
NoRepr[LabelsLike]
|
Whether the image is a label map, as it was given (see |
None
|
Attributes
metadata
class-attribute
instance-attribute
What describes the image beyond its data and geometry.
dtype
class-attribute
instance-attribute
dtype = alias('data.dtype', readonly=True)
The data type of the data.
grid
class-attribute
instance-attribute
grid = alias('geometry.grid', readonly=True)
The Cartesian field that defines the sampling grid.
transformation
property
writable
transformation: Transformation
The preferred transformation, which is always the last in the
transformations list.
When the list is empty, this property return an Identity.
Assigning a transformation makes it the preferred one:
- if the assigned value is an integer, the transformation at that index is selected and moved to the end of the list;
- if the assigned value is a string, the transformation whose output system has that name is selected and moved to the end of the list. When several output systems have that name, the transformation closest to the end of the list is selected, so that the preferred transformation stays preferred if it matches;
- if the assigned value is a transformation that is already in the list, it is moved to the end of the list;
- if it is a new transformation, it is appended to the list.
An unknown index or system name raises a KeyError.
Example
>>> voxel = CoordinateSystem(["i", "j", "k"], name="voxel")
>>> phys = CoordinateSystem(["x", "y", "z"], name="phys")
>>> world = CoordinateSystem(["x", "y", "z"], name="world")
>>> aligned = CoordinateSystem(["x", "y", "z"], name="aligned")
>>>
>>> vox2scanner = Affine(input=voxel, output=phys)
>>> vox2world = Affine(input=voxel, output=world)
>>> vox2aligned = Affine(input=voxel, output=aligned)
>>>
>>> img = SingleScaleImage(data, [vox2scanner, vox2world])
>>> img.transformation.output
CoordinateSystem(name='world', axes=['x', 'y', 'z'])
>>>
>>> img.transformation = 0
>>> img.transformation.output
CoordinateSystem(name='phys', axes=['x', 'y', 'z'])
>>>
>>> img.transformation = "world"
>>> img.transformation.output
CoordinateSystem(name='world', axes=['x', 'y', 'z'])
>>>
>>> img.transformation = vox2aligned
>>> img.transformation.output
CoordinateSystem(name='aligned', axes=['x', 'y', 'z'])
>>>
>>> [t.output.name for t in img.transformations]
['phys', 'world', 'aligned']
Methods:
labels
labels() -> LabelsLike
Whether the image is a label map, and the names of its labels.
A label map is an image whose values are integers that each stand for a region or a class, such as a segmentation. Code that resamples an image reads this property to avoid averaging labels. The property takes one of four values.
Nonewhen it is not known whether the image is a label map.Falsewhen the image is known not to be a label map.Truewhen the image is a label map whose names are not known.- A
LabelTablewhen the names of the labels are known. The table is never empty.
A value given to the constructor or assigned to the property is
returned as it is. Otherwise the value is derived from the
intent field of the metadata: the intents label and
neuroname give True, any other intent gives False, and an
image without an intent gives None. A multi-scale image that
was given no value takes the value of its finest level. Assigning
None restores the derived value. The data are never read to
find the values that they hold.
__array__
Convert the data to a NumPy array, optionally of a given type.
from_dict
classmethod
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 |
from_any
classmethod
Build an instance from a mapping, a data model or an argument.
This constructors dispatches to from_dict, from_instance
or the constructor, depending on the type of other.
Raises:
| Type | Description |
|---|---|
TypeError
|
If a mapping has a key that names no field. Unlike
|
to_backend
to_backend(
backend: BackendLike | None = None,
*,
device: DeviceLike | None = None,
) -> ArrayProtocol | None
Return the data as a bare array of the backend of a setting.
The object does not change. Small parameters, such as the matrix
of an affine transformation, are converted too, since the caller
asks for them. An object without data, such as the identity,
gives None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
str | module
|
The setting. By default, the current setting is used. |
None
|
device
|
str | int
|
The device for converted arrays. The backend supplies its default. |
None
|
Returns:
| Type | Description |
|---|---|
array | None
|
The data. |
as_backend
as_backend(
backend: BackendLike | None = None,
*,
device: DeviceLike | None = None,
inplace: bool = False,
) -> Self
Return the object with its data converted to the requested backend.
By default, the object holds no voxels and is returned as it is. Small parameters stay NumPy arrays where they are stored, so that code can convert a list of objects without testing their type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
str | module
|
The setting. By default, the current setting is used. |
None
|
device
|
str | int
|
The device for converted arrays. The backend supplies its default. |
None
|
inplace
|
bool
|
Whether this object holds the converted data and is returned, instead of a new object. |
False
|
Returns:
| Type | Description |
|---|---|
object
|
An object of the same class. |
to_cupy
Return the data as a CuPy array on the GPU.
to_dask
Return the data as a Dask array, without reading them.
as_numpy
Return the object with its data as NumPy arrays.
On an object read from a file, as_numpy(inplace=True) reads the
file once and keeps its values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inplace
|
bool
|
Whether this object holds the converted data and is returned. |
False
|
Returns:
| Type | Description |
|---|---|
object
|
An object of the same class. |
as_cupy
Return the object with its data as CuPy arrays on the GPU.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
str | int | None
|
The device, such as |
None
|
inplace
|
bool
|
Whether this object holds the converted data and is returned. |
False
|
Returns:
| Type | Description |
|---|---|
object
|
An object of the same class. |
as_dask
Return the object with its data as Dask arrays.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
str | int | None
|
The device, such as |
None
|
inplace
|
bool
|
Whether this object holds the converted data and is returned. |
False
|
Returns:
| Type | Description |
|---|---|
object
|
An object of the same class. |
SingleScaleImage
magic
SingleScaleImage(
data: ArrayProtocol | None = None,
transformations: list[Transformation] = (),
frames: NoRepr[Any] = (),
*,
metadata: NoRepr[Metadata | None] = None,
labels: NoRepr[LabelsLike] = None,
)
Bases: Image
The base class of single-resolution images.
data and transformations are the parameters most often given
to the constructor, and they can be passed by position in this order.
The other parameters are keyword-only, except those that a file
reader from brainhops.io.common adds, such as the opened Zarr
node of a plain Zarr array, which follow transformations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
ArrayProtocol | None
|
The image data. Must be an array-like object that supports the array protocol (e.g. numpy, cupy or dask array). |
None
|
transformations
|
list[Transformation]
|
A list of transformations from voxel space (i.e., in terms of data's axes) to different world spaces. The last transformation in the list is the preferred one. |
()
|
frames
|
NoRepr[Any]
|
The frames of the values, as they were given (see |
()
|
metadata
|
NoRepr[Metadata | None]
|
What describes the image beyond its data and geometry. |
None
|
labels
|
NoRepr[LabelsLike]
|
Whether the image is a label map, as it was given (see |
None
|
Attributes
data
class-attribute
instance-attribute
The image data, as the image stores them.
An image built from an array returns that array, whatever the
backend setting. An image read from a file returns a lazy array of
the file (see ArrayProxy),
which reads nothing until a computation needs its values, unless an
array was assigned as data. Its shape, and a part of it, such as
image.data[0], are therefore had without reading the whole file.
The backend setting applies when a computation reads the array, and
the to_* and as_* methods convert it on request.
transformations
class-attribute
instance-attribute
transformations: NotKwOnly[list[Transformation]] = ()
A list of transformations from voxel space (i.e., in terms of data's axes) to different world spaces.
The last transformation in the list is the preferred one.
frames
property
writable
The frame of the values along each axis.
Some axes hold the components of points, vectors or tensors, and
the type of such an axis says which (see
[ComponentAxis][brainhops.datamodel.axes.ComponentAxis]). The
components are expressed in a coordinate system, called the frame
of the values, and each axis has one slot that records it:
Noneis the array system of the image, so that the components are in voxel units along the axes of the data. This is the default.- A transformation maps the array system to the frame. It is
often an entry of
transformations, such as the map to scanner RAS for a file that stores its vectors in RAS. - A coordinate system names a foreign frame, which belongs to another space that no transformation of the image reaches. The values along such an axis are never re-expressed.
Only a component axis can have a frame. The constructor and the
setter also accept a mapping from axis names or indices to slots,
and an empty tuple, which leaves every slot None.
A stored transformation corresponds exactly to the components: the outputs that no component axis of the array feeds are as many as the components, which follow them in order. A transformation that is given with more such outputs, such as a map that also carries a time axis along, is restricted to the outputs that share one axis type, when exactly one type has as many outputs as there are components. A projection that removes the other outputs is then composed onto the transformation.
Lazily applying a transformation keeps the frames, because the
values do not change. Indexing and reslicing compose each frame
with the map of the voxels, so that the values keep their meaning
without being rotated. reframe re-expresses the values in
another frame. The design is recorded in
spec/design/vector-and-tensor-images.md.
Raises:
| Type | Description |
|---|---|
TypeError
|
If a slot is neither a transformation, a coordinate system nor
|
ValueError
|
If there is not one slot per axis, if an axis that is not a component axis has a frame, or if a transformation does not tell which of its axes the components follow. |
KeyError
|
If a mapping names an axis that does not exist. |
geometry
property
geometry: Geometry
The geometry of the image.
The geometry pairs the Cartesian field matching the data shape with the preferred voxel-to-world transformation. Any image can be resliced onto this geometry.
metadata
class-attribute
instance-attribute
What describes the image beyond its data and geometry.
dtype
class-attribute
instance-attribute
dtype = alias('data.dtype', readonly=True)
The data type of the data.
grid
class-attribute
instance-attribute
grid = alias('geometry.grid', readonly=True)
The Cartesian field that defines the sampling grid.
transformation
property
writable
transformation: Transformation
The preferred transformation, which is always the last in the
transformations list.
When the list is empty, this property return an Identity.
Assigning a transformation makes it the preferred one:
- if the assigned value is an integer, the transformation at that index is selected and moved to the end of the list;
- if the assigned value is a string, the transformation whose output system has that name is selected and moved to the end of the list. When several output systems have that name, the transformation closest to the end of the list is selected, so that the preferred transformation stays preferred if it matches;
- if the assigned value is a transformation that is already in the list, it is moved to the end of the list;
- if it is a new transformation, it is appended to the list.
An unknown index or system name raises a KeyError.
Example
>>> voxel = CoordinateSystem(["i", "j", "k"], name="voxel")
>>> phys = CoordinateSystem(["x", "y", "z"], name="phys")
>>> world = CoordinateSystem(["x", "y", "z"], name="world")
>>> aligned = CoordinateSystem(["x", "y", "z"], name="aligned")
>>>
>>> vox2scanner = Affine(input=voxel, output=phys)
>>> vox2world = Affine(input=voxel, output=world)
>>> vox2aligned = Affine(input=voxel, output=aligned)
>>>
>>> img = SingleScaleImage(data, [vox2scanner, vox2world])
>>> img.transformation.output
CoordinateSystem(name='world', axes=['x', 'y', 'z'])
>>>
>>> img.transformation = 0
>>> img.transformation.output
CoordinateSystem(name='phys', axes=['x', 'y', 'z'])
>>>
>>> img.transformation = "world"
>>> img.transformation.output
CoordinateSystem(name='world', axes=['x', 'y', 'z'])
>>>
>>> img.transformation = vox2aligned
>>> img.transformation.output
CoordinateSystem(name='aligned', axes=['x', 'y', 'z'])
>>>
>>> [t.output.name for t in img.transformations]
['phys', 'world', 'aligned']
Methods:
reslice
reslice(
geometry: _GeometryLike | None = None,
degree: InterpolationLike | None = None,
bound: BoundaryLike = "reflect",
coeff: bool = False,
copy: bool = False,
*,
clip: Clip = None,
dtype: DTypeLike | None = None,
reframe: bool | ReframeMethodOrCallable = False,
frame: FrameTargets = -1,
) -> SingleScaleImage
Resample the data onto another geometry.
The values along an axis that holds vectors or tensors are
sampled without being rotated: each of their
frames is
composed with the map of the voxels, so that the values keep
their meaning. With reframe, the values are then re-expressed
in the frame frame of the result, as by reframe.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
geometry
|
Image or Geometry or Transformation
|
The target voxel-to-world geometry. An image or a geometry also determines the output shape, whereas a bare transformation keeps the current shape. By default, the image is resampled onto its ow geometry. |
None
|
degree
|
int
|
Spline degree, from 0 (nearest neighbour) up to 7.
A degree of 1 gives linear interpolation. By default, the
degree is 0 for a label map, whose |
None
|
bound
|
str or float
|
Boundary condition, which says how the data continues beyond
its edges. A float is a constant value beyond the edges. The
strings are the following names, and their aliases listed in
|
"reflect"
|
coeff
|
bool
|
Whether the data already holds spline coefficients. If false, the data is prefiltered before interpolation. |
False
|
copy
|
bool
|
If true, the output never shares memory with the input.
If false, a reslicing that only rearranges existing voxels,
such as a flip, a permutation or a slice with a unit step,
may return a view, as |
False
|
clip
|
float, pair, sequence of pairs, or None
|
A scalar sets symmetric margins. A |
None
|
dtype
|
DTypeLike
|
Output dtype. None preserves the input dtype. A floating dtype retains interpolated fractions of integer input. An explicit dtype promotes the input and output dtypes to choose working precision, with a minimum of float32. Integer-only combinations use float64. Integer output keeps rounding half away from zero and saturation. Dask arrays remain lazy. |
None
|
reframe
|
bool | ReframeMethod | str | callable
|
Whether and how the values of vector and tensor axes are
re-expressed after they are sampled. |
False
|
frame
|
int or str or Transformation or None or dict
|
The frame in which the values are re-expressed when |
-1
|
Returns:
| Type | Description |
|---|---|
SingleScaleImage
|
The resliced image. Its metadata is derived from the metadata
of this image with a |
reframe
reframe(
frame: FrameTargets = -1,
*,
method: ReframeMethodOrCallable = "jacobian",
) -> SingleScaleImage
Re-express the values of vectors and tensors in another frame.
Some axes hold the components of vectors or tensors, expressed in
a frame that
frames
records. This method changes that frame. With the default
arguments, the values are re-expressed in the world of the
preferred transformation, which is what a writer or a viewer of
the image expects. No voxel moves.
If the values are in the frame F and are re-expressed in the
frame F′, the components at each voxel x are changed by
where D is the Jacobian, which is the linear part of a map that
is affine. The type and the valence of the axis say how the
components change (see
[ComponentAxis][brainhops.datamodel.axes.ComponentAxis]): each
vector index is multiplied by J and each covector index by
J⁻ᵀ, so that a vector becomes J v, a gradient becomes
J⁻ᵀ g and a diffusion tensor becomes J T Jᵀ. A tensor stored
in a layout with components that are zero by construction is
stored in a closed layout afterwards (see
[TensorAxis][brainhops.datamodel.axes.TensorAxis]), which
changes the length of its axis. The coordinates of points cannot
be re-expressed this way.
The components follow some axes of the system of their frame, in
order, and these axes are read from the structure of the frame,
not from the types of the axes. They are the outputs of the frame
that no component axis of the array feeds, and a stored frame has
exactly one such output per component. A frame given as frame
that has more of them is first restricted to the outputs that
share one axis type, as the setter of
frames
does. The Jacobian is taken along the axes of the array that the
frame maps onto these outputs, and the two frames of a change
must map the same axes of the array. The array system takes the
axes of the other frame.
The Jacobian of a map that is not affine is computed by finite differences between the voxels: central inside the image and one-sided at its edges. Along an axis of one voxel, the fields of the map are taken to be constant.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frame
|
int or str or Transformation or None or dict
|
The new frame. An integer selects an entry of
|
-1
|
method
|
ReframeMethod | str | callable
|
What is applied to the values. |
"jacobian"
|
Returns:
| Type | Description |
|---|---|
SingleScaleImage
|
The image with its values re-expressed, the same
transformations, and its new frames. The image itself is
returned when no value changes frame. Its metadata is derived
from the metadata of this image with a |
Raises:
| Type | Description |
|---|---|
KeyError
|
If a frame names a system that no transformation ends in, or if a dictionary names an axis that does not exist. |
ValueError
|
If a dictionary names an axis that is not a component axis or that has a foreign frame, if the frames do not tell which of their axes the components follow, or if they map different axes of the array onto them. |
NotImplementedError
|
If the values of an axis whose frame changes are the coordinates of points. |
__call__
__call__(
transformation: Transformation,
) -> SingleScaleImage
Apply a transformation lazily, without reslicing.
The output space of transform should match the output space of
the preferred transformation. The new preferred transformation,
transform.inverse() @ self.transformation, is appended to the
existing ones. No voxel moves, so the new image shares the
metadata and the frames of this image.
__getitem__
__getitem__(index: CartesianIndex) -> SingleScaleImage
Index the data, keeping every transformation consistent with it.
The metadata is derived from the metadata of this image with an
Indexed record (see
Metadata.derive).
An index along a time or a channel axis keeps the entries of the
fields that run along that axis at the positions that it keeps,
and an index of a spatial axis, or of an axis of unknown type,
clears the fields tied to the spatial sampling and maps an
encoding direction given in voxel axes. "getitem" is appended
to history, and the metadata keeps its class and its record.
The frames
of the values are composed with the map from the indexed voxels
to the original ones, so the values are not changed. A component
axis stays a component axis only when it is indexed with its full
range in order. Otherwise its remaining entries are no longer the
components of one object, so it becomes a channel axis and loses
its frame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
[tuple of] (int | slice | None)
|
The index, as for the data array. A tuple may contain
integers, slices, |
required |
Returns:
| Type | Description |
|---|---|
SingleScaleImage
|
The indexed image. |
from_dict
classmethod
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 |
from_any
classmethod
Build an instance from a mapping, a data model or an argument.
This constructors dispatches to from_dict, from_instance
or the constructor, depending on the type of other.
Raises:
| Type | Description |
|---|---|
TypeError
|
If a mapping has a key that names no field. Unlike
|
to_backend
to_backend(
backend: BackendLike | None = None,
*,
device: DeviceLike | None = None,
) -> ArrayProtocol | None
Return the data as a bare array of the backend of a setting.
The object does not change. Small parameters, such as the matrix
of an affine transformation, are converted too, since the caller
asks for them. An object without data, such as the identity,
gives None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
str | module
|
The setting. By default, the current setting is used. |
None
|
device
|
str | int
|
The device for converted arrays. The backend supplies its default. |
None
|
Returns:
| Type | Description |
|---|---|
array | None
|
The data. |
to_cupy
Return the data as a CuPy array on the GPU.
to_dask
Return the data as a Dask array, without reading them.
as_numpy
Return the object with its data as NumPy arrays.
On an object read from a file, as_numpy(inplace=True) reads the
file once and keeps its values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inplace
|
bool
|
Whether this object holds the converted data and is returned. |
False
|
Returns:
| Type | Description |
|---|---|
object
|
An object of the same class. |
as_cupy
Return the object with its data as CuPy arrays on the GPU.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
str | int | None
|
The device, such as |
None
|
inplace
|
bool
|
Whether this object holds the converted data and is returned. |
False
|
Returns:
| Type | Description |
|---|---|
object
|
An object of the same class. |
as_dask
Return the object with its data as Dask arrays.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
str | int | None
|
The device, such as |
None
|
inplace
|
bool
|
Whether this object holds the converted data and is returned. |
False
|
Returns:
| Type | Description |
|---|---|
object
|
An object of the same class. |
labels
labels() -> LabelsLike
Whether the image is a label map, and the names of its labels.
A label map is an image whose values are integers that each stand for a region or a class, such as a segmentation. Code that resamples an image reads this property to avoid averaging labels. The property takes one of four values.
Nonewhen it is not known whether the image is a label map.Falsewhen the image is known not to be a label map.Truewhen the image is a label map whose names are not known.- A
LabelTablewhen the names of the labels are known. The table is never empty.
A value given to the constructor or assigned to the property is
returned as it is. Otherwise the value is derived from the
intent field of the metadata: the intents label and
neuroname give True, any other intent gives False, and an
image without an intent gives None. A multi-scale image that
was given no value takes the value of its finest level. Assigning
None restores the derived value. The data are never read to
find the values that they hold.
MultiScaleImage
magic
MultiScaleImage(
images: list[SingleScaleImage] = (),
transformations: list[Transformation] = (),
*,
metadata: NoRepr[Metadata | None] = None,
labels: NoRepr[LabelsLike] = None,
)
Bases: Image, Multiscale[SingleScaleImage]
The base class of multi-scale (pyramid) images.
images and transformations are the parameters most often given
to the constructor, and they can be passed by position in this order.
The other parameters are keyword-only, except those that a file
reader from brainhops.io.common adds, such as the opened Zarr
node of an OME-Zarr pyramid, which follow transformations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
images
|
list[SingleScaleImage]
|
Each image in the multi-resolution pyramid, ordered from highest to lowest resolution. |
()
|
transformations
|
list[Transformation]
|
A list of transformations from each level's preferred space to different world spaces. The last transformation in the list is the preferred one. |
()
|
metadata
|
NoRepr[Metadata | None]
|
What describes the image beyond its data and geometry. |
None
|
labels
|
NoRepr[LabelsLike]
|
Whether the image is a label map, as it was given (see |
None
|
Attributes
images
class-attribute
instance-attribute
images: NotKwOnly[list[SingleScaleImage]] = ()
Each image in the multi-resolution pyramid, ordered from highest to lowest resolution.
transformations
class-attribute
instance-attribute
transformations: NotKwOnly[list[Transformation]] = ()
A list of transformations from each level's preferred space to different world spaces.
The last transformation in the list is the preferred one.
scales
property
scales: list[SingleScaleImage]
The pyramid levels, from highest to lowest resolution.
geometry
property
geometry: Geometry
The geometry of the highest-resolution level.
The geometry pairs the grid of the highest-resolution level with the preferred transformation of the pyramid, composed with that level's own transformation.
BUILDS_SCALES
class-attribute
BUILDS_SCALES: bool = False
Whether converting a single scale builds the coarser scales.
When it is true, a conversion to this class from a single-scale
object builds as many scales as with_scales() builds, unless
nscales= says otherwise. The formats of OME-Zarr set it.
WRITES_SCALES
class-attribute
WRITES_SCALES: bool = False
Whether the writer builds the coarser scales of a single scale.
When it is true, io.save gives the options of a pyramid to the
writer of this class rather than to the conversion, when it saves a
single scale. The writer then writes the finest scale, and builds
each coarser scale from the scales that it has written, read back
from the store. The formats of OME-Zarr set it.
metadata
class-attribute
instance-attribute
What describes the image beyond its data and geometry.
dtype
class-attribute
instance-attribute
dtype = alias('data.dtype', readonly=True)
The data type of the data.
grid
class-attribute
instance-attribute
grid = alias('geometry.grid', readonly=True)
The Cartesian field that defines the sampling grid.
transformation
property
writable
transformation: Transformation
The preferred transformation, which is always the last in the
transformations list.
When the list is empty, this property return an Identity.
Assigning a transformation makes it the preferred one:
- if the assigned value is an integer, the transformation at that index is selected and moved to the end of the list;
- if the assigned value is a string, the transformation whose output system has that name is selected and moved to the end of the list. When several output systems have that name, the transformation closest to the end of the list is selected, so that the preferred transformation stays preferred if it matches;
- if the assigned value is a transformation that is already in the list, it is moved to the end of the list;
- if it is a new transformation, it is appended to the list.
An unknown index or system name raises a KeyError.
Example
>>> voxel = CoordinateSystem(["i", "j", "k"], name="voxel")
>>> phys = CoordinateSystem(["x", "y", "z"], name="phys")
>>> world = CoordinateSystem(["x", "y", "z"], name="world")
>>> aligned = CoordinateSystem(["x", "y", "z"], name="aligned")
>>>
>>> vox2scanner = Affine(input=voxel, output=phys)
>>> vox2world = Affine(input=voxel, output=world)
>>> vox2aligned = Affine(input=voxel, output=aligned)
>>>
>>> img = SingleScaleImage(data, [vox2scanner, vox2world])
>>> img.transformation.output
CoordinateSystem(name='world', axes=['x', 'y', 'z'])
>>>
>>> img.transformation = 0
>>> img.transformation.output
CoordinateSystem(name='phys', axes=['x', 'y', 'z'])
>>>
>>> img.transformation = "world"
>>> img.transformation.output
CoordinateSystem(name='world', axes=['x', 'y', 'z'])
>>>
>>> img.transformation = vox2aligned
>>> img.transformation.output
CoordinateSystem(name='aligned', axes=['x', 'y', 'z'])
>>>
>>> [t.output.name for t in img.transformations]
['phys', 'world', 'aligned']
Methods:
to_singlescale
to_singlescale(index: int = 0) -> SingleScaleImage
Return a level as a single-scale image in world space.
reslice
reslice(
geometry: _GeometryLike | None = None,
degree: InterpolationLike | None = None,
bound: BoundaryLike = "reflect",
coeff: bool = False,
copy: bool = False,
*,
clip: Clip = None,
dtype: DTypeLike | None = None,
reframe: bool | ReframeMethodOrCallable = False,
frame: FrameTargets = -1,
) -> SingleScaleImage
Reslice the level whose voxel size best matches the target grid.
The method always returns a single-scale image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
geometry
|
Image or Geometry or Transformation
|
The target geometry, interpreted as in
|
None
|
degree
|
int
|
Spline degree, from 0 (nearest neighbour) up to 7. A degree of 1
gives linear interpolation. By default, the degree is 0 for a
label map, whose |
None
|
bound
|
str or float
|
Boundary condition, which says how the data continues beyond
its edges. A float is a constant value beyond the edges. The
strings are the following names, and their aliases listed in
|
"reflect"
|
coeff
|
bool
|
Whether the data already holds spline coefficients. If false, the data is prefiltered before interpolation. |
False
|
copy
|
bool
|
If true, the output never shares memory with the input. If false,
a reslicing that only rearranges existing voxels, such as a flip,
a permutation or a slice with a unit step, may return a view, as
|
False
|
clip
|
float, pair, sequence of pairs, or None
|
A scalar sets symmetric margins. A |
None
|
dtype
|
DTypeLike
|
Output dtype, as in |
None
|
reframe
|
bool | ReframeMethod | str | callable
|
Whether and how the values of vector and tensor axes are
re-expressed, as in |
False
|
frame
|
int or str or Transformation or None or dict
|
The frame in which the values are re-expressed, as in
|
-1
|
Returns:
| Type | Description |
|---|---|
SingleScaleImage
|
The resliced image. |
__call__
__call__(transform: Transformation) -> MultiScaleImage
Apply a transformation to the pyramid lazily, without reslicing.
The transformation is handled as in SingleScaleImage.
from_dict
classmethod
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 |
from_any
classmethod
Build an instance from a mapping, a data model or an argument.
This constructors dispatches to from_dict, from_instance
or the constructor, depending on the type of other.
Raises:
| Type | Description |
|---|---|
TypeError
|
If a mapping has a key that names no field. Unlike
|
with_scales
with_scales(
scales: None = None,
*,
factor: FactorLike | None = None,
mode: str | None = None,
align: str = DEFAULT_ALIGN,
min_size: int = MIN_SIZE,
strict: bool = False,
) -> Self
with_scales(
scales: int,
*,
factor: FactorLike | None = None,
mode: str | None = None,
align: str = DEFAULT_ALIGN,
min_size: int = MIN_SIZE,
strict: bool = False,
) -> Self
with_scales(
scales: Sequence[FactorLike],
*,
mode: str | None = None,
align: str = DEFAULT_ALIGN,
) -> Self
Return a copy with the given scales, finest first.
A pyramid lets a viewer that shows a large image whole, or an algorithm that works from coarse to fine, read a coarse scale instead of the finest one. This method gives a multiscale object the scales that it should have. The finest scale is always kept.
scales is read by its type:
None, the default, builds as many scales as the rules allow.- An int is the number of scales, the finest one included. When
the rules stop before, fewer scales are built, unless
strictis true. - A sequence of factors gives, for each coarser scale, its
factor from the finest scale along each axis, in a form that
FactorLikedescribes. The factors are positive integers, and the factor of an axis never decreases from a scale to the next. - A sequence of scales, such as single-scale images for an image, is the complete list of scales, finest first, which the copy takes as they are. They must be ordered from fine to coarse and share one world space.
The rules build the scales step by step. At each step, an axis
is downsampled by its factor of factor, which is 2 for the
spatial axes and 1, which leaves an axis as it is, for the other
axes by default. An axis is downsampled while it has more than
min_size voxels, even when its next scale has fewer, so that
an axis of 40 voxels becomes an axis of 20 voxels and an axis of
32 voxels stays as it is. The rules stop when no axis can be
downsampled. An axis whose voxels are more than sqrt(f) times
larger than the smallest voxels of the axes that can still be
downsampled waits, so that anisotropic voxels become roughly
isotropic first.
A scale is computed from the scale before it whenever its
factors are multiples of the factors of that scale, and from the
finest scale otherwise, or always in the mode "nearest", which
picks the voxels of the finest scale. A coarser scale that the
object already holds is kept when its factors, its placement and
its shape are those that are asked for, and the scales after it
are built from it. The voxels of a scale lie where align says,
and its values are computed as mode says, as
brainhops._core.pyramids explains.
Example
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scales
|
int or sequence
|
The number of scales, the factors of the coarser scales, or the list of scales. By default, as many scales as the rules allow. |
None
|
factor
|
int or sequence of int or mapping
|
The factor of each axis at each step of the rules, in a form
that |
None
|
mode
|
str
|
How a coarse voxel is computed from the voxels that it
covers, one of |
None
|
align
|
(exact, edges, centers)
|
How the voxels of a coarse scale are laid over those of the
finest scale. |
"exact"
|
min_size
|
int
|
The number of voxels at or below which the rules stop downsampling an axis. |
32
|
strict
|
bool
|
Whether to refuse to build fewer scales than an int |
False
|
Returns:
| Type | Description |
|---|---|
Self
|
The copy with its scales. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If |
KeyError
|
If no axis has a name that a factor gives. |
IndexError
|
If a position that a factor gives is out of range. |
to_backend
to_backend(
backend: BackendLike | None = None,
*,
device: DeviceLike | None = None,
) -> ArrayProtocol | None
Return the data as a bare array of the backend of a setting.
The object does not change. Small parameters, such as the matrix
of an affine transformation, are converted too, since the caller
asks for them. An object without data, such as the identity,
gives None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
str | module
|
The setting. By default, the current setting is used. |
None
|
device
|
str | int
|
The device for converted arrays. The backend supplies its default. |
None
|
Returns:
| Type | Description |
|---|---|
array | None
|
The data. |
to_cupy
Return the data as a CuPy array on the GPU.
to_dask
Return the data as a Dask array, without reading them.
as_numpy
Return the object with its data as NumPy arrays.
On an object read from a file, as_numpy(inplace=True) reads the
file once and keeps its values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inplace
|
bool
|
Whether this object holds the converted data and is returned. |
False
|
Returns:
| Type | Description |
|---|---|
object
|
An object of the same class. |
as_cupy
Return the object with its data as CuPy arrays on the GPU.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
str | int | None
|
The device, such as |
None
|
inplace
|
bool
|
Whether this object holds the converted data and is returned. |
False
|
Returns:
| Type | Description |
|---|---|
object
|
An object of the same class. |
as_dask
Return the object with its data as Dask arrays.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
str | int | None
|
The device, such as |
None
|
inplace
|
bool
|
Whether this object holds the converted data and is returned. |
False
|
Returns:
| Type | Description |
|---|---|
object
|
An object of the same class. |