Writer¶
Writes an OME-Zarr 0.5 image from a NumPy or Dask array, and adds labels to it. Use
from_existing() to add labels to an image that is already on disk.
- class ome_zarr_io.Writer(path, image, dims, axis_units, downscale_method='mean', scale_transformations=None, downscale_levels=None, downscale_factor=2, overwrite=False, omero_metadata=None, channels=None, colors=None, color_seed=0, name=None)¶
Class for writing valid OME-Zarr 0.5 multiscale images.
Provides functionality to write image data in the OME-Zarr format, a cloud-optimized format for bioimaging data supporting multiscale pyramids, metadata, and coordinate transformations.
Initialize the OME-Zarr writer.
- Parameters:
path (str | Path) – Path where the OME-Zarr will be written.
image (Array | ndarray) – Dask or NumPy array representing the image data.
dims (List[str]) – List of dimension names (e.g., [“t”, “c”, “z”, “y”, “x”]).
axis_units (List[Axis] | Dict[str, Any]) –
Either a list of Axis objects whose length corresponds to the number of dimensions of the input image, or a dictionary that specifies units for each dimension. Dictionary format:
Per-dimension units: {“t”: “second”, “z”: “micrometer”, “y”: “micrometer”, “x”: “micrometer”}
downscale_method (Literal['mean', 'nearest', 'gaussian']) – Method to use for downscaling; default “mean”. “mean” averages each block of pixels (a box filter followed by subsampling, also called area downsampling) and is intended for intensity images. “nearest” takes one pixel per block and should be used for label images. “gaussian” is a deprecated alias for “mean”.
scale_transformations (Dict[str, Any] | None) –
Optional dictionary specifying scale values for dimensions. Examples:
{“z”: 0.25, “y”: 0.1, “x”: 0.1} for spatial dimensions
{“t”: 0.5, “z”: 0.25, “y”: 0.1, “x”: 0.1} including time axis
Units are determined by the axis_units parameter. Scale values will be automatically adjusted for each downscale level.
downscale_levels (int | None) – Optional number of downscale levels to create. If
None, no downscaling is performed.downscale_factor (int) – Integer factor (>= 2) by which each level is downscaled relative to the previous one (default: 2).
overwrite (bool) – Whether to overwrite existing files.
omero_metadata (Omero | None) – Deprecated; use
channelsinstead. Optional OMERO metadata for channel display configuration. Must be an Omero object containing channel information for image visualization. A channel without a color or window gets an automatic color or the full data range, because the spec requires both.channels (Dict[str, Any] | List[Any] | Omero | None) – Plain-Python channel description, an alternative to
omero_metadata. A dict keyed by label ({"DAPI": {"color": "0000FF", "window": (0, 4095)}}), a list of labels, a list of dicts, or an Omero object. Per-channel keys:color(hex without “#”, or “random”),window(“auto” (default), “minmax”, (start, end), a Window, or None, which is written as the full data range like “minmax”),familyandactive. Window min/max are the data’s min/max; “auto” start/end follow Fiji’s auto-contrast. Requires a “c” axis with one entry per channel. A channel without acolorgets a distinct automatic one, because the spec requires every channel to have a color.colors (Literal['random'] | None) – Kept for compatibility. Channels without a color always get an automatic one now, so “random” has no further effect.
color_seed (int) – Changes the automatic palette; the same seed gives the same colors.
name (str | None) – Name stored in the multiscale metadata. Defaults to the file name of
pathwithout its extension.
- classmethod from_existing(path, **unexpected)¶
Attach a Writer to an OME-Zarr image that is already on disk.
The returned Writer is only for adding to the image, e.g. with
add_labels();write()is disabled so the image cannot be overwritten. Everythingadd_labelsneeds is read from the image’s metadata: its axes, shape, pixel sizes, number of levels and downscale factor. No pixel data is read.The image’s pyramid must be one this library could have written: only Y and X downscaled, by a constant integer factor, with scales that follow, and no translation or multiscale-level coordinateTransformations. Anything else raises a ValueError, because labels written with it would not line up with the image.
- Parameters:
- Raises:
FileNotFoundError – If
pathdoes not exist.ValueError – If
pathis not an OME-Zarr 0.5 image, its group holds more than onemultiscalesentry, or its pyramid is not one that labels can be written for.TypeError – If any other argument is passed.
from_existingnever overwrites the image, so it has nooverwriteargument; to replace a label image, passoverwrite=Truetoadd_labels().
- Return type:
- property downscale_method: Literal['mean', 'nearest']¶
Get the downscale method from the downscaler.
- add_labels(name, array, colors=None, properties=None, source_image='../../', overwrite=False, downscale_method='nearest', downscale_levels=None, downscale_factor=None, chunks=None, shards=None, compressors=None)¶
Attach a label image to an existing OME-Zarr image group.
This creates the NGFF 0.5 structure expected for labeled segmentation masks:
parent image group: ome.labels = [“<name>”]
labels/<name>/zarr.json: ome.multiscales + ome.image-label metadata
label image arrays written as a multiscale pyramid
See
https://ngff.openmicroscopy.org/specifications/0.5/index.html#labels-metadatafor details.- Parameters:
name (str) – Name of the label image as it will appear under the parent labels group.
array (Array | ndarray) – Label array to attach. Must have an integer data type (uint8, int8, uint16, int16, uint32, int32, uint64 or int64); float and boolean arrays are rejected. Must have the same dimensions as the source image; each non-spatial axis (e.g. c, z, t) may have size 1 instead of the image’s size, per the NGFF spec. Y/X must match the image.
colors (List[Dict[str, Any]] | None) – Optional list of {“label-value”: …, “rgba”: […]} entries.
properties (List[Dict[str, Any]] | None) – Optional list of label metadata entries.
source_image (str) – Relative path from the label image group to the source image group.
overwrite (bool) – If True, overwrite an existing label image with the same name.
downscale_method (Literal['mean', 'nearest', 'gaussian'] | None) – Label images should typically use nearest-neighbor downsampling.
downscale_levels (int | None) – Deprecated. The label always gets the same number of levels as the image on disk, as the spec requires. Passing the image’s own value emits a DeprecationWarning; any other value raises.
downscale_factor (int | None) – Optional override for the label downscaling factor. It must still allow as many levels as the image has.
chunks (int | tuple | str | None) – Chunk specification for label arrays.
compressors (CompressorsLike | None) – Optional compressor configuration.
- Returns:
The newly created label group.
- Return type:
- write(chunks=None, shards=None, compressors=None)¶
Write the image as OME-Zarr.
Creates a complete OME-Zarr file with:
Multiscale pyramid datasets
Proper OME-Zarr 0.5 metadata
Coordinate transformations for each level
Zarr arrays for each resolution level
- Parameters:
chunks (int | tuple | str | None) – Chunk shape for zarr arrays. Can be an int, tuple, or “auto”. If None, zarr will determine chunk size automatically.
shards (int | tuple | None) – Shard shape for zarr arrays (zarr v3 feature). Can be an int or tuple. If None, no sharding is applied.
compressors (CompressorsLike | None) – List of compressors to apply to zarr arrays. Can be codec objects from zarr.codecs (e.g., BloscCodec, GzipCodec, ZstdCodec) or a single compressor. If None, zarr will use default compression.
- Return type:
None