Skip to content

Images API reference

Open an image

ngio.open_image

open_image(
    store: StoreOrGroup,
    path: str | None = None,
    pixel_size: PixelSize | None = None,
    strict: bool = False,
    axes_setup: AxesSetup | None = None,
    cache: bool = False,
    mode: AccessModeLiteral = "r+",
) -> Image

Open a single level image from an OME-Zarr image.

Parameters:

  • store (StoreOrGroup) –

    The Zarr store or group to create the image in.

  • path (str | None, default: None ) –

    The path to the image in the ome_zarr file.

  • pixel_size (PixelSize | None, default: None ) –

    Select the pyramid level whose pixel size matches this one. A lookup key, not a value to write; to set a pixel size see pixelsize on the create/derive entry points.

  • strict (bool, default: False ) –

    Only used if the pixel size is provided. If True, the pixel size must match the image pixel size exactly. If False, the closest pixel size level will be returned.

  • axes_setup (AxesSetup | None, default: None ) –

    Axes setup to load ome-zarr with non-standard axes configurations.

  • cache (bool, default: False ) –

    Whether to use a cache for the zarr group metadata.

  • mode (AccessModeLiteral, default: 'r+' ) –

    The access mode for the image. Defaults to "r+".

Source code in src/ngio/images/_ome_zarr_container.py
def open_image(
    store: StoreOrGroup,
    path: str | None = None,
    pixel_size: PixelSize | None = None,
    strict: bool = False,
    axes_setup: AxesSetup | None = None,
    cache: bool = False,
    mode: AccessModeLiteral = "r+",
) -> Image:
    """Open a single level image from an OME-Zarr image.

    Args:
        store (StoreOrGroup): The Zarr store or group to create the image in.
        path (str | None): The path to the image in the ome_zarr file.
        pixel_size: Select the pyramid level whose pixel size matches this one.
            A lookup key, not a value to write; to set a pixel size see
            `pixelsize` on the create/derive entry points.
        strict (bool): Only used if the pixel size is provided. If True, the
                pixel size must match the image pixel size exactly. If False, the
                closest pixel size level will be returned.
        axes_setup (AxesSetup | None): Axes setup to load ome-zarr with
            non-standard axes configurations.
        cache (bool): Whether to use a cache for the zarr group metadata.
        mode (AccessModeLiteral): The
            access mode for the image. Defaults to "r+".
    """
    group_handler = ZarrGroupHandler(store=store, cache=cache, mode=mode)
    images_container = ImagesContainer(group_handler, axes_setup=axes_setup)
    return images_container.get(
        path=path,
        pixel_size=pixel_size,
        strict=strict,
    )

Image

ngio.Image

Image(
    group_handler: ZarrGroupHandler,
    path: str,
    meta_handler: ImageMetaHandler,
)

Bases: AbstractImage

A class to handle a single image (or level) in an OME-Zarr image.

This class is meant to be subclassed by specific image types.

Initialize the Image at a single level.

Parameters:

  • group_handler (ZarrGroupHandler) –

    The Zarr group handler.

  • path (str) –

    The path to the image in the ome_zarr file.

  • meta_handler (ImageMetaHandler) –

    The image metadata handler.

Source code in src/ngio/images/_image.py
def __init__(
    self,
    group_handler: ZarrGroupHandler,
    path: str,
    meta_handler: ImageMetaHandler,
) -> None:
    """Initialize the Image at a single level.

    Args:
        group_handler: The Zarr group handler.
        path: The path to the image in the ome_zarr file.
        meta_handler: The image metadata handler.

    """
    super().__init__(
        group_handler=group_handler, path=path, meta_handler=meta_handler
    )
    # (meta generation, channels meta); same idea as `_dataset_cache`.
    self._channels_meta_cache: tuple[int, ChannelsMeta] | None = None

path property

path: str

Return the path of the image.

dataset property

dataset: Dataset

Return the dataset of the image.

dimensions property

dimensions: Dimensions

Return the dimensions of the image.

pixel_size property

pixel_size: PixelSize

Return the pixel size of the image.

axes_handler property

axes_handler: AxesHandler

Return the axes handler of the image.

axes_setup property

axes_setup: AxesSetup

Return the axes setup of the image.

axes property

axes: tuple[str, ...]

Return the axes of the image.

zarr_array property

zarr_array: Array

Return the Zarr array.

shape property

shape: tuple[int, ...]

Return the shape of the image.

dtype property

dtype: str

Return the dtype of the image.

chunks property

chunks: tuple[int, ...]

Return the chunks of the image.

write_granularity property

write_granularity: tuple[int, ...]

Return the atomic write unit of the on-disk array.

The shard shape when the array is sharded (writes are read-modify-writes of whole shard objects), otherwise the chunk shape.

is_3d property

is_3d: bool

Return True if the image is 3D.

is_2d property

is_2d: bool

Return True if the image is 2D.

is_time_series property

is_time_series: bool

Return True if the image is a time series.

is_2d_time_series property

is_2d_time_series: bool

Return True if the image is a 2D time series.

is_3d_time_series property

is_3d_time_series: bool

Return True if the image is a 3D time series.

is_multi_channels property

is_multi_channels: bool

Return True if the image is multichannel.

space_unit property

space_unit: str | None

Return the space unit of the image.

time_unit property

time_unit: str | None

Return the time unit of the image.

meta_handler property

meta_handler: ImageMetaHandler

Return the metadata handler.

meta property

meta: NgioImageMeta

Return the metadata.

channels_meta property

channels_meta: ChannelsMeta

Return the channels metadata.

Cached against the meta handler's generation, like dimensions: this sits on the hot path of every get_*/set_* with a channel_selection, where re-deriving cost a full metadata reload per call. The channel setters go through update_meta, which moves the generation, so a write through this image re-derives it.

channel_labels property

channel_labels: list[str]

Return the channels of the image.

wavelength_ids property

wavelength_ids: list[str | None]

Return the list of wavelength of the image.

num_channels property

num_channels: int

Return the number of channels.

has_axis

has_axis(axis: str) -> bool

Return True if the image has the given axis.

Source code in src/ngio/images/_abstract_image.py
def has_axis(self, axis: str) -> bool:
    """Return True if the image has the given axis."""
    return self.axes_handler.has_axis(axis)

set_space_unit

set_space_unit(unit: SpaceUnits = DefaultSpaceUnit) -> None

Set the unit of the spatial axes; the time unit is untouched.

Parameters:

  • unit (SpaceUnits, default: DefaultSpaceUnit ) –

    The space unit to set.

Source code in src/ngio/images/_abstract_image.py
def set_space_unit(self, unit: SpaceUnits = DefaultSpaceUnit) -> None:
    """Set the unit of the spatial axes; the time unit is untouched.

    Args:
        unit: The space unit to set.
    """
    meta = self._meta_handler.get_meta()
    meta = meta.to_units(space_unit=unit)
    self._meta_handler.update_meta(meta)

set_time_unit

set_time_unit(unit: TimeUnits = DefaultTimeUnit) -> None

Set the unit of the time axis; the space unit is untouched.

Parameters:

  • unit (TimeUnits, default: DefaultTimeUnit ) –

    The time unit to set.

Source code in src/ngio/images/_abstract_image.py
def set_time_unit(self, unit: TimeUnits = DefaultTimeUnit) -> None:
    """Set the unit of the time axis; the space unit is untouched.

    Args:
        unit: The time unit to set.
    """
    meta = self._meta_handler.get_meta()
    meta = meta.to_units(time_unit=unit)
    self._meta_handler.update_meta(meta)

set_axes_units

set_axes_units(
    space_unit: SpaceUnits = DefaultSpaceUnit,
    time_unit: TimeUnits = DefaultTimeUnit,
) -> None

Set BOTH the space and the time units of the image axes.

Note that both units are set on every call: an omitted parameter is set to its default, not left unchanged. To change one unit without touching the other, use set_space_unit / set_time_unit — which is also why this method is deprecated in their favour.

Parameters:

  • space_unit (SpaceUnits, default: DefaultSpaceUnit ) –

    The space unit of the image.

  • time_unit (TimeUnits, default: DefaultTimeUnit ) –

    The time unit of the image.

Source code in src/ngio/images/_abstract_image.py
@deprecated(replacement="set_space_unit() / set_time_unit()")
def set_axes_units(
    self,
    space_unit: SpaceUnits = DefaultSpaceUnit,
    time_unit: TimeUnits = DefaultTimeUnit,
) -> None:
    """Set BOTH the space and the time units of the image axes.

    Note that both units are set on every call: an *omitted* parameter is
    set to its default, not left unchanged. To change one unit without
    touching the other, use `set_space_unit` / `set_time_unit` — which is
    also why this method is deprecated in their favour.

    Args:
        space_unit: The space unit of the image.
        time_unit: The time unit of the image.
    """
    meta = self._meta_handler.get_meta()
    meta = meta.to_units(space_unit=space_unit, time_unit=time_unit)
    self._meta_handler.update_meta(meta)

