spacr.napari_bridge¶
Workflow inputs and outputs¶
Napari Bridge¶
Send the matching image/labels to napari and import the revised labels back with field identity preserved.
Open: Make Masks → Napari Bridge.
Inputs and outputs below include conditional alternatives. The guidance and handoff notes say which route applies.
Inputs
Microscope images — Source image folder; original files, supported vendor files or imported TIFFs.
Label masks — masks/ when retained, or explicitly saved image/mask pairs. Intermediate masks may be removed by cleanup.
Outputs
Label masks — masks/ when retained, or explicitly saved image/mask pairs. Intermediate masks may be removed by cleanup.
Send a mask to napari for correction and read the corrected mask back.
spaCR has its own brush (spacr.curation, spacr.qt.layer_viewer,
spacr.qt.curation_tool): a world-space brush over a labels layer, with
track curation beside it and an append-only ledger under both. This module
does not replace them. It lets users who already work in napari correct a
mask there with napari’s fill tool, polygon tool, keybindings and plugins.
So: a mask goes out to napari, the user corrects it there, and it comes back.
Round-trip fidelity¶
The returned mask must equal the corrected layer exactly. The following rules apply, and each is covered by a test:
Label values survive exactly. Label 41 comes back as 41 and not as 1, not renumbered, not relabelled by connectivity.
to_spacr_mask()casts back to spaCR’suint16mask convention (spacr.mask_io.save_mask()) and refuses a label that would not fit rather than letting it wrap —np.uint16(70000)is4464without a warning, which would silently assign the cell a different label.Orientation survives exactly. A napari 2-D layer’s array axes are
(row, column), which is numpy’s order and spaCR’s order, so the correct amount of transposing is none. The test uses a non-square image, because a spurious.Tis not detectable on a square one.The shape may not change. napari’s brush cannot change an array’s shape, but a caller handing back the wrong layer can, and that is a mistake worth a refusal rather than a resize.
Corrections are recorded, the same way as spaCR’s own¶
Every write-back appends to the artefact’s spacr.curation.CurationLog
— the same sidecar the brush writes, in the same append-only form. Without
the record, a hand-edited mask could not be told apart from a segmented one.
spacr.curation.is_curated() reports a napari correction the same way it
reports a brush stroke.
napari is optional, and is never imported at module scope¶
napari is declared in the napari extra, never in the core
dependencies, and every import of it here is inside the function that needs
it, for two reasons:
it pulls a second Qt stack, and this module is imported by a settings panel inside spaCR’s own PySide6 application;
the missing-dependency path must print
pip install "spacr[napari]"instead of a raw import traceback.require_napari()is that path, followingspacr.qt._QT_MISSING_MESSAGEandspacr.ome_zarr.require_zarr().
Everything except require_napari(), open_in_napari() and
run_event_loop() works with no napari installed at all, which is also
how the fidelity tests run: layer_specs() and labels_from_viewer()
speak to a duck-typed viewer, so the conversion either side of napari is
exercised for real without one.
Attributes¶
Exceptions¶
A mask came back in a shape this module will not silently accept. |
|
|
Classes¶
What one round trip changed, and where it was recorded. |
|
A field's mask, and optionally its image, prepared for napari. |
Functions¶
|
Add the field's layers to |
|
The whole round trip: open in napari, wait, take the mask back. |
|
Take the corrected labels back out of a viewer. |
|
What napari should be asked to add, as plain dictionaries. |
|
Read a field's mask, and optionally its image, ready for napari. |
|
The install instruction, naming the module that was actually missing. |
|
Whether napari can be imported. Never raises. |
|
Open the field in napari and return the viewer. |
|
Read an image file for display beside the mask. |
|
Import and return |
|
Block until the napari window is closed. Headless callers only. |
|
Convert an array back to spaCR's mask convention, or refuse. |
|
Write a corrected mask the way spaCR writes masks, and record it. |
Module Contents¶
- exception spacr.napari_bridge.MaskFidelityError[source]¶
Bases:
ValueErrorA mask came back in a shape this module will not silently accept.
Raised rather than corrected. Every case it covers — a label too large for
uint16, a negative label, a changed array shape, fractional values — is one where “doing something sensible” means quietly writing a different mask than the user drew.Initialize self. See help(type(self)) for accurate signature.
- exception spacr.napari_bridge.NapariExtraMissing[source]¶
Bases:
ImportErrornapariis not installed.An
ImportErrorsubclass, so a caller already guarding withexcept ImportErrorkeeps working. Its message isNAPARI_MISSING_MESSAGE, which names the missing module and the install command.Initialize self. See help(type(self)) for accurate signature.
- class spacr.napari_bridge.CorrectionResult[source]¶
What one round trip changed, and where it was recorded.
- Parameters:
mask_path – the file that was written, or would have been.
mask – the corrected mask, in spaCR’s convention.
changed_pixels – how many elements differ from what was there.
added – labels present now that were not before.
removed – labels that were there and are gone.
altered – labels present in both whose pixels moved.
log_path – the curation ledger that was appended to, or
"".edit – the
spacr.curation.CurationEditthat was appended.written – whether the mask file was actually rewritten. False for a round trip that changed nothing — see
write_back().
- class spacr.napari_bridge.MaskHandoff[source]¶
A field’s mask, and optionally its image, prepared for napari.
- Parameters:
mask – the label array,
uint16, exactly as it is on disk.mask_path – where it came from, and where a correction is written back. Also what the curation ledger is named after.
image – the image to show under it, or None.
image_path – where that came from.
name – the labels layer’s name in napari, and what is looked for on the way back.
scale – per-axis world scale handed to napari, when the field is calibrated. Empty means one world unit per pixel.
- spacr.napari_bridge.add_to_viewer(viewer: Any, handoff: MaskHandoff) Tuple[Any, ...][source]¶
Add the field’s layers to
viewer. Returns the layers it made.vieweris duck-typed on purpose: anything withadd_imageandadd_labelswill do, which is what lets the round trip be tested for real without napari installed.- Parameters:
viewer – a
napari.Viewer, or anything shaped like one.handoff – the field.
- spacr.napari_bridge.correct_mask(mask_path: Any, image_path: Any = '', *, viewer: Any = None, block: bool = True, write: bool = True, name: str = LABELS_LAYER_NAME) CorrectionResult[source]¶
The whole round trip: open in napari, wait, take the mask back.
For a script or a notebook. Not for use from inside spaCR’s own Qt application with
block=True— seerun_event_loop(); the GUI screen callsopen_in_napari()andlabels_from_viewer()separately, driven by the user.- Parameters:
mask_path – the mask to correct. The corrected one is written back here, and the ledger beside it.
image_path – the image to show under it.
viewer – an existing viewer, instead of opening one.
block – run the napari event loop and return when the window closes. False returns as soon as the viewer is open, which is only useful when the caller drives the loop itself.
write – passed to
write_back().name – the labels layer’s name, on the way out and back.
- Returns:
- Raises:
NapariExtraMissing – when napari is not installed.
- spacr.napari_bridge.labels_from_viewer(viewer: Any, *, name: str = LABELS_LAYER_NAME) numpy.ndarray[source]¶
Take the corrected labels back out of a viewer.
- Parameters:
viewer – a
napari.Viewer, or anything whoselayersare iterable and carrynameanddata.name – which layer to take. Falls back to the only labels-shaped layer when the name is not found, so edits on a renamed layer are still read back.
- Returns:
the layer’s array, converted with
to_spacr_mask().- Raises:
MaskFidelityError – when there is no such layer, or when what came back is not a mask spaCR can write.
- spacr.napari_bridge.layer_specs(handoff: MaskHandoff) Tuple[Dict[str, Any], ...][source]¶
What napari should be asked to add, as plain dictionaries.
Separated from the call that adds them so the contents of the handoff — which array, under which name, at which scale, with no axis reordering — can be asserted with no napari installed. Each dict carries a
"kind"naming theadd_*method it belongs to; everything else is keyword arguments for it.- Parameters:
handoff – the field.
- Returns:
the image spec (when there is an image) then the labels spec.
- spacr.napari_bridge.load_handoff(mask_path: Any, image_path: Any = '', *, name: str = LABELS_LAYER_NAME, scale: Sequence[float] = ()) MaskHandoff[source]¶
Read a field’s mask, and optionally its image, ready for napari.
The mask is read with
spacr.mask_io.load_mask(), which is spaCR’s own reader and already probes.tif/.tiff/.npyfor a bare stem, so the mask is read the same way the rest of the pipeline reads it.- Parameters:
mask_path – the label mask.
image_path – the image to show under it. Optional.
name – the labels layer’s name.
scale – per-axis world scale.
- Returns:
a
MaskHandoff.- Raises:
FileNotFoundError – when the mask is not there.
- spacr.napari_bridge.missing_napari_message(module: str = 'napari') str[source]¶
The install instruction, naming the module that was actually missing.
- spacr.napari_bridge.napari_available() bool[source]¶
Whether napari can be imported. Never raises.
Uses
importlib.util.find_spec()without importing napari, so a screen can disable a button before the user presses it.
- spacr.napari_bridge.open_in_napari(handoff: MaskHandoff, *, viewer: Any = None, title: str = '') Any[source]¶
Open the field in napari and return the viewer.
Does not start an event loop: see
run_event_loop()for why that is a separate decision.- Parameters:
handoff – the field.
viewer – an existing viewer to add to, instead of making one.
title – the window title. Defaults to the mask’s filename.
- Returns:
the viewer.
- Raises:
NapariExtraMissing – when napari is not installed.
- spacr.napari_bridge.read_image(path: Any) numpy.ndarray[source]¶
Read an image file for display beside the mask.
TIFFs go through
tifffileso a 16-bit field keeps its bit depth,.npythrough numpy, everything else through Pillow — the same three branches, in the same order, asspacr.qt.widgets.live_preview.load_preview_image(), written here because this module must not import anything fromspacr.qt.- Parameters:
path – the file.
- Returns:
the array exactly as stored, with no rescaling and no axis reordering.
- Raises:
FileNotFoundError – when there is nothing there.
- spacr.napari_bridge.require_napari() Any[source]¶
Import and return
napari, or raiseNapariExtraMissing.The only place this module imports napari. The module docstring explains why napari is never imported at module scope.
- Returns:
the imported
naparimodule.- Raises:
NapariExtraMissing – when the extra is not installed.
- spacr.napari_bridge.run_event_loop() None[source]¶
Block until the napari window is closed. Headless callers only.
A separate function rather than a flag on
open_in_napari(), because whether it may be called depends on where the caller runs:from a script or a notebook it is what makes
correct_maskmean “correct it, then take it back”;from inside spaCR’s own Qt application it must never be called — there is already a running
QApplicationevent loop, and starting a second one nests them. The GUI screen therefore opens the viewer and lets the user press “Take the mask back” when they are done.
- Raises:
NapariExtraMissing – when napari is not installed.
- spacr.napari_bridge.to_spacr_mask(data: Any) numpy.ndarray[source]¶
Convert an array back to spaCR’s mask convention, or refuse.
This function implements the round-trip fidelity rules. It casts to
MASK_DTYPEand does nothing else: no transpose, no flip, no relabelling, no renumbering. A napari 2-D layer’s axes are(row, column), the same order numpy and spaCR use, so any reordering here would be an invented one.- Parameters:
data – whatever came out of the labels layer.
- Returns:
a
uint16array with the same shape and the same label values.- Raises:
MaskFidelityError – for a negative label, a fractional value, a label that does not fit in
uint16, or an array that is not 2-D or 3-D. Each is refused rather than repaired, because every repair would silently change which pixel belongs to which cell.
- spacr.napari_bridge.write_back(mask_path: Any, corrected: Any, *, original: numpy.ndarray | None = None, source: str = LOG_SOURCE, extra: Mapping[str, Any] | None = None, write: bool = True) CorrectionResult[source]¶
Write a corrected mask the way spaCR writes masks, and record it.
The function writes the mask file and appends a ledger entry.
The mask goes through
spacr.mask_io.save_mask(), which is the one place spaCR decides what a mask file is —uint16, LZW-compressed TIFF by default,.npywhen the path orSPACR_MASK_FORMATsays so. A corrected mask written any other way would be a mask the rest of the pipeline reads differently from the one segmentation produced.The correction goes into the artefact’s
spacr.curation.CurationLog, appended, never rewritten, sospacr.curation.is_curated()tells a curated dataset from a raw one whether the editing happened in spaCR’s brush or in napari.A round trip that changed nothing writes nothing and records nothing. That is the same rule
spacr.curation.MaskCuration.end_stroke()applies to a stroke that moved no pixels: no no-op entry is added to the ledger, and the file is not rewritten, so its mtime does not change and downstream artifacts are not marked stale.- Parameters:
mask_path – where the mask lives. The ledger is written beside it.
corrected – the corrected labels, from napari or anywhere.
original – what it was before. Read from
mask_pathwhen not given, so the diff is against what is actually on disk.source – what to stamp a new ledger with. An existing ledger keeps its own; the tool that made each edit is recorded on the edit.
extra – anything else to record on the ledger entry.
write – False computes and records nothing, returning the diff only — for a preview.
- Returns:
- Raises:
MaskFidelityError – when the mask cannot be written faithfully, or when its shape changed.
- spacr.napari_bridge.NAPARI_MISSING_MESSAGE = Multiline-String[source]¶
Show Value
"""Correcting a mask in napari needs the optional `napari` extra, which is not installed in this environment (missing module: {module}). Install it with: python -m pip install "spacr[napari]" You do not need it to correct masks: spaCR's own Curate screen has a brush, a label picker and track curation, and records the same ledger. This bridge is for people who would rather work in napari."""