Skip to content

napari viewer plugin

Open an OME-ZARR image and overlay the labels produced by tile_process as a napari Labels layer in a single call. Requires the optional napari extra (pip install "patchworks[napari]").

patchworks.plugins.napari.view_in_napari(image: Union[da.Array, str, Path], labels: Union[da.Array, str, Path, None] = None, *, channel: int | None = None, labels_component: str = 'labels', image_name: str = 'image', labels_name: str = 'labels', glasbey: bool = True, show: bool = True, split_channels: bool = True, shown: 'Sequence[int] | None' = None, hover: bool = True, **add_image_kwargs: Any)

Open image in napari and overlay labels as a Labels layer.

Parameters:

Name Type Description Default
image (Array, str or Path)

OME-ZARR store (multi-scale aware), any bioio-readable file, or an in-memory array.

required
labels (Array, str, Path or None)

Label array to overlay. A plain .zarr store written by tile_process is read from its labels_component; an OME-ZARR pyramid is shown multi-scale. None (default) auto-loads every label image stored inside the OME-ZARR under labels/<name>/ — the place tile_process writes them by default — each as its own Labels layer. (Falls back to image-only if there are none.)

None
channel int or None

Channel to display from the image. None (default) shows every channel — the segmentation channel doesn't need to match what you view. Pass an int to show just that one.

None
labels_component str