set_axes_names

set_axes_names(axes_names: Sequence[str]) -> None

Set the axes names of the label.

Parameters:

  • axes_names (Sequence[str]) –

    The axes names to set.

Source code in src/ngio/images/_abstract_image.py
def set_axes_names(self, axes_names: Sequence[str]) -> None:
    """Set the axes names of the label.

    Args:
        axes_names (Sequence[str]): The axes names to set.
    """
    meta = self._meta_handler.get_meta()
    meta = meta.rename_axes(axes_names=axes_names)
    self._meta_handler._axes_setup = meta.axes_handler.axes_setup
    self._meta_handler.update_meta(meta)

set_name

set_name(name: str) -> None

Set the name of the image in the metadata.

This does not change the group name or any paths.

Parameters:

  • name (str) –

    The name of the image.

Source code in src/ngio/images/_abstract_image.py
def set_name(
    self,
    name: str,
) -> None:
    """Set the name of the image in the metadata.

    This does not change the group name or any paths.

    Args:
        name (str): The name of the image.
    """
    meta = self._meta_handler.get_meta()
    meta = meta.rename_image(name=name)
    self._meta_handler.update_meta(meta)

track_writes

track_writes() -> Generator[list[tuple[RegionType, ...]]]

Record the region of every set_* write made through this handle.

Only the set_* methods are recorded — set_array, set_roi, and their masked variants. Yields a list that accumulates one on-disk index tuple per completed write, ready to hand to consolidate(regions=...) so the pyramid rebuild covers exactly what was written:

with image.track_writes() as regions:
    image.set_roi(roi, patch)
    image.set_array(other, y=slice(0, 64))
image.consolidate(regions=regions)

Tracking is scoped to the context and to this handle in this process: writes through setter pipes built directly on the zarr array, through another handle to the same image, or in worker processes (ProcessMapper) are not seen — iterators track their own writes through their ROI list instead. Threads sharing this handle all record, and a write that raises records nothing. Nested contexts each keep their own list.

Source code in src/ngio/images/_abstract_image.py
@contextmanager
def track_writes(self) -> Generator[list[tuple[RegionType, ...]]]:
    """Record the region of every `set_*` write made through this handle.

    Only the `set_*` methods are recorded — `set_array`, `set_roi`, and
    their masked variants. Yields a list that accumulates one on-disk
    index tuple per completed write, ready to hand to
    `consolidate(regions=...)` so the pyramid rebuild covers exactly what
    was written:

    ```python
    with image.track_writes() as regions:
        image.set_roi(roi, patch)
        image.set_array(other, y=slice(0, 64))
    image.consolidate(regions=regions)
    ```

    Tracking is scoped to the context and to *this* handle in *this*
    process: writes through setter pipes built directly on the zarr
    array, through another handle to the same image, or in worker
    processes (`ProcessMapper`) are not seen — iterators track their own
    writes through their ROI list instead. Threads sharing this handle
    all record, and a write that raises records nothing. Nested contexts
    each keep their own list.
    """
    regions: list[tuple[RegionType, ...]] = []
    with self._tracker_lock:
        self._write_trackers.append(regions)
    try:
        yield regions
    finally:
        with self._tracker_lock:
            self._write_trackers.remove(regions)

roi

roi(name: str | None = 'image') -> Roi

Return the ROI covering the entire image.

Source code in src/ngio/images/_abstract_image.py
def roi(self, name: str | None = "image") -> Roi:
    """Return the ROI covering the entire image."""
    slices = {}
    for ax_name in ["t", "z", "y", "x"]:
        axis_size = self.dimensions.get(ax_name, default=None)
        if axis_size is None:
            continue
        slices[ax_name] = slice(0, axis_size)
    roi_px = Roi.from_values(name=name, slices=slices, space="pixel")
    return roi_px.to_world(pixel_size=self.pixel_size)

build_image_roi_table

build_image_roi_table(
    name: str | None = "image",
) -> RoiTable

Build the ROI table containing the ROI covering the entire image.

Source code in src/ngio/images/_abstract_image.py
def build_image_roi_table(self, name: str | None = "image") -> RoiTable:
    """Build the ROI table containing the ROI covering the entire image."""
    return RoiTable(rois=[self.roi(name=name)])

require_dimensions_match

require_dimensions_match(
    other: AbstractImage, allow_singleton: bool = False
) -> None

Assert that two images have matching spatial dimensions.

Parameters:

  • other (AbstractImage) –

    The other image to compare to.

  • allow_singleton (bool, default: False ) –

    If True, allow singleton dimensions to be compatible with non-singleton dimensions.

Raises:

Source code in src/ngio/images/_abstract_image.py
def require_dimensions_match(
    self,
    other: "AbstractImage",
    allow_singleton: bool = False,
) -> None:
    """Assert that two images have matching spatial dimensions.

    Args:
        other: The other image to compare to.
        allow_singleton: If True, allow singleton dimensions to be
            compatible with non-singleton dimensions.

    Raises:
        NgioValueError: If the images do not have compatible dimensions.
    """
    self.dimensions.require_dimensions_match(
        other.dimensions, allow_singleton=allow_singleton
    )

check_if_dimensions_match

check_if_dimensions_match(
    other: AbstractImage, allow_singleton: bool = False
) -> bool

Check if two images have matching spatial dimensions.

Parameters:

  • other (AbstractImage) –

    The other image to compare to.

  • allow_singleton (bool, default: False ) –

    If True, allow singleton dimensions to be compatible with non-singleton dimensions.

Returns:

  • bool ( bool ) –

    True if the images have matching dimensions, False otherwise.

Source code in src/ngio/images/_abstract_image.py
def check_if_dimensions_match(
    self,
    other: "AbstractImage",
    allow_singleton: bool = False,
) -> bool:
    """Check if two images have matching spatial dimensions.

    Args:
        other: The other image to compare to.
        allow_singleton: If True, allow singleton dimensions to be
            compatible with non-singleton dimensions.

    Returns:
        bool: True if the images have matching dimensions, False otherwise.
    """
    return self.dimensions.check_if_dimensions_match(
        other.dimensions, allow_singleton=allow_singleton
    )

require_axes_match

require_axes_match(other: AbstractImage) -> None

Assert that two images have compatible axes.

Parameters:

Raises:

Source code in src/ngio/images/_abstract_image.py
def require_axes_match(
    self,
    other: "AbstractImage",
) -> None:
    """Assert that two images have compatible axes.

    Args:
        other: The other image to compare to.

    Raises:
        NgioValueError: If the images do not have compatible axes.
    """
    self.dimensions.require_axes_match(other.dimensions)

check_if_axes_match

check_if_axes_match(other: AbstractImage) -> bool

Check if two images have compatible axes.

Parameters:

Returns:

  • bool ( bool ) –

    True if the images have compatible axes, False otherwise.

Source code in src/ngio/images/_abstract_image.py
def check_if_axes_match(
    self,
    other: "AbstractImage",
) -> bool:
    """Check if two images have compatible axes.

    Args:
        other: The other image to compare to.

    Returns:
        bool: True if the images have compatible axes, False otherwise.

    """
    return self.dimensions.check_if_axes_match(other.dimensions)

require_rescalable

require_rescalable(other: AbstractImage) -> None

Assert that two images can be rescaled to each other.

For this to be true, the images must have the same axes, and the pixel sizes must be compatible (i.e. one can be scaled to the other).

Parameters:

Raises:

Source code in src/ngio/images/_abstract_image.py
def require_rescalable(
    self,
    other: "AbstractImage",
) -> None:
    """Assert that two images can be rescaled to each other.

    For this to be true, the images must have the same axes, and
    the pixel sizes must be compatible (i.e. one can be scaled to the other).

    Args:
        other: The other image to compare to.

    Raises:
        NgioValueError: If the images cannot be scaled to each other.
    """
    self.dimensions.require_rescalable(other.dimensions)

check_if_rescalable

check_if_rescalable(other: AbstractImage) -> bool

Check if two images can be rescaled to each other.

For this to be true, the images must have the same axes, and the pixel sizes must be compatible (i.e. one can be scaled to the other).

Parameters:

Returns:

  • bool ( bool ) –

    True if the images can be rescaled to each other, False otherwise.

Source code in src/ngio/images/_abstract_image.py
def check_if_rescalable(
    self,
    other: "AbstractImage",
) -> bool:
    """Check if two images can be rescaled to each other.

    For this to be true, the images must have the same axes, and
    the pixel sizes must be compatible (i.e. one can be scaled to the other).

    Args:
        other: The other image to compare to.

    Returns:
        bool: True if the images can be rescaled to each other, False otherwise.
    """
    return self.dimensions.check_if_rescalable(other.dimensions)

get_channel_idx

get_channel_idx(
    channel_label: str | None = None,
    wavelength_id: str | None = None,
) -> int

Get the index of a channel by its label or wavelength ID.

