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 or channels
(add_channels()) 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, with
add_labels()oradd_channels();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, source_level=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.
source_level (int | None) – Resolution level of the image that
arraywas computed on.None(default) meansarrayis at full resolution (level 0). If given,arrayis upscaled to level 0 with nearest-neighbour repetition (lazily, for dask arrays) before the label pyramid is built. The per-axis factors come from the image’s scale transformations, so anisotropic pyramids are handled. Non-spatial axes of size 1 are left as they are.
- Returns:
The newly created label group.
- Raises:
ValueError – If
arrayis boolean (convert it explicitly, e.g.mask.astype("uint8")), ifsource_leveldoes not exist, or ifarraydoes not match the shape of that level.- Return type:
- add_channels(array, channels, downscale_method='mean')¶
Append channels to the image on disk, e.g. a background-subtracted copy.
arrayis the new channels at full resolution (level 0). Its pyramid is built with the image’s own downscale factor and number of levels, then thecaxis of every level is extended andomero.channelsgets one entry per new channel. The existing channels are not rewritten.- Parameters:
array (Array | ndarray) – NumPy or dask array with the image’s dimensions. Every axis but
cmust match the image, and the dtype must equal the image’s (all channels of a zarr array share one dtype). Itscsize is the number of new channels.channels (Any) – One entry per new channel, in any form
Writer(channels=...)accepts except anOmeroobject: a list of labels, a list of dicts or a dict keyed by label. Per channel:label,color,window,familyandactive;active=Falsehides the channel by default in viewers. Labels must differ from those already in the image. A missing color gets an automatic one that avoids the image’s existing colors.downscale_method (Literal['mean', 'nearest']) – “mean” (default) for intensity data.
- Raises:
RuntimeError – If the Writer was not made with
from_existing().TypeError – If
arrayis not a NumPy or dask array.ValueError – If the image has no
caxis or noomerochannels matching itscaxis, ifarraydoes not match the image’s shape or dtype, ifchannelsdoes not have one entry per new channel, or if a label already exists.
- Return type:
None
If writing fails part way, the
caxes are shrunk back and the image is left as it was.
- 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