Array name inside a plain-zarr label store (default "labels", matching tile_process's output_component).

'labels'
image_name str

Layer names shown in napari.

'image'
labels_name str

Layer names shown in napari.

'image'
glasbey bool

Colour the labels with a glasbey palette (many distinct, high-contrast colours, tuned to read on the dark canvas) instead of napari's default. Default True.

True
show bool

Start the napari event loop (blocking). Set False in scripts/tests that manage the loop themselves.

True
split_channels bool

Each channel its own layer (default), so several can be shown together, each in its own colour; False: one layer with a channel slider.

True
shown sequence of int

The channels visible at first (default: the first). A hidden channel is not read until it is switched on.

None
hover bool

Show each object's parent and children when hovering it, from the object tables, read in the background once the window is up (for a whole slide, minutes of reading the network shares with zooming).

True
**add_image_kwargs Any

Extra keyword arguments forwarded to viewer.add_image (e.g. colormap, contrast_limits).

{}

Returns:

Type Description
Viewer

The viewer instance (useful when show=False).

Notes

In 3-D view (the cube icon, or viewer.dims.ndisplay = 3), napari always shows the coarsest pyramid level — there is no automatic zoom-based switching in 3-D, only in 2-D. To pin a specific resolution (needs napari>=0.7.1)::

viewer.layers["labels"].locked_data_level = 0   # full resolution
viewer.layers["labels"].locked_data_level = None  # back to coarsest

A widget for this is also in the layer controls panel in napari>=0.7.1.

Examples:

>>> view_in_napari("scan.zarr")  # auto-loads scan.zarr/labels/*
Source code in src/patchworks/plugins/napari.py
def view_in_napari(
    image: Union[da.Array, str, Path],
    labels: Union[da.Array, str, Path, None] = None,
    *,
    channel: int | None = None,
    labels_component: str = "labels",
    image_name: str = "image",
    labels_name: str = "labels",
    glasbey: bool = True,
    show: bool = True,
    split_channels: bool = True,
    shown: "Sequence[int] | None" = None,
    hover: bool = True,
    **add_image_kwargs: Any,
):
    """Open *image* in napari and overlay *labels* as a Labels layer.

    Parameters
    ----------
    image : da.Array, str or Path
        OME-ZARR store (multi-scale aware), any bioio-readable file, or an
        in-memory array.
    labels : da.Array, str, Path or None
        Label array to overlay. A plain `.zarr` store written by
        `tile_process` is read from its `labels_component`; an OME-ZARR
        pyramid is shown multi-scale. `None` (default) **auto-loads** every
        label image stored inside the OME-ZARR under `labels/<name>/` — the
        place `tile_process` writes them by default — each as its own Labels
        layer. (Falls back to image-only if there are none.)
    channel : int or None, optional
        Channel to display from the image. `None` (default) shows every
        channel — the segmentation channel doesn't need to match what you
        view. Pass an int to show just that one.
    labels_component : str, optional
        Array name inside a plain-zarr label store (default `"labels"`,
        matching `tile_process`'s `output_component`).
    image_name, labels_name : str, optional
        Layer names shown in napari.
    glasbey : bool, optional
        Colour the labels with a glasbey palette (many distinct, high-contrast
        colours, tuned to read on the dark canvas) instead of napari's default.
        Default `True`.
    show : bool, optional
        Start the napari event loop (blocking). Set `False` in scripts/tests
        that manage the loop themselves.
    split_channels : bool, optional
        Each channel its own layer (default), so several can be shown
        together, each in its own colour; `False`: one layer with a
        channel slider.
    shown : sequence of int, optional
        The channels visible at first (default: the first). A hidden
        channel is not read until it is switched on.
    hover : bool, optional
        Show each object's parent and children when hovering it, from the
        object tables, read in the background once the window is up (for a
        whole slide, minutes of reading the network shares with zooming).
    **add_image_kwargs
        Extra keyword arguments forwarded to `viewer.add_image`
        (e.g. `colormap`, `contrast_limits`).

    Returns
    -------
    napari.Viewer
        The viewer instance (useful when `show=False`).

    Notes
    -----
    In 3-D view (the cube icon, or `viewer.dims.ndisplay = 3`), napari
    always shows the **coarsest** pyramid level — there is no automatic
    zoom-based switching in 3-D, only in 2-D. To pin a specific resolution
    (needs `napari>=0.7.1`)::

        viewer.layers["labels"].locked_data_level = 0   # full resolution
        viewer.layers["labels"].locked_data_level = None  # back to coarsest

    A widget for this is also in the layer controls panel in napari>=0.7.1.

    Examples
    --------
    >>> view_in_napari("scan.zarr")  # auto-loads scan.zarr/labels/*  # doctest: +SKIP
    """
    napari = _require_napari()

    with _timed("napari window"):
        viewer = napari.Viewer()
    with _timed("image: opening its arrays"):
        layers = image_layers(
            image, channel, image_name, add_image_kwargs, split_channels, shown
        )
    with _timed("image: napari adding the layer"):
        for data, name, kwargs in layers:
            viewer.add_image(data, name=name, **kwargs)

    label_kwargs: dict[str, Any] = {}
    if glasbey:
        from napari.utils.colormaps import CyclicLabelColormap

        # Glasbey colours, cycled per label.
        colors = np.array(
            [
                [int(h[i : i + 2], 16) / 255 for i in (0, 2, 4)] + [1.0]
                for h in GLASBEY_256
            ]
        )
        label_kwargs["colormap"] = CyclicLabelColormap(colors=colors)

    if labels is not None:
        lab = _resolve_labels(labels, labels_component)
        lab_ndim = lab[0].ndim if isinstance(lab, list) else lab.ndim
        lab_scale, lab_units = (
            _pyramid_calibration(labels, lab_ndim)
            if _is_zarr(labels)
            else (None, None)
        )
        metadata = _label_hint(labels) if _is_zarr(labels) else {}
        viewer.add_labels(
            lab,
            name=labels_name,
            multiscale=isinstance(lab, list),
            scale=lab_scale,
            translate=(
                _pyramid_translate(labels, lab_ndim)
                if _is_zarr(labels)
                else None
            ),
            units=lab_units,
            metadata=metadata,
            **label_kwargs,
        )
    elif _is_zarr(image):
        # No labels given: every label image in the store, each as a multiscale
        # layer (also for one level, for 3-D resolution switching).
        names = _inner_label_names(image)
        if not names:
            logger.warning(
                "%s has no label images under labels/, so nothing was "
                "overlaid. Pass labels=<path> explicitly if they live "
                "somewhere else.",
                image,
            )
        else:
            logger.info(
                "auto-loading %d label image(s) from %s/labels: %s",
                len(names),
                image,
                ", ".join(names),
            )
        loaded = 0
        for name in names:
            store = f"{image}/labels/{name}"
            # One bad label image must not hide the others.
            try:
                lab = _label_levels(store)
                lab_scale, lab_units = _pyramid_calibration(store, lab[0].ndim)
                with _timed(f"labels/{name}"):
                    viewer.add_labels(
                        lab,
                        name=name,
                        multiscale=True,
                        scale=lab_scale,
                        translate=_pyramid_translate(store, lab[0].ndim),
                        units=lab_units,
                        metadata=_label_hint(store),
                        **label_kwargs,
                    )
            except Exception:
                logger.exception(
                    "could not add labels/%s as a layer; skipping it and "
                    "continuing with the rest.",
                    name,
                )
                continue
            loaded += 1
            logger.info("auto-loaded labels/%s from %s", name, image)
        if not hover:
            pass
        elif loaded and show:
            # Minutes for a whole slide's tables: read after the window
            # is up, not before.
            _show_relations_later(viewer, image)
        elif loaded:
            with _timed("object tables, for hovering"):
                _show_relations(viewer, image)
        if names and not loaded:
            logger.error(
                "found %d label image(s) in %s/labels but none could be "
                "added -- see the errors above.",
                len(names),
                image,
            )

    _name_axes(viewer, image)
    if show:
        napari.run()
    return viewer