Source code in src/ngio/images/_image.py
def get_channel_idx(
    self, channel_label: str | None = None, wavelength_id: str | None = None
) -> int:
    """Get the index of a channel by its label or wavelength ID."""
    return self.channels_meta.get_channel_idx(
        channel_label=channel_label, wavelength_id=wavelength_id
    )

resolve_channel_selection

resolve_channel_selection(
    channel_selection: ChannelSlicingInputType = None,
) -> dict[str, int | list[int]]

Resolve a channel selection against this image's channel metadata.

Accepts everything the get_* methods accept as channel_selection — an index, a channel label, a ChannelSelectionModel, or a sequence of those — and returns the slicing entry it resolves to ({"c": index} or {"c": [indices]}; {} for None), ready to use as slicing kwargs. Resolution touches only metadata, so this is also the way to validate a selection before loading any data.

Raises:

Source code in src/ngio/images/_image.py
def resolve_channel_selection(
    self, channel_selection: ChannelSlicingInputType = None
) -> dict[str, int | list[int]]:
    """Resolve a channel selection against this image's channel metadata.

    Accepts everything the `get_*` methods accept as `channel_selection` —
    an index, a channel label, a `ChannelSelectionModel`, or a sequence of
    those — and returns the slicing entry it resolves to (`{"c": index}`
    or `{"c": [indices]}`; `{}` for `None`), ready to use as slicing
    kwargs. Resolution touches only metadata, so this is also the way to
    validate a selection before loading any data.

    Raises:
        NgioValueError: If a referenced channel does not exist.
    """
    return _parse_channel_selection(self, channel_selection)

get_as_numpy

get_as_numpy(
    channel_selection: ChannelSlicingInputType = None,
    axes_order: Sequence[str] | None = None,
    transforms: Sequence[TransformProtocol] | None = None,
    **slicing_kwargs: slice | int | Sequence[int] | None,
) -> ndarray

Get the image as a numpy array.

Parameters:

  • channel_selection (ChannelSlicingInputType, default: None ) –

    Select a specific channel by label. If None, all channels are returned. Alternatively, you can slice arbitrary channels using the slicing kwargs (c=[0, 2]).

  • axes_order (Sequence[str] | None, default: None ) –

    The order of the axes to return the array.

  • transforms (Sequence[TransformProtocol] | None, default: None ) –

    The transforms to apply to the array.

  • **slicing_kwargs (slice | int | Sequence[int] | None, default: {} ) –

    The slices to get the array.

Returns:

  • ndarray –

    The array of the region of interest.

Source code in src/ngio/images/_image.py
def get_as_numpy(
    self,
    channel_selection: ChannelSlicingInputType = None,
    axes_order: Sequence[str] | None = None,
    transforms: Sequence[TransformProtocol] | None = None,
    **slicing_kwargs: slice | int | Sequence[int] | None,
) -> np.ndarray:
    """Get the image as a numpy array.

    Args:
        channel_selection: Select a specific channel by label.
            If None, all channels are returned.
            Alternatively, you can slice arbitrary channels
            using the slicing kwargs (c=[0, 2]).
        axes_order: The order of the axes to return the array.
        transforms: The transforms to apply to the array.
        **slicing_kwargs: The slices to get the array.

    Returns:
        The array of the region of interest.
    """
    _slicing_kwargs = add_channel_selection_to_slicing_dict(
        image=self, channel_selection=channel_selection, slicing_dict=slicing_kwargs
    )
    return self._get_as_numpy(
        axes_order=axes_order, transforms=transforms, **_slicing_kwargs
    )

get_roi_as_numpy

get_roi_as_numpy(
    roi: Roi,
    channel_selection: ChannelSlicingInputType = None,
    axes_order: Sequence[str] | None = None,
    transforms: Sequence[TransformProtocol] | None = None,
    **slicing_kwargs: SlicingInputType,
) -> ndarray

Get the image as a numpy array for a region of interest.

Parameters:

  • roi (Roi) –

    The region of interest to get the array.

  • channel_selection (ChannelSlicingInputType, default: None ) –

    Select a what subset of channels to return. If None, all channels are returned.

  • axes_order (Sequence[str] | None, default: None ) –

    The order of the axes to return the array.

  • transforms (Sequence[TransformProtocol] | None, default: None ) –

    The transforms to apply to the array.

  • **slicing_kwargs (SlicingInputType, default: {} ) –

    Per-axis selections in absolute coordinates; an explicit selection on an axis the roi already pins replaces the roi-derived one (and drops the pipe's roi).

Returns:

  • ndarray –

    The array of the region of interest.

Source code in src/ngio/images/_image.py
def get_roi_as_numpy(
    self,
    roi: Roi,
    channel_selection: ChannelSlicingInputType = None,
    axes_order: Sequence[str] | None = None,
    transforms: Sequence[TransformProtocol] | None = None,
    **slicing_kwargs: SlicingInputType,
) -> np.ndarray:
    """Get the image as a numpy array for a region of interest.

    Args:
        roi: The region of interest to get the array.
        channel_selection: Select a what subset of channels to return.
            If None, all channels are returned.
        axes_order: The order of the axes to return the array.
        transforms: The transforms to apply to the array.
        **slicing_kwargs: Per-axis selections in absolute
            coordinates; an explicit selection on an axis the `roi`
            already pins replaces the roi-derived one (and drops the
            pipe's `roi`).

    Returns:
        The array of the region of interest.
    """
    _slicing_kwargs = add_channel_selection_to_slicing_dict(
        image=self, channel_selection=channel_selection, slicing_dict=slicing_kwargs
    )
    return self._get_roi_as_numpy(
        roi=roi, axes_order=axes_order, transforms=transforms, **_slicing_kwargs
    )

get_as_dask

get_as_dask(
    channel_selection: ChannelSlicingInputType = None,
    axes_order: Sequence[str] | None = None,
    transforms: Sequence[TransformProtocol] | None = None,
    **slicing_kwargs: SlicingInputType,
) -> Array

Get the image as a dask array.

Parameters:

  • channel_selection (ChannelSlicingInputType, default: None ) –

    Select a what subset of channels to return. If None, all channels are returned.

  • axes_order (Sequence[str] | None, default: None ) –

    The order of the axes to return the array.

  • transforms (Sequence[TransformProtocol] | None, default: None ) –

    The transforms to apply to the array.

  • **slicing_kwargs (SlicingInputType, default: {} ) –

    The slices to get the array.

Returns:

  • Array –

    The dask array of the region of interest.

Source code in src/ngio/images/_image.py
def get_as_dask(
    self,
    channel_selection: ChannelSlicingInputType = None,
    axes_order: Sequence[str] | None = None,
    transforms: Sequence[TransformProtocol] | None = None,
    **slicing_kwargs: SlicingInputType,
) -> da.Array:
    """Get the image as a dask array.

    Args:
        channel_selection: Select a what subset of channels to return.
            If None, all channels are returned.
        axes_order: The order of the axes to return the array.
        transforms: The transforms to apply to the array.
        **slicing_kwargs: The slices to get the array.

    Returns:
        The dask array of the region of interest.
    """
    _slicing_kwargs = add_channel_selection_to_slicing_dict(
        image=self, channel_selection=channel_selection, slicing_dict=slicing_kwargs
    )
    return self._get_as_dask(
        axes_order=axes_order, transforms=transforms, **_slicing_kwargs
    )

get_roi_as_dask

get_roi_as_dask(
    roi: Roi,
    channel_selection: ChannelSlicingInputType = None,
    axes_order: Sequence[str] | None = None,
    transforms: Sequence[TransformProtocol] | None = None,
    **slicing_kwargs: SlicingInputType,
) -> Array

Get the image as a dask array for a region of interest.

Parameters:

  • roi (Roi) –

    The region of interest to get the array.

  • channel_selection (ChannelSlicingInputType, default: None ) –

    Select a what subset of channels to return. If None, all channels are returned.

  • axes_order (Sequence[str] | None, default: None ) –

    The order of the axes to return the array.

  • transforms (Sequence[TransformProtocol] | None, default: None ) –

    The transforms to apply to the array.

  • **slicing_kwargs (SlicingInputType, default: {} ) –

    Per-axis selections in absolute coordinates; an explicit selection on an axis the roi already pins replaces the roi-derived one (and drops the pipe's roi).

Returns:

  • Array –

    The dask array of the region of interest.

Source code in src/ngio/images/_image.py
def get_roi_as_dask(
    self,
    roi: Roi,
    channel_selection: ChannelSlicingInputType = None,
    axes_order: Sequence[str] | None = None,
    transforms: Sequence[TransformProtocol] | None = None,
    **slicing_kwargs: SlicingInputType,
) -> da.Array:
    """Get the image as a dask array for a region of interest.

    Args:
        roi: The region of interest to get the array.
        channel_selection: Select a what subset of channels to return.
            If None, all channels are returned.
        axes_order: The order of the axes to return the array.
        transforms: The transforms to apply to the array.
        **slicing_kwargs: Per-axis selections in absolute
            coordinates; an explicit selection on an axis the `roi`
            already pins replaces the roi-derived one (and drops the
            pipe's `roi`).

    Returns:
        The dask array of the region of interest.
    """
    _slicing_kwargs = add_channel_selection_to_slicing_dict(
        image=self, channel_selection=channel_selection, slicing_dict=slicing_kwargs
    )
    return self._get_roi_as_dask(
        roi=roi, axes_order=axes_order, transforms=transforms, **_slicing_kwargs
    )

get_array

get_array(
    channel_selection: ChannelSlicingInputType = None,
    axes_order: Sequence[str] | None = None,
    transforms: Sequence[TransformProtocol] | None = None,
    mode: Literal["numpy", "dask"] = "numpy",
    **slicing_kwargs: SlicingInputType,
) -> ndarray | Array

Get the image as a zarr array.

Parameters:

  • channel_selection (ChannelSlicingInputType, default: None ) –

    Select a what subset of channels to return. If None, all channels are returned.

  • axes_order (Sequence[str] | None, default: None ) –

    The order of the axes to return the array.

  • transforms (Sequence[TransformProtocol] | None, default: None ) –

    The transforms to apply to the array.

  • mode (Literal['numpy', 'dask'], default: 'numpy' ) –

    The object type to return. Can be "dask", "numpy".

  • **slicing_kwargs (SlicingInputType, default: {} ) –

    The slices to get the array.

Returns:

  • ndarray | Array –

    The zarr array of the region of interest.

Source code in src/ngio/images/_image.py
def get_array(
    self,
    channel_selection: ChannelSlicingInputType = None,
    axes_order: Sequence[str] | None = None,
    transforms: Sequence[TransformProtocol] | None = None,
    mode: Literal["numpy", "dask"] = "numpy",
    **slicing_kwargs: SlicingInputType,
) -> np.ndarray | da.Array:
    """Get the image as a zarr array.

    Args:
        channel_selection: Select a what subset of channels to return.
            If None, all channels are returned.
        axes_order: The order of the axes to return the array.
        transforms: The transforms to apply to the array.
        mode: The object type to return.
            Can be "dask", "numpy".
        **slicing_kwargs: The slices to get the array.

    Returns:
        The zarr array of the region of interest.
    """
    _slicing_kwargs = add_channel_selection_to_slicing_dict(
        image=self, channel_selection=channel_selection, slicing_dict=slicing_kwargs
    )
    return self._get_array(
        axes_order=axes_order, mode=mode, transforms=transforms, **_slicing_kwargs
    )

get_roi

get_roi(
    roi: Roi,
    channel_selection: ChannelSlicingInputType = None,
    axes_order: Sequence[str] | None = None,
    transforms: Sequence[TransformProtocol] | None = None,
    mode: Literal["numpy", "dask"] = "numpy",
    **slicing_kwargs: SlicingInputType,
) -> ndarray | Array

Get the image as a zarr array for a region of interest.

Parameters:

  • roi (Roi) –

    The region of interest to get the array.

  • channel_selection (ChannelSlicingInputType, default: None ) –

    Select a what subset of channels to return. If None, all channels are returned.

  • axes_order (Sequence[str] | None, default: None ) –

    The order of the axes to return the array.

  • transforms (Sequence[TransformProtocol] | None, default: None ) –

    The transforms to apply to the array.

  • mode (Literal['numpy', 'dask'], default: 'numpy' ) –

    The object type to return. Can be "dask", "numpy".

  • **slicing_kwargs (SlicingInputType, default: {} ) –

    Per-axis selections in absolute coordinates; an explicit selection on an axis the roi already pins replaces the roi-derived one (and drops the pipe's roi).

Returns:

  • ndarray | Array –

    The zarr array of the region of interest.

Source code in src/ngio/images/_image.py
def get_roi(
    self,
    roi: Roi,
    channel_selection: ChannelSlicingInputType = None,
    axes_order: Sequence[str] | None = None,
    transforms: Sequence[TransformProtocol] | None = None,
    mode: Literal["numpy", "dask"] = "numpy",
    **slicing_kwargs: SlicingInputType,
) -> np.ndarray | da.Array:
    """Get the image as a zarr array for a region of interest.

    Args:
        roi: The region of interest to get the array.
        channel_selection: Select a what subset of channels to return.
            If None, all channels are returned.
        axes_order: The order of the axes to return the array.
        transforms: The transforms to apply to the array.
        mode: The object type to return.
            Can be "dask", "numpy".
        **slicing_kwargs: Per-axis selections in absolute
            coordinates; an explicit selection on an axis the `roi`
            already pins replaces the roi-derived one (and drops the
            pipe's `roi`).

    Returns:
        The zarr array of the region of interest.
    """
    _slicing_kwargs = add_channel_selection_to_slicing_dict(
        image=self, channel_selection=channel_selection, slicing_dict=slicing_kwargs
    )
    return self._get_roi(
        roi=roi,
        axes_order=axes_order,
        mode=mode,
        transforms=transforms,
        **_slicing_kwargs,
    )

set_array

set_array(
    patch: ndarray | Array,
    channel_selection: ChannelSlicingInputType = None,
    axes_order: Sequence[str] | None = None,
    transforms: Sequence[TransformProtocol] | None = None,
    merge: MergeInput | None = None,
    **slicing_kwargs: SlicingInputType,
) -> None

Set the image array.

Dask patches are serial-only: concurrent dask writes from several threads can silently lose updates (numpy patches are unaffected).

Parameters:

  • patch (ndarray | Array) –

    The array to set.

  • channel_selection (ChannelSlicingInputType, default: None ) –

    Select a what subset of channels to return. If None, all channels are set.

  • axes_order (Sequence[str] | None, default: None ) –

    The order of the axes to set the array.

  • transforms (Sequence[TransformProtocol] | None, default: None ) –

    The transforms to apply to the array.

  • merge (MergeInput | None, default: None ) –

    How to combine the patch with what is already there — a rule name, a callable, or a policy. None overwrites.

  • **slicing_kwargs (SlicingInputType, default: {} ) –

    The slices to set the array.

Source code in src/ngio/images/_image.py
def set_array(
    self,
    patch: np.ndarray | da.Array,
    channel_selection: ChannelSlicingInputType = None,
    axes_order: Sequence[str] | None = None,
    transforms: Sequence[TransformProtocol] | None = None,
    merge: MergeInput | None = None,
    **slicing_kwargs: SlicingInputType,
) -> None:
    """Set the image array.

    Dask patches are serial-only: concurrent dask writes from several
    threads can silently lose updates (numpy patches are unaffected).

    Args:
        patch: The array to set.
        channel_selection: Select a what subset of channels to return.
            If None, all channels are set.
        axes_order: The order of the axes to set the array.
        transforms: The transforms to apply to the array.
        merge: How to combine the patch with what is already there —
            a rule name, a callable, or a policy. `None` overwrites.
        **slicing_kwargs: The slices to set the array.
    """
    _slicing_kwargs = add_channel_selection_to_slicing_dict(
        image=self, channel_selection=channel_selection, slicing_dict=slicing_kwargs
    )
    self._set_array(
        patch=patch,
        axes_order=axes_order,
        transforms=transforms,
        merge=merge,
        **_slicing_kwargs,
    )

set_roi

set_roi(
    roi: Roi,
    patch: ndarray | Array,
    channel_selection: ChannelSlicingInputType = None,
    axes_order: Sequence[str] | None = None,
    transforms: Sequence[TransformProtocol] | None = None,
    merge: MergeInput | None = None,
    **slicing_kwargs: SlicingInputType,
) -> None

Set the image array for a region of interest.

Dask patches are serial-only: concurrent dask writes from several threads can silently lose updates (numpy patches are unaffected).

Parameters:

  • roi (Roi) –

    The region of interest to set the array.

  • patch (ndarray | Array) –

    The array to set.

  • channel_selection (ChannelSlicingInputType, default: None ) –

    Select a what subset of channels to return.

  • axes_order (Sequence[str] | None, default: None ) –

    The order of the axes to set the array.

  • transforms (Sequence[TransformProtocol] | None, default: None ) –

    The transforms to apply to the array.

  • merge (MergeInput | None, default: None ) –

    How to combine the patch with what is already there — a rule name, a callable, or a policy. None overwrites.

  • **slicing_kwargs (SlicingInputType, default: {} ) –

    Per-axis selections in absolute coordinates; an explicit selection on an axis the roi already pins replaces the roi-derived one (and drops the pipe's roi).

Source code in src/ngio/images/_image.py
def set_roi(
    self,
    roi: Roi,
    patch: np.ndarray | da.Array,
    channel_selection: ChannelSlicingInputType = None,
    axes_order: Sequence[str] | None = None,
    transforms: Sequence[TransformProtocol] | None = None,
    merge: MergeInput | None = None,
    **slicing_kwargs: SlicingInputType,
) -> None:
    """Set the image array for a region of interest.

    Dask patches are serial-only: concurrent dask writes from several
    threads can silently lose updates (numpy patches are unaffected).

    Args:
        roi: The region of interest to set the array.
        patch: The array to set.
        channel_selection: Select a what subset of channels to return.
        axes_order: The order of the axes to set the array.
        transforms: The transforms to apply to the array.
        merge: How to combine the patch with what is already there —
            a rule name, a callable, or a policy. `None` overwrites.
        **slicing_kwargs: Per-axis selections in absolute
            coordinates; an explicit selection on an axis the `roi`
            already pins replaces the roi-derived one (and drops the
            pipe's `roi`).
    """
    _slicing_kwargs = add_channel_selection_to_slicing_dict(
        image=self, channel_selection=channel_selection, slicing_dict=slicing_kwargs
    )
    self._set_roi(
        roi=roi,
        patch=patch,
        axes_order=axes_order,
        transforms=transforms,
        merge=merge,
        **_slicing_kwargs,
    )

consolidate

consolidate(
    order: InterpolationOrder = "linear",
    mode: ConsolidationMode | None = None,
    regions: ConsolidationRegions | None = None,
) -> None

Consolidate the image on disk.

Parameters:

  • order (InterpolationOrder, default: 'linear' ) –

    The interpolation order.

  • mode (ConsolidationMode | None, default: None ) –

    How to build each level, see ConsolidationMode.

  • regions (ConsolidationRegions | None, default: None ) –

    Where this level changed — typically the Rois that were written (set_roi's own argument fits directly); raw on-disk index tuples, as a setter pipe's slicing_ops.normalized_slicing_tuple produces, also work. Only the pyramid regions derived from them are rebuilt, identically to a full rebuild; outside the exact envelope (integral downsamples, order not "cubic", coverage below ConsolidationConfig.partial_max_coverage) the whole pyramid is rebuilt instead, silently. None rebuilds everything.

Source code in src/ngio/images/_image.py
def consolidate(
    self,
    order: InterpolationOrder = "linear",
    mode: ConsolidationMode | None = None,
    regions: ConsolidationRegions | None = None,
) -> None:
    """Consolidate the image on disk.

    Args:
        order: The interpolation order.
        mode: How to build each level, see `ConsolidationMode`.
        regions: Where this level changed — typically the `Roi`s that were
            written (`set_roi`'s own argument fits directly); raw on-disk
            index tuples, as a setter pipe's
            `slicing_ops.normalized_slicing_tuple` produces, also work.
            Only the pyramid regions derived from them are rebuilt,
            identically to a full rebuild; outside the exact envelope
            (integral downsamples, `order` not `"cubic"`, coverage below
            `ConsolidationConfig.partial_max_coverage`) the whole pyramid
            is rebuilt instead, silently. `None` rebuilds everything.
    """
    self._consolidate(order=order, mode=mode, regions=regions)

Open a label

ngio.open_label

open_label(
    store: StoreOrGroup,
    name: str | None = None,
    path: str | None = None,
    pixel_size: PixelSize | None = None,
    strict: bool = False,
    axes_setup: AxesSetup | None = None,
    cache: bool = False,
    mode: AccessModeLiteral = "r+",
) -> Label

Open a single level label from an OME-Zarr Label group.

Parameters:

  • store (StoreOrGroup) –

    The Zarr store or group to create the image in.

  • name (str | None, default: None ) –

    The name of the label. If None, we will try to open the store as a multiscale label.

  • path (str | None, default: None ) –

    The path to the image in the ome_zarr file.

  • pixel_size (PixelSize | None, default: None ) –

    Select the pyramid level whose pixel size matches this one. A lookup key, not a value to write; to set a pixel size see pixelsize on the create/derive entry points.

  • strict (bool, default: False ) –

    Only used if the pixel size is provided. If True, the pixel size must match the image pixel size exactly. If False, the closest pixel size level will be returned.

  • axes_setup (AxesSetup | None, default: None ) –

    Axes setup to load ome-zarr with non-standard axes configurations.

  • cache (bool, default: False ) –

    Whether to use a cache for the zarr group metadata.

  • mode (AccessModeLiteral, default: 'r+' ) –

    The access mode for the image. Defaults to "r+".

Source code in src/ngio/images/_ome_zarr_container.py
def open_label(
    store: StoreOrGroup,
    name: str | None = None,
    path: str | None = None,
    pixel_size: PixelSize | None = None,
    strict: bool = False,
    axes_setup: AxesSetup | None = None,
    cache: bool = False,
    mode: AccessModeLiteral = "r+",
) -> Label:
    """Open a single level label from an OME-Zarr Label group.

    Args:
        store (StoreOrGroup): The Zarr store or group to create the image in.
        name (str | None): The name of the label. If None,
            we will try to open the store as a multiscale label.
        path (str | None): The path to the image in the ome_zarr file.
        pixel_size: Select the pyramid level whose pixel size matches this one.
            A lookup key, not a value to write; to set a pixel size see
            `pixelsize` on the create/derive entry points.
        strict (bool): Only used if the pixel size is provided. If True, the
            pixel size must match the image pixel size exactly. If False, the
            closest pixel size level will be returned.
        axes_setup (AxesSetup | None): Axes setup to load ome-zarr with
            non-standard axes configurations.
        cache (bool): Whether to use a cache for the zarr group metadata.
        mode (AccessModeLiteral): The access mode for the image. Defaults to "r+".

    """
    group_handler = ZarrGroupHandler(store=store, cache=cache, mode=mode)
    if name is None:
        label_meta_handler = LabelMetaHandler(group_handler, axes_setup=axes_setup)
        path = (
            label_meta_handler.get_meta()
            .get_dataset(path=path, pixel_size=pixel_size, strict=strict)
            .path
        )
        return Label(group_handler, path, label_meta_handler)

    labels_container = LabelsContainer(group_handler, axes_setup=axes_setup)
    return labels_container.get(
        name=name,
        path=path,
        pixel_size=pixel_size,
        strict=strict,
    )

Label

ngio.Label

Label(
    group_handler: ZarrGroupHandler,
    path: str,
    meta_handler: LabelMetaHandler,
)

Bases: AbstractImage

A single level of a label pyramid.

Initialize the Image at a single level.

Parameters:

  • group_handler (ZarrGroupHandler) –

    The Zarr group handler.

  • path (str) –

    The path to the image in the ome_zarr file.

  • meta_handler (LabelMetaHandler) –

    The image metadata handler.

Source code in src/ngio/images/_label.py
def __init__(
    self,
    group_handler: ZarrGroupHandler,
    path: str,
    meta_handler: LabelMetaHandler,
) -> None:
    """Initialize the Image at a single level.

    Args:
        group_handler: The Zarr group handler.
        path: The path to the image in the ome_zarr file.
        meta_handler: The image metadata handler.

    """
    super().__init__(
        group_handler=group_handler, path=path, meta_handler=meta_handler
    )

path property

path: str

Return the path of the image.

dataset property

dataset: Dataset

Return the dataset of the image.

dimensions property

dimensions: Dimensions

Return the dimensions of the image.

pixel_size property

pixel_size: PixelSize

Return the pixel size of the image.

axes_handler property

axes_handler: AxesHandler

Return the axes handler of the image.

axes_setup property

axes_setup: AxesSetup

Return the axes setup of the image.

axes property

axes: tuple[str, ...]

Return the axes of the image.

zarr_array property

zarr_array: Array

Return the Zarr array.

shape property

shape: tuple[int, ...]

Return the shape of the image.

dtype property

dtype: str

Return the dtype of the image.

chunks property

chunks: tuple[int, ...]

Return the chunks of the image.

write_granularity property

write_granularity: tuple[int, ...]

Return the atomic write unit of the on-disk array.

The shard shape when the array is sharded (writes are read-modify-writes of whole shard objects), otherwise the chunk shape.

is_3d property

is_3d: bool

Return True if the image is 3D.

is_2d property

is_2d: bool

Return True if the image is 2D.

is_time_series property

is_time_series: bool

Return True if the image is a time series.

is_2d_time_series property

is_2d_time_series: bool

Return True if the image is a 2D time series.

is_3d_time_series property

is_3d_time_series: bool

Return True if the image is a 3D time series.

is_multi_channels property

is_multi_channels: bool

Return True if the image is multichannel.

space_unit property

space_unit: str | None

Return the space unit of the image.

time_unit property

time_unit: str | None

Return the time unit of the image.

meta_handler property

meta_handler: LabelMetaHandler

Return the metadata handler.

meta property

meta: NgioLabelMeta

Return the metadata.

has_axis

has_axis(axis: str) -> bool

Return True if the image has the given axis.

Source code in src/ngio/images/_abstract_image.py
def has_axis(self, axis: str) -> bool:
    """Return True if the image has the given axis."""
    return self.axes_handler.has_axis(axis)

set_space_unit

set_space_unit(unit: SpaceUnits = DefaultSpaceUnit) -> None

Set the unit of the spatial axes; the time unit is untouched.

Parameters:

  • unit (SpaceUnits, default: DefaultSpaceUnit ) –

    The space unit to set.

Source code in src/ngio/images/_abstract_image.py
def set_space_unit(self, unit: SpaceUnits = DefaultSpaceUnit) -> None:
    """Set the unit of the spatial axes; the time unit is untouched.

    Args:
        unit: The space unit to set.
    """
    meta = self._meta_handler.get_meta()
    meta = meta.to_units(space_unit=unit)
    self._meta_handler.update_meta(meta)

set_time_unit

set_time_unit(unit: TimeUnits = DefaultTimeUnit) -> None

Set the unit of the time axis; the space unit is untouched.

Parameters:

  • unit (TimeUnits, default: DefaultTimeUnit ) –

    The time unit to set.

Source code in src/ngio/images/_abstract_image.py
def set_time_unit(self, unit: TimeUnits = DefaultTimeUnit) -> None:
    """Set the unit of the time axis; the space unit is untouched.

    Args:
        unit: The time unit to set.
    """
    meta = self._meta_handler.get_meta()
    meta = meta.to_units(time_unit=unit)
    self._meta_handler.update_meta(meta)

set_axes_units

set_axes_units(
    space_unit: SpaceUnits = DefaultSpaceUnit,
    time_unit: TimeUnits = DefaultTimeUnit,
) -> None

Set BOTH the space and the time units of the image axes.

Note that both units are set on every call: an omitted parameter is set to its default, not left unchanged. To change one unit without touching the other, use set_space_unit / set_time_unit — which is also why this method is deprecated in their favour.

Parameters:

  • space_unit (SpaceUnits, default: DefaultSpaceUnit ) –

    The space unit of the image.

  • time_unit (TimeUnits, default: DefaultTimeUnit ) –

    The time unit of the image.

Source code in src/ngio/images/_abstract_image.py
@deprecated(replacement="set_space_unit() / set_time_unit()")
def set_axes_units(
    self,
    space_unit: SpaceUnits = DefaultSpaceUnit,
    time_unit: TimeUnits = DefaultTimeUnit,
) -> None:
    """Set BOTH the space and the time units of the image axes.

    Note that both units are set on every call: an *omitted* parameter is
    set to its default, not left unchanged. To change one unit without
    touching the other, use `set_space_unit` / `set_time_unit` — which is
    also why this method is deprecated in their favour.

    Args:
        space_unit: The space unit of the image.
        time_unit: The time unit of the image.
    """
    meta = self._meta_handler.get_meta()
    meta = meta.to_units(space_unit=space_unit, time_unit=time_unit)
    self._meta_handler.update_meta(meta)

set_axes_names

set_axes_names(axes_names: Sequence[str]) -> None

Set the axes names of the label.

Parameters:

  • axes_names (Sequence[str]) –

    The axes names to set.

Source code in src/ngio/images/_abstract_image.py
def set_axes_names(self, axes_names: Sequence[str]) -> None:
    """Set the axes names of the label.

    Args:
        axes_names (Sequence[str]): The axes names to set.
    """
    meta = self._meta_handler.get_meta()
    meta = meta.rename_axes(axes_names=axes_names)
    self._meta_handler._axes_setup = meta.axes_handler.axes_setup
    self._meta_handler.update_meta(meta)

set_name

set_name(name: str) -> None

Set the name of the image in the metadata.

This does not change the group name or any paths.

Parameters:

  • name (str) –

    The name of the image.

Source code in src/ngio/images/_abstract_image.py
def set_name(
    self,
    name: str,
) -> None:
    """Set the name of the image in the metadata.

    This does not change the group name or any paths.

    Args:
        name (str): The name of the image.
    """
    meta = self._meta_handler.get_meta()
    meta = meta.rename_image(name=name)
    self._meta_handler.update_meta(meta)

track_writes

track_writes() -> Generator[list[tuple[RegionType, ...]]]

Record the region of every set_* write made through this handle.

Only the set_* methods are recorded — set_array, set_roi, and their masked variants. Yields a list that accumulates one on-disk index tuple per completed write, ready to hand to consolidate(regions=...) so the pyramid rebuild covers exactly what was written:

with image.track_writes() as regions:
    image.set_roi(roi, patch)
    image.set_array(other, y=slice(0, 64))
image.consolidate(regions=regions)

Tracking is scoped to the context and to this handle in this process: writes through setter pipes built directly on the zarr array, through another handle to the same image, or in worker processes (ProcessMapper) are not seen — iterators track their own writes through their ROI list instead. Threads sharing this handle all record, and a write that raises records nothing. Nested contexts each keep their own list.

Source code in src/ngio/images/_abstract_image.py
@contextmanager
def track_writes(self) -> Generator[list[tuple[RegionType, ...]]]:
    """Record the region of every `set_*` write made through this handle.

    Only the `set_*` methods are recorded — `set_array`, `set_roi`, and
    their masked variants. Yields a list that accumulates one on-disk
    index tuple per completed write, ready to hand to
    `consolidate(regions=...)` so the pyramid rebuild covers exactly what
    was written:

    ```python
    with image.track_writes() as regions:
        image.set_roi(roi, patch)
        image.set_array(other, y=slice(0, 64))
    image.consolidate(regions=regions)
    ```

    Tracking is scoped to the context and to *this* handle in *this*
    process: writes through setter pipes built directly on the zarr
    array, through another handle to the same image, or in worker
    processes (`ProcessMapper`) are not seen — iterators track their own
    writes through their ROI list instead. Threads sharing this handle
    all record, and a write that raises records nothing. Nested contexts
    each keep their own list.
    """
    regions: list[tuple[RegionType, ...]] = []
    with self._tracker_lock:
        self._write_trackers.append(regions)
    try:
        yield regions
    finally:
        with self._tracker_lock:
            self._write_trackers.remove(regions)

roi

roi(name: str | None = 'image') -> Roi

Return the ROI covering the entire image.

Source code in src/ngio/images/_abstract_image.py
def roi(self, name: str | None = "image") -> Roi:
    """Return the ROI covering the entire image."""
    slices = {}
    for ax_name in ["t", "z", "y", "x"]:
        axis_size = self.dimensions.get(ax_name, default=None)
        if axis_size is None:
            continue
        slices[ax_name] = slice(0, axis_size)
    roi_px = Roi.from_values(name=name, slices=slices, space="pixel")
    return roi_px.to_world(pixel_size=self.pixel_size)

build_image_roi_table

build_image_roi_table(
    name: str | None = "image",
) -> RoiTable

Build the ROI table containing the ROI covering the entire image.

Source code in src/ngio/images/_abstract_image.py
def build_image_roi_table(self, name: str | None = "image") -> RoiTable:
    """Build the ROI table containing the ROI covering the entire image."""
    return RoiTable(rois=[self.roi(name=name)])

require_dimensions_match

require_dimensions_match(
    other: AbstractImage, allow_singleton: bool = False
) -> None

Assert that two images have matching spatial dimensions.

Parameters:

  • other (AbstractImage) –

    The other image to compare to.

  • allow_singleton (bool, default: False ) –

    If True, allow singleton dimensions to be compatible with non-singleton dimensions.

Raises:

Source code in src/ngio/images/_abstract_image.py
def require_dimensions_match(
    self,
    other: "AbstractImage",
    allow_singleton: bool = False,
) -> None:
    """Assert that two images have matching spatial dimensions.

    Args:
        other: The other image to compare to.
        allow_singleton: If True, allow singleton dimensions to be
            compatible with non-singleton dimensions.

    Raises:
        NgioValueError: If the images do not have compatible dimensions.
    """
    self.dimensions.require_dimensions_match(
        other.dimensions, allow_singleton=allow_singleton
    )

check_if_dimensions_match

check_if_dimensions_match(
    other: AbstractImage, allow_singleton: bool = False
) -> bool

Check if two images have matching spatial dimensions.

Parameters:

  • other (AbstractImage) –

    The other image to compare to.

  • allow_singleton (bool, default: False ) –

    If True, allow singleton dimensions to be compatible with non-singleton dimensions.

Returns:

  • bool ( bool ) –

    True if the images have matching dimensions, False otherwise.

Source code in src/ngio/images/_abstract_image.py
def check_if_dimensions_match(
    self,
    other: "AbstractImage",
    allow_singleton: bool = False,
) -> bool:
    """Check if two images have matching spatial dimensions.

    Args:
        other: The other image to compare to.
        allow_singleton: If True, allow singleton dimensions to be
            compatible with non-singleton dimensions.

    Returns:
        bool: True if the images have matching dimensions, False otherwise.
    """
    return self.dimensions.check_if_dimensions_match(
        other.dimensions, allow_singleton=allow_singleton
    )

require_axes_match

require_axes_match(other: AbstractImage) -> None

Assert that two images have compatible axes.

Parameters:

Raises:

Source code in src/ngio/images/_abstract_image.py
def require_axes_match(
    self,
    other: "AbstractImage",
) -> None:
    """Assert that two images have compatible axes.

    Args:
        other: The other image to compare to.

    Raises:
        NgioValueError: If the images do not have compatible axes.
    """
    self.dimensions.require_axes_match(other.dimensions)

check_if_axes_match

check_if_axes_match(other: AbstractImage) -> bool

Check if two images have compatible axes.

Parameters:

Returns:

  • bool ( bool ) –

    True if the images have compatible axes, False otherwise.

Source code in src/ngio/images/_abstract_image.py
def check_if_axes_match(
    self,
    other: "AbstractImage",
) -> bool:
    """Check if two images have compatible axes.

    Args:
        other: The other image to compare to.

    Returns:
        bool: True if the images have compatible axes, False otherwise.

    """
    return self.dimensions.check_if_axes_match(other.dimensions)

require_rescalable

require_rescalable(other: AbstractImage) -> None

Assert that two images can be rescaled to each other.

For this to be true, the images must have the same axes, and the pixel sizes must be compatible (i.e. one can be scaled to the other).

Parameters:

Raises:

Source code in src/ngio/images/_abstract_image.py
def require_rescalable(
    self,
    other: "AbstractImage",
) -> None:
    """Assert that two images can be rescaled to each other.

    For this to be true, the images must have the same axes, and
    the pixel sizes must be compatible (i.e. one can be scaled to the other).

    Args:
        other: The other image to compare to.

    Raises:
        NgioValueError: If the images cannot be scaled to each other.
    """
    self.dimensions.require_rescalable(other.dimensions)

check_if_rescalable

check_if_rescalable(other: AbstractImage) -> bool

Check if two images can be rescaled to each other.

For this to be true, the images must have the same axes, and the pixel sizes must be compatible (i.e. one can be scaled to the other).

Parameters:

Returns:

  • bool ( bool ) –

    True if the images can be rescaled to each other, False otherwise.

Source code in src/ngio/images/_abstract_image.py
def check_if_rescalable(
    self,
    other: "AbstractImage",
) -> bool:
    """Check if two images can be rescaled to each other.

    For this to be true, the images must have the same axes, and
    the pixel sizes must be compatible (i.e. one can be scaled to the other).

    Args:
        other: The other image to compare to.

    Returns:
        bool: True if the images can be rescaled to each other, False otherwise.
    """
    return self.dimensions.check_if_rescalable(other.dimensions)

get_as_numpy

get_as_numpy(
    axes_order: Sequence[str] | None = None,
    transforms: Sequence[TransformProtocol] | None = None,
    **slicing_kwargs: SlicingInputType,
) -> ndarray

Get the label as a numpy array.

Parameters:

  • axes_order (Sequence[str] | None, default: None ) –

    The order of the axes to return the array.

  • transforms (Sequence[TransformProtocol] | None, default: None ) –

    The transforms to apply to the array.

  • **slicing_kwargs (SlicingInputType, default: {} ) –

    The slices to get the array.

Source code in src/ngio/images/_label.py
def get_as_numpy(
    self,
    axes_order: Sequence[str] | None = None,
    transforms: Sequence[TransformProtocol] | None = None,
    **slicing_kwargs: SlicingInputType,
) -> np.ndarray:
    """Get the label as a numpy array.

    Args:
        axes_order: The order of the axes to return the array.
        transforms: The transforms to apply to the array.
        **slicing_kwargs: The slices to get the array.
    """
    return self._get_as_numpy(
        axes_order=axes_order, transforms=transforms, **slicing_kwargs
    )

get_as_dask

get_as_dask(
    axes_order: Sequence[str] | None = None,
    transforms: Sequence[TransformProtocol] | None = None,
    **slicing_kwargs: SlicingInputType,
) -> Array

Get the label as a dask array.

Parameters:

  • axes_order (Sequence[str] | None, default: None ) –

    The order of the axes to return the array.

  • transforms (Sequence[TransformProtocol] | None, default: None ) –

    The transforms to apply to the array.

  • **slicing_kwargs (SlicingInputType, default: {} ) –

    The slices to get the array.

Source code in src/ngio/images/_label.py
def get_as_dask(
    self,
    axes_order: Sequence[str] | None = None,
    transforms: Sequence[TransformProtocol] | None = None,
    **slicing_kwargs: SlicingInputType,
) -> da.Array:
    """Get the label as a dask array.

    Args:
        axes_order: The order of the axes to return the array.
        transforms: The transforms to apply to the array.
        **slicing_kwargs: The slices to get the array.
    """
    return self._get_as_dask(
        axes_order=axes_order, transforms=transforms, **slicing_kwargs
    )

get_array

get_array(
    axes_order: Sequence[str] | None = None,
    transforms: Sequence[TransformProtocol] | None = None,
    mode: Literal["numpy", "dask"] = "numpy",
    **slicing_kwargs: SlicingInputType,
) -> ndarray | Array

Get the label as a numpy or dask array, by mode.

Parameters:

  • axes_order (Sequence[str] | None, default: None ) –

    The order of the axes to return the array.

  • transforms (Sequence[TransformProtocol] | None, default: None ) –

    The transforms to apply to the array.

  • mode (Literal['numpy', 'dask'], default: 'numpy' ) –

    The object type to return ("numpy" or "dask").

  • **slicing_kwargs (SlicingInputType, default: {} ) –

    The slices to get the array.

Source code in src/ngio/images/_label.py
def get_array(
    self,
    axes_order: Sequence[str] | None = None,
    transforms: Sequence[TransformProtocol] | None = None,
    mode: Literal["numpy", "dask"] = "numpy",
    **slicing_kwargs: SlicingInputType,
) -> np.ndarray | da.Array:
    """Get the label as a numpy or dask array, by `mode`.

    Args:
        axes_order: The order of the axes to return the array.
        transforms: The transforms to apply to the array.
        mode: The object type to return ("numpy" or "dask").
        **slicing_kwargs: The slices to get the array.
    """
    return self._get_array(
        axes_order=axes_order, transforms=transforms, mode=mode, **slicing_kwargs
    )

get_roi_as_numpy

get_roi_as_numpy(
    roi: Roi,
    axes_order: Sequence[str] | None = None,
    transforms: Sequence[TransformProtocol] | None = None,
    **slicing_kwargs: SlicingInputType,
) -> ndarray

Get a region of the label as a numpy array.

Parameters:

  • roi (Roi) –

    The region of interest to get.

  • axes_order (Sequence[str] | None, default: None ) –

    The order of the axes to return the array.

  • transforms (Sequence[TransformProtocol] | None, default: None ) –

    The transforms to apply to the array.

  • **slicing_kwargs (SlicingInputType, default: {} ) –

    Per-axis selections in absolute coordinates; an explicit selection on an axis the roi already pins replaces the roi-derived one (and drops the pipe's roi).

Source code in src/ngio/images/_label.py
def get_roi_as_numpy(
    self,
    roi: Roi,
    axes_order: Sequence[str] | None = None,
    transforms: Sequence[TransformProtocol] | None = None,
    **slicing_kwargs: SlicingInputType,
) -> np.ndarray:
    """Get a region of the label as a numpy array.

    Args:
        roi: The region of interest to get.
        axes_order: The order of the axes to return the array.
        transforms: The transforms to apply to the array.
        **slicing_kwargs: Per-axis selections in absolute coordinates; an
            explicit selection on an axis the `roi` already pins replaces
            the roi-derived one (and drops the pipe's `roi`).
    """
    return self._get_roi_as_numpy(
        roi, axes_order=axes_order, transforms=transforms, **slicing_kwargs
    )

get_roi_as_dask

get_roi_as_dask(
    roi: Roi,
    axes_order: Sequence[str] | None = None,
    transforms: Sequence[TransformProtocol] | None = None,
    **slicing_kwargs: SlicingInputType,
) -> Array

Get a region of the label as a dask array.

Parameters:

  • roi (Roi) –

    The region of interest to get.

  • axes_order (Sequence[str] | None, default: None ) –

    The order of the axes to return the array.

  • transforms (Sequence[TransformProtocol] | None, default: None ) –

    The transforms to apply to the array.

  • **slicing_kwargs (SlicingInputType, default: {} ) –

    Per-axis selections in absolute coordinates; an explicit selection on an axis the roi already pins replaces the roi-derived one (and drops the pipe's roi).

Source code in src/ngio/images/_label.py
def get_roi_as_dask(
    self,
    roi: Roi,
    axes_order: Sequence[str] | None = None,
    transforms: Sequence[TransformProtocol] | None = None,
    **slicing_kwargs: SlicingInputType,
) -> da.Array:
    """Get a region of the label as a dask array.

    Args:
        roi: The region of interest to get.
        axes_order: The order of the axes to return the array.
        transforms: The transforms to apply to the array.
        **slicing_kwargs: Per-axis selections in absolute coordinates; an
            explicit selection on an axis the `roi` already pins replaces
            the roi-derived one (and drops the pipe's `roi`).
    """
    return self._get_roi_as_dask(
        roi, axes_order=axes_order, transforms=transforms, **slicing_kwargs
    )

get_roi

get_roi(
    roi: Roi,
    axes_order: Sequence[str] | None = None,
    transforms: Sequence[TransformProtocol] | None = None,
    mode: Literal["numpy", "dask"] = "numpy",
    **slicing_kwargs: SlicingInputType,
) -> ndarray | Array

Get a region of the label as a numpy or dask array, by mode.

Parameters:

  • roi (Roi) –

    The region of interest to get.

  • axes_order (Sequence[str] | None, default: None ) –

    The order of the axes to return the array.

  • transforms (Sequence[TransformProtocol] | None, default: None ) –

    The transforms to apply to the array.

  • mode (Literal['numpy', 'dask'], default: 'numpy' ) –

    The object type to return ("numpy" or "dask").

  • **slicing_kwargs (SlicingInputType, default: {} ) –

    Per-axis selections in absolute coordinates; an explicit selection on an axis the roi already pins replaces the roi-derived one (and drops the pipe's roi).

Source code in src/ngio/images/_label.py
def get_roi(
    self,
    roi: Roi,
    axes_order: Sequence[str] | None = None,
    transforms: Sequence[TransformProtocol] | None = None,
    mode: Literal["numpy", "dask"] = "numpy",
    **slicing_kwargs: SlicingInputType,
) -> np.ndarray | da.Array:
    """Get a region of the label as a numpy or dask array, by `mode`.

    Args:
        roi: The region of interest to get.
        axes_order: The order of the axes to return the array.
        transforms: The transforms to apply to the array.
        mode: The object type to return ("numpy" or "dask").
        **slicing_kwargs: Per-axis selections in absolute coordinates; an
            explicit selection on an axis the `roi` already pins replaces
            the roi-derived one (and drops the pipe's `roi`).
    """
    return self._get_roi(
        roi,
        axes_order=axes_order,
        transforms=transforms,
        mode=mode,
        **slicing_kwargs,
    )

set_array

set_array(
    patch: ndarray | Array,
    axes_order: Sequence[str] | None = None,
    transforms: Sequence[TransformProtocol] | None = None,
    merge: MergeInput | None = None,
    **slicing_kwargs: SlicingInputType,
) -> None

Write a patch to the label.

Dask patches are serial-only: concurrent dask writes from several threads can silently lose updates (numpy patches are unaffected).

Parameters:

  • patch (ndarray | Array) –

    The patch to set.

  • axes_order (Sequence[str] | None, default: None ) –

    The order of the axes of the patch.

  • transforms (Sequence[TransformProtocol] | None, default: None ) –

    The transforms to apply to the patch.

  • merge (MergeInput | None, default: None ) –

    How to combine the patch with what is already there. None overwrites. See ngio.transforms.

  • **slicing_kwargs (SlicingInputType, default: {} ) –

    The slices to set the patch.

Source code in src/ngio/images/_label.py
def set_array(
    self,
    patch: np.ndarray | da.Array,
    axes_order: Sequence[str] | None = None,
    transforms: Sequence[TransformProtocol] | None = None,
    merge: MergeInput | None = None,
    **slicing_kwargs: SlicingInputType,
) -> None:
    """Write a patch to the label.

    Dask patches are serial-only: concurrent dask writes from several
    threads can silently lose updates (numpy patches are unaffected).

    Args:
        patch: The patch to set.
        axes_order: The order of the axes of the patch.
        transforms: The transforms to apply to the patch.
        merge: How to combine the patch with what is already there.
            `None` overwrites. See `ngio.transforms`.
        **slicing_kwargs: The slices to set the patch.
    """
    return self._set_array(
        patch,
        axes_order=axes_order,
        transforms=transforms,
        merge=merge,
        **slicing_kwargs,
    )

set_roi

set_roi(
    roi: Roi,
    patch: ndarray | Array,
    axes_order: Sequence[str] | None = None,
    transforms: Sequence[TransformProtocol] | None = None,
    merge: MergeInput | None = None,
    **slicing_kwargs: SlicingInputType,
) -> None

Write a patch to a region of the label.

Dask patches are serial-only: concurrent dask writes from several threads can silently lose updates (numpy patches are unaffected).

Parameters:

  • roi (Roi) –

    The region of interest to set.

  • patch (ndarray | Array) –

    The patch to set.

  • axes_order (Sequence[str] | None, default: None ) –

    The order of the axes of the patch.

  • transforms (Sequence[TransformProtocol] | None, default: None ) –

    The transforms to apply to the patch.

  • merge (MergeInput | None, default: None ) –

    How to combine the patch with what is already there. None overwrites. See ngio.transforms.

  • **slicing_kwargs (SlicingInputType, default: {} ) –

    Per-axis selections in absolute coordinates; an explicit selection on an axis the roi already pins replaces the roi-derived one (and drops the pipe's roi).

Source code in src/ngio/images/_label.py
def set_roi(
    self,
    roi: Roi,
    patch: np.ndarray | da.Array,
    axes_order: Sequence[str] | None = None,
    transforms: Sequence[TransformProtocol] | None = None,
    merge: MergeInput | None = None,
    **slicing_kwargs: SlicingInputType,
) -> None:
    """Write a patch to a region of the label.

    Dask patches are serial-only: concurrent dask writes from several
    threads can silently lose updates (numpy patches are unaffected).

    Args:
        roi: The region of interest to set.
        patch: The patch to set.
        axes_order: The order of the axes of the patch.
        transforms: The transforms to apply to the patch.
        merge: How to combine the patch with what is already there.
            `None` overwrites. See `ngio.transforms`.
        **slicing_kwargs: Per-axis selections in absolute coordinates; an
            explicit selection on an axis the `roi` already pins replaces
            the roi-derived one (and drops the pipe's `roi`).
    """
    return self._set_roi(
        roi,
        patch,
        axes_order=axes_order,
        transforms=transforms,
        merge=merge,
        **slicing_kwargs,
    )

build_masking_roi_table

build_masking_roi_table(
    axes_order: Sequence[str] | None = None,
) -> MaskingRoiTable

Compute the masking ROI table.

Source code in src/ngio/images/_label.py
def build_masking_roi_table(
    self, axes_order: Sequence[str] | None = None
) -> MaskingRoiTable:
    """Compute the masking ROI table."""
    return build_masking_roi_table(self, axes_order=axes_order)

consolidate

consolidate(
    mode: ConsolidationMode | None = None,
    regions: ConsolidationRegions | None = None,
) -> None

Consolidate the label on disk.

Parameters:

  • mode (ConsolidationMode | None, default: None ) –

    How to build each level, see ConsolidationMode.

  • regions (ConsolidationRegions | None, default: None ) –

    Where this level changed — Rois or on-disk index tuples — to rebuild only what derives from it. See Image.consolidate.

Source code in src/ngio/images/_label.py
def consolidate(
    self,
    mode: ConsolidationMode | None = None,
    regions: ConsolidationRegions | None = None,
) -> None:
    """Consolidate the label on disk.

    Args:
        mode: How to build each level, see `ConsolidationMode`.
        regions: Where this level changed — `Roi`s or on-disk index
            tuples — to rebuild only what derives from it. See
            `Image.consolidate`.
    """
    self._consolidate(
        order="nearest",
        mode=mode,
        regions=regions,
    )

relabel_sequential

relabel_sequential(
    consolidation_mode: ConsolidationMode | None = None,
) -> int

Renumber the objects to a dense 1..N, in place.

Useful after any process that leaves gaps in the ids — a segmentation written region by region, a filtering step that dropped objects, or a stitch run with compact=False.

Numbers are handed out in first-encounter order over the chunk grid rather than by sorting the existing ids, which is what lets this be a single pass over the label instead of one pass to collect and another to write. Which object ends up as 1 therefore follows the array, and depends on the chunking.

Parameters:

  • consolidation_mode (ConsolidationMode | None, default: None ) –

    How to rebuild the pyramid afterwards, see consolidate. Every level derives from level 0, so they would otherwise disagree with the renumbered ids.

Returns:

  • int –

    How many distinct objects the label now holds.

Source code in src/ngio/images/_label.py
def relabel_sequential(
    self,
    consolidation_mode: ConsolidationMode | None = None,
) -> int:
    """Renumber the objects to a dense `1..N`, in place.

    Useful after any process that leaves gaps in the ids — a segmentation
    written region by region, a filtering step that dropped objects, or a
    stitch run with `compact=False`.

    Numbers are handed out in first-encounter order over the chunk grid
    rather than by sorting the existing ids, which is what lets this be a
    single pass over the label instead of one pass to collect and another to
    write. Which object ends up as `1` therefore follows the array, and
    depends on the chunking.

    Args:
        consolidation_mode: How to rebuild the pyramid afterwards, see
            `consolidate`. Every level derives from level 0, so they would
            otherwise disagree with the renumbered ids.

    Returns:
        How many distinct objects the label now holds.
    """
    count = len(relabel_sequential(self.zarr_array))
    self.consolidate(mode=consolidation_mode)
    return count