micro_sam.sam_annotator.annotator

  1from typing import Optional, Tuple, Union
  2
  3import numpy as np
  4
  5import torch
  6
  7import napari
  8from napari.utils.notifications import show_info
  9
 10from .. import util
 11from . import util as vutil
 12from . import _widgets as widgets
 13from ._state import AnnotatorState
 14from ._titles import get_dock_title
 15from ._annotator import _AnnotatorBase
 16from ..v2.util import DEFAULT_MODEL, resolve_default_tiling
 17from .util import _sync_embedding_widget, _validate_sam2_model_type
 18
 19
 20def detect_ndim_from_viewer(viewer: "napari.viewer.Viewer") -> int:
 21    """Detect the dimensionality from image layers already loaded in the viewer.
 22
 23    Used when the annotator is launched as a napari plugin widget without an explicit
 24    ndim. Falls back to 2 when no image has been loaded yet, e.g. when the widget is
 25    opened from the napari Plugins menu before any image is added.
 26
 27    Args:
 28        viewer: The napari viewer.
 29
 30    Returns:
 31        The detected number of spatial dimensions (2 or 3).
 32    """
 33    image_layers = [layer for layer in viewer.layers if isinstance(layer, napari.layers.Image)]
 34    if image_layers:
 35        # Use the normalizer so it handles singletons and channels. Unsupported inputs
 36        # default to 2D here so the widget can open. Then '_on_image_selection_changed'
 37        # reports the issue to the user instead of crashing construction.
 38        try:
 39            return vutil.prepare_annotation_image(image_layers[0].data)[1]
 40        except ValueError:
 41            return 2
 42    return 2
 43
 44
 45class Annotator(_AnnotatorBase):
 46    """Unified annotator for 2D and 3D images.
 47
 48    This class handles both 2D and 3D annotation, with dimensionality
 49    controlled by the `ndim` parameter or auto-detected from the image.
 50    """
 51
 52    def _create_embedding_widget(self):
 53        # Expose the 'image dimensions' (ndim) override here: the segmentation annotator is the only
 54        # one that wires it into image normalization (it handles both 2d and 3d data).
 55        return widgets.EmbeddingWidget(ndim_choice=True)
 56
 57    def _get_widgets(self):
 58        """Create the widgets for the segmentation annotator.
 59
 60        The interactive segmentation widget merges the prompt menu, the segment and the
 61        clear controls into a single ndim-aware widget placed right after the embeddings.
 62        """
 63        # Automatic segmentation needs a UniSAM2 decoder. At startup the decoder is not loaded yet
 64        # (only on 'Compute Embeddings'), so also treat the default model as decoder-capable when it
 65        # has a registered decoder - otherwise the widget would start disabled for the Microscopy
 66        # default. This is re-synced after compute via '_sync_autosegment_widget' once the actual
 67        # decoder is known.
 68        from ..v2.util import DEFAULT_MODEL, has_registered_decoder
 69        with_decoder = AnnotatorState().decoder is not None or has_registered_decoder(DEFAULT_MODEL)
 70        return {
 71            "interactive": widgets.InteractiveSegmentationWidget(
 72                self._viewer, ndim=self._ndim, prompt_widget=self._prompt_widget,
 73            ),
 74            "autosegment": widgets.AutoSegmentWidget(
 75                self._viewer, with_decoder=with_decoder, volumetric=(self._ndim == 3),
 76            ),
 77            "commit": widgets.commit(),
 78        }
 79
 80    def _create_keybindings(self):
 81        """Bind the keys to the merged interactive segmentation widget."""
 82        interactive = self._widgets["interactive"]
 83
 84        @self._viewer.bind_key("s", overwrite=True)
 85        def _segment(viewer):
 86            interactive.segment(viewer)
 87
 88        # We also need to over-write the keybindings for the prompt layers.
 89        # See https://github.com/napari/napari/issues/7302 for details.
 90        prompt_layer = self._viewer.layers["prompts"]
 91        point_prompt_layer = self._viewer.layers["point_prompts"]
 92
 93        @prompt_layer.bind_key("s", overwrite=True)
 94        def _segment_prompts(event):
 95            interactive.segment(self._viewer)
 96
 97        @point_prompt_layer.bind_key("s", overwrite=True)
 98        def _segment_point_prompts(event):
 99            interactive.segment(self._viewer)
100
101        # The layer the key reached is the active one, so it goes first: only it relabels a selected
102        # scribble. The viewer-level fallback below has no active prompt layer, so it relabels none.
103        @prompt_layer.bind_key("t", overwrite=True)
104        def _toggle_shape_prompt_label(event=None):
105            vutil.toggle_label(self._shape_prompt_layer, self._point_prompt_layer)
106
107        @point_prompt_layer.bind_key("t", overwrite=True)
108        def _toggle_point_prompt_label(event=None):
109            vutil.toggle_label(self._point_prompt_layer, self._shape_prompt_layer)
110
111        @self._viewer.bind_key("c", overwrite=True)
112        def _commit(viewer):
113            self._widgets["commit"](viewer)
114
115        @self._viewer.bind_key("t", overwrite=True)
116        def _toggle_label(event=None):
117            vutil.toggle_label(self._point_prompt_layer, self._shape_prompt_layer)
118
119        @self._viewer.bind_key("Shift-C", overwrite=True)
120        def _clear_annotations(viewer):
121            interactive.clear(viewer)
122
123    def __init__(
124        self,
125        viewer: "napari.viewer.Viewer",
126        ndim: Optional[int] = None,
127        reset_state: bool = True,
128    ) -> None:
129        """Create the annotator GUI.
130
131        Args:
132            viewer: The napari viewer.
133            ndim: The number of spatial dimensions (2 or 3). If None, auto-detected from the image.
134            reset_state: Whether to reset the annotator state.
135
136        Raises:
137            ValueError: If ndim is invalid or doesn't match the image shape.
138        """
139        # Auto-detect ndim when launched as a napari widget without an explicit ndim.
140        # Detect from an already-loaded image layer, defaulting to 2D when none is present
141        # (e.g. when the widget is opened from the napari Plugins menu before loading an image).
142        if ndim is None:
143            ndim = detect_ndim_from_viewer(viewer)
144
145        # Validate ndim
146        if ndim not in (2, 3):
147            raise ValueError(f"Invalid ndim: {ndim}. Expected 2 or 3.")
148
149        super().__init__(viewer=viewer, ndim=ndim)
150
151        # Set the expected annotator class to the state.
152        state = AnnotatorState()
153
154        # Reset the state.
155        if reset_state:
156            state.reset_state()
157
158        state.annotator = self
159
160        # Rebuild the annotator if an image with a different dimensionality is selected as input.
161        # This handles loading e.g. a 3D image after the widget was opened from the Plugins menu.
162        self._embedding_widget.image_selection.changed.connect(self._on_image_selection_changed)
163
164        # Re-normalize when the user changes the 'image dimensions' (ndim) override.
165        if getattr(self._embedding_widget, "ndim_choice", False):
166            self._embedding_widget.image_ndim_dropdown.currentTextChanged.connect(self._on_ndim_mode_changed)
167
168        # Normalize and align to any image that is already selected (e.g. opened from the
169        # Plugins menu after an image was loaded, so no selection-changed event will fire).
170        self._on_image_selection_changed()
171
172    def _on_image_selection_changed(self, *args):
173        """Normalize the selected image and rebuild the annotator if its dimensionality changed."""
174        # Skip while we replace the image layer ourselves during normalization.
175        if self._suppress_selection_rebuild:
176            return
177        image_layer = self._embedding_widget.image_selection.get_value()
178        if image_layer is None:
179            return
180        # Squeeze singletons and map channels to RGB, replacing the image layer if needed,
181        # so the image, segmentation and prompt layers all stay aligned. The 'image dimensions'
182        # override (auto/2d/3d) disambiguates multi-channel inputs. Unsupported inputs (e.g. 3D
183        # volumes with a channel axis) are reported instead of crashing the widget.
184        try:
185            image_layer, ndim = self._maybe_normalize_image_layer(
186                image_layer, ndim=self._embedding_widget._ndim_override()
187            )
188        except ValueError as e:
189            show_info(str(e))
190            return
191
192        # Detect an actual change of the selected image, tracked by layer identity (the state's
193        # 'image_name' is not reliably set on every code path, so we don't depend on it). The first
194        # call (during setup) just records the image and does not reset. A later switch to a
195        # different image layer triggers the reset below.
196        previous_layer = getattr(self, "_last_image_layer", None)
197        image_changed = previous_layer is not None and image_layer is not previous_layer
198        self._last_image_layer = image_layer
199
200        # When the selected image changes, reset everything so the tool behaves as if it was just
201        # opened on the new image: the precomputed embeddings, the model and everything derived from
202        # them belong to the previous image and must not be reused (they can even differ in
203        # dimensionality, e.g. 3D volume -> 2D image). 'reset_state' clears the state. Resetting the
204        # (shared, kept) embedding widget inputs restores the default model, tiling and save path. The
205        # forced rebuild recreates the dimension-specific widgets and napari layers, so all
206        # checkboxes are back to defaults, the autosegment cache is gone and the prompt / segmentation
207        # layers are cleared. The user recomputes embeddings for the new image via 'Compute Embeddings'.
208        if image_changed:
209            AnnotatorState().reset_state()
210            self._embedding_widget._reset_inputs_to_defaults()
211            self._rebuild_for_ndim(ndim, force=True)
212            return
213
214        if ndim != self._ndim:
215            self._rebuild_for_ndim(ndim)
216
217    def _on_ndim_mode_changed(self, *args):
218        """Re-interpret the current image when the 'image dimensions' override changes.
219
220        Unlike selecting a different image, this keeps the embedding-widget inputs (model, tiling and
221        the override itself); it only re-normalizes, clears the now-invalid embeddings / prompts and
222        rebuilds the layers for the resulting dimensionality.
223        """
224        if self._suppress_selection_rebuild:
225            return
226        image_layer = self._embedding_widget.image_selection.get_value()
227        if image_layer is None:
228            return
229        try:
230            image_layer, ndim = self._maybe_normalize_image_layer(
231                image_layer, ndim=self._embedding_widget._ndim_override()
232            )
233        except ValueError as e:
234            # The chosen override (e.g. '3d' on a 2D image) cannot be applied: warn in a modal dialog,
235            # recommend 'auto', and revert the dropdown to 'auto' so the tool is not stuck on the
236            # invalid choice.
237            from qtpy import QtWidgets
238            QtWidgets.QMessageBox.warning(
239                self, "Invalid image dimensions",
240                f"{e}\n\nThis dimensionality cannot be applied to the selected image. "
241                "Switching back to 'auto', which is recommended for automatic dimensionality detection.",
242                QtWidgets.QMessageBox.Ok,
243            )
244            dropdown = self._embedding_widget.image_ndim_dropdown
245            dropdown.blockSignals(True)
246            dropdown.setCurrentText("auto")
247            self._embedding_widget.image_ndim_mode = "auto"
248            dropdown.blockSignals(False)
249            return
250
251        # No effective change (same layer and dimensionality): keep the current work.
252        if image_layer is getattr(self, "_last_image_layer", None) and ndim == self._ndim:
253            return
254
255        self._last_image_layer = image_layer
256        AnnotatorState().reset_state()
257        self._rebuild_for_ndim(ndim, force=True)
258
259
260def annotator(
261    image: np.ndarray,
262    *,
263    ndim: Optional[int] = None,
264    embedding_path: Optional[Union[str, util.ImageEmbeddings]] = None,
265    segmentation_result: Optional[np.ndarray] = None,
266    model_type: str = DEFAULT_MODEL,
267    tile_shape: Optional[Tuple[int, int]] = None,
268    halo: Optional[Tuple[int, int]] = None,
269    return_viewer: bool = False,
270    viewer: Optional["napari.viewer.Viewer"] = None,
271    precompute_autoseg_state: bool = False,
272    checkpoint_path: Optional[str] = None,
273    decoder_path: Optional[str] = None,
274    device: Optional[Union[str, torch.device]] = None,
275    prefer_decoder: bool = True,
276) -> Optional["napari.viewer.Viewer"]:
277    """Start the annotation tool for a given image.
278
279    Args:
280        image: The image data (2D or 3D).
281        ndim: The number of spatial dimensions (2 or 3). If None, auto-detected from image shape.
282        embedding_path: Filepath where to save the embeddings
283            or the precompted image embeddings computed by `precompute_image_embeddings`.
284        segmentation_result: An initial segmentation to load.
285            This can be used to correct segmentations with Segment Anything or to save and load progress.
286            The segmentation will be loaded as the 'committed_objects' layer.
287        model_type: The Segment Anything 2 model to use. The name must start with 'hvit_'. For the available
288            models, see https://computational-cell-analytics.github.io/micro-sam/micro_sam.html#finetuned-models.
289        tile_shape: Shape of tiles for tiled embedding prediction. If `None`, reuse the tiling of
290            already cached embeddings, else use the default tiling for images exceeding the in-plane
291            size threshold, and pass smaller images to Segment Anything without tiling.
292        halo: Shape of the overlap between tiles, which is needed to segment objects on tile borders.
293            If `None`, use the default overlap whenever tiling is active.
294        return_viewer: Whether to return the napari viewer to further modify it before starting the tool.
295            By default, does not return the napari viewer.
296        viewer: The viewer to which the Segment Anything functionality should be added.
297            This enables using a pre-initialized viewer.
298        precompute_autoseg_state: Whether to precompute the automatic segmentation state (the decoder
299            predictions). Requires an embedding path and a model with a decoder; it is ignored for a
300            model without one. This will take more time when precomputing embeddings, but will then
301            make automatic segmentation much faster. By default, set to 'False'.
302        checkpoint_path: Path to a custom checkpoint from which to load the SAM model.
303        decoder_path: Path to a custom decoder checkpoint from which to load the `micro-sam` decoder.
304        device: The computational device to use for the SAM model.
305            By default, automatically chooses the best available device.
306        prefer_decoder: Whether to use decoder based instance segmentation if
307            the model used has an additional decoder for instance segmentation.
308            By default, set to 'True'.
309
310    Returns:
311        The napari viewer, only returned if `return_viewer=True`.
312
313    Raises:
314        ValueError: If the model is not a Segment Anything 2 model. Also if ndim is not valid or does not
315            match the image shape.
316    """
317    # Normalize the image: squeeze singletons and map the channel axis to RGB. The optional 'ndim'
318    # override disambiguates multi-channel inputs (e.g. reads a channels-first (C, H, W) array as a
319    # 2d image), consistent with the GUI's 'image dimensions' control. With ndim=None it is
320    # auto-detected. 'prepare_annotation_image' raises if the override cannot be applied to the shape.
321    _validate_sam2_model_type(model_type, "segmentation")
322    image, ndim, rgb = vutil.prepare_annotation_image(image, ndim=ndim)
323
324    # Extract image shape (strip RGB channel if present)
325    state = AnnotatorState()
326    state.image_shape = image.shape[:-1] if rgb else image.shape
327
328    # The API / CLI computes embeddings before creating the widget, so apply the same
329    # size heuristic here. Reuse these resolved settings when syncing the widget below.
330    tile_shape, halo = resolve_default_tiling(state.image_shape, tile_shape, halo, embedding_path)
331
332    # Initialize the predictor state
333    state.initialize_predictor(
334        image,
335        model_type=model_type,
336        save_path=embedding_path,
337        halo=halo,
338        tile_shape=tile_shape,
339        precompute_autoseg_state=precompute_autoseg_state,
340        ndim=ndim,
341        checkpoint_path=checkpoint_path,
342        decoder_path=decoder_path,
343        device=device,
344        prefer_decoder=prefer_decoder,
345        use_cli=True,
346    )
347
348    # Create or get viewer
349    if viewer is None:
350        viewer = napari.Viewer()
351
352    viewer.add_image(image, name="image", rgb=rgb)
353    annotator_instance = Annotator(viewer, ndim=ndim, reset_state=False)
354
355    # Trigger layer update of the annotator so that layers have the correct shape.
356    # And initialize the 'committed_objects' with the segmentation result if it was given.
357    annotator_instance._update_image(segmentation_result=segmentation_result)
358
359    # Add the annotator widget to the viewer and sync widgets.
360    viewer.window.add_dock_widget(annotator_instance, name=get_dock_title("segmentation"))
361    _sync_embedding_widget(
362        widget=state.widgets["embeddings"],
363        model_type=(
364            model_type
365            if checkpoint_path is None
366            else state.predictor.model_type
367        ),
368        save_path=embedding_path,
369        checkpoint_path=checkpoint_path,
370        device=device,
371        tile_shape=tile_shape,
372        halo=halo,
373    )
374
375    if return_viewer:
376        return viewer
377
378    napari.run()
def detect_ndim_from_viewer(viewer: napari.viewer.Viewer) -> int:
21def detect_ndim_from_viewer(viewer: "napari.viewer.Viewer") -> int:
22    """Detect the dimensionality from image layers already loaded in the viewer.
23
24    Used when the annotator is launched as a napari plugin widget without an explicit
25    ndim. Falls back to 2 when no image has been loaded yet, e.g. when the widget is
26    opened from the napari Plugins menu before any image is added.
27
28    Args:
29        viewer: The napari viewer.
30
31    Returns:
32        The detected number of spatial dimensions (2 or 3).
33    """
34    image_layers = [layer for layer in viewer.layers if isinstance(layer, napari.layers.Image)]
35    if image_layers:
36        # Use the normalizer so it handles singletons and channels. Unsupported inputs
37        # default to 2D here so the widget can open. Then '_on_image_selection_changed'
38        # reports the issue to the user instead of crashing construction.
39        try:
40            return vutil.prepare_annotation_image(image_layers[0].data)[1]
41        except ValueError:
42            return 2
43    return 2

Detect the dimensionality from image layers already loaded in the viewer.

Used when the annotator is launched as a napari plugin widget without an explicit ndim. Falls back to 2 when no image has been loaded yet, e.g. when the widget is opened from the napari Plugins menu before any image is added.

Arguments:
  • viewer: The napari viewer.
Returns:

The detected number of spatial dimensions (2 or 3).

 46class Annotator(_AnnotatorBase):
 47    """Unified annotator for 2D and 3D images.
 48
 49    This class handles both 2D and 3D annotation, with dimensionality
 50    controlled by the `ndim` parameter or auto-detected from the image.
 51    """
 52
 53    def _create_embedding_widget(self):
 54        # Expose the 'image dimensions' (ndim) override here: the segmentation annotator is the only
 55        # one that wires it into image normalization (it handles both 2d and 3d data).
 56        return widgets.EmbeddingWidget(ndim_choice=True)
 57
 58    def _get_widgets(self):
 59        """Create the widgets for the segmentation annotator.
 60
 61        The interactive segmentation widget merges the prompt menu, the segment and the
 62        clear controls into a single ndim-aware widget placed right after the embeddings.
 63        """
 64        # Automatic segmentation needs a UniSAM2 decoder. At startup the decoder is not loaded yet
 65        # (only on 'Compute Embeddings'), so also treat the default model as decoder-capable when it
 66        # has a registered decoder - otherwise the widget would start disabled for the Microscopy
 67        # default. This is re-synced after compute via '_sync_autosegment_widget' once the actual
 68        # decoder is known.
 69        from ..v2.util import DEFAULT_MODEL, has_registered_decoder
 70        with_decoder = AnnotatorState().decoder is not None or has_registered_decoder(DEFAULT_MODEL)
 71        return {
 72            "interactive": widgets.InteractiveSegmentationWidget(
 73                self._viewer, ndim=self._ndim, prompt_widget=self._prompt_widget,
 74            ),
 75            "autosegment": widgets.AutoSegmentWidget(
 76                self._viewer, with_decoder=with_decoder, volumetric=(self._ndim == 3),
 77            ),
 78            "commit": widgets.commit(),
 79        }
 80
 81    def _create_keybindings(self):
 82        """Bind the keys to the merged interactive segmentation widget."""
 83        interactive = self._widgets["interactive"]
 84
 85        @self._viewer.bind_key("s", overwrite=True)
 86        def _segment(viewer):
 87            interactive.segment(viewer)
 88
 89        # We also need to over-write the keybindings for the prompt layers.
 90        # See https://github.com/napari/napari/issues/7302 for details.
 91        prompt_layer = self._viewer.layers["prompts"]
 92        point_prompt_layer = self._viewer.layers["point_prompts"]
 93
 94        @prompt_layer.bind_key("s", overwrite=True)
 95        def _segment_prompts(event):
 96            interactive.segment(self._viewer)
 97
 98        @point_prompt_layer.bind_key("s", overwrite=True)
 99        def _segment_point_prompts(event):
100            interactive.segment(self._viewer)
101
102        # The layer the key reached is the active one, so it goes first: only it relabels a selected
103        # scribble. The viewer-level fallback below has no active prompt layer, so it relabels none.
104        @prompt_layer.bind_key("t", overwrite=True)
105        def _toggle_shape_prompt_label(event=None):
106            vutil.toggle_label(self._shape_prompt_layer, self._point_prompt_layer)
107
108        @point_prompt_layer.bind_key("t", overwrite=True)
109        def _toggle_point_prompt_label(event=None):
110            vutil.toggle_label(self._point_prompt_layer, self._shape_prompt_layer)
111
112        @self._viewer.bind_key("c", overwrite=True)
113        def _commit(viewer):
114            self._widgets["commit"](viewer)
115
116        @self._viewer.bind_key("t", overwrite=True)
117        def _toggle_label(event=None):
118            vutil.toggle_label(self._point_prompt_layer, self._shape_prompt_layer)
119
120        @self._viewer.bind_key("Shift-C", overwrite=True)
121        def _clear_annotations(viewer):
122            interactive.clear(viewer)
123
124    def __init__(
125        self,
126        viewer: "napari.viewer.Viewer",
127        ndim: Optional[int] = None,
128        reset_state: bool = True,
129    ) -> None:
130        """Create the annotator GUI.
131
132        Args:
133            viewer: The napari viewer.
134            ndim: The number of spatial dimensions (2 or 3). If None, auto-detected from the image.
135            reset_state: Whether to reset the annotator state.
136
137        Raises:
138            ValueError: If ndim is invalid or doesn't match the image shape.
139        """
140        # Auto-detect ndim when launched as a napari widget without an explicit ndim.
141        # Detect from an already-loaded image layer, defaulting to 2D when none is present
142        # (e.g. when the widget is opened from the napari Plugins menu before loading an image).
143        if ndim is None:
144            ndim = detect_ndim_from_viewer(viewer)
145
146        # Validate ndim
147        if ndim not in (2, 3):
148            raise ValueError(f"Invalid ndim: {ndim}. Expected 2 or 3.")
149
150        super().__init__(viewer=viewer, ndim=ndim)
151
152        # Set the expected annotator class to the state.
153        state = AnnotatorState()
154
155        # Reset the state.
156        if reset_state:
157            state.reset_state()
158
159        state.annotator = self
160
161        # Rebuild the annotator if an image with a different dimensionality is selected as input.
162        # This handles loading e.g. a 3D image after the widget was opened from the Plugins menu.
163        self._embedding_widget.image_selection.changed.connect(self._on_image_selection_changed)
164
165        # Re-normalize when the user changes the 'image dimensions' (ndim) override.
166        if getattr(self._embedding_widget, "ndim_choice", False):
167            self._embedding_widget.image_ndim_dropdown.currentTextChanged.connect(self._on_ndim_mode_changed)
168
169        # Normalize and align to any image that is already selected (e.g. opened from the
170        # Plugins menu after an image was loaded, so no selection-changed event will fire).
171        self._on_image_selection_changed()
172
173    def _on_image_selection_changed(self, *args):
174        """Normalize the selected image and rebuild the annotator if its dimensionality changed."""
175        # Skip while we replace the image layer ourselves during normalization.
176        if self._suppress_selection_rebuild:
177            return
178        image_layer = self._embedding_widget.image_selection.get_value()
179        if image_layer is None:
180            return
181        # Squeeze singletons and map channels to RGB, replacing the image layer if needed,
182        # so the image, segmentation and prompt layers all stay aligned. The 'image dimensions'
183        # override (auto/2d/3d) disambiguates multi-channel inputs. Unsupported inputs (e.g. 3D
184        # volumes with a channel axis) are reported instead of crashing the widget.
185        try:
186            image_layer, ndim = self._maybe_normalize_image_layer(
187                image_layer, ndim=self._embedding_widget._ndim_override()
188            )
189        except ValueError as e:
190            show_info(str(e))
191            return
192
193        # Detect an actual change of the selected image, tracked by layer identity (the state's
194        # 'image_name' is not reliably set on every code path, so we don't depend on it). The first
195        # call (during setup) just records the image and does not reset. A later switch to a
196        # different image layer triggers the reset below.
197        previous_layer = getattr(self, "_last_image_layer", None)
198        image_changed = previous_layer is not None and image_layer is not previous_layer
199        self._last_image_layer = image_layer
200
201        # When the selected image changes, reset everything so the tool behaves as if it was just
202        # opened on the new image: the precomputed embeddings, the model and everything derived from
203        # them belong to the previous image and must not be reused (they can even differ in
204        # dimensionality, e.g. 3D volume -> 2D image). 'reset_state' clears the state. Resetting the
205        # (shared, kept) embedding widget inputs restores the default model, tiling and save path. The
206        # forced rebuild recreates the dimension-specific widgets and napari layers, so all
207        # checkboxes are back to defaults, the autosegment cache is gone and the prompt / segmentation
208        # layers are cleared. The user recomputes embeddings for the new image via 'Compute Embeddings'.
209        if image_changed:
210            AnnotatorState().reset_state()
211            self._embedding_widget._reset_inputs_to_defaults()
212            self._rebuild_for_ndim(ndim, force=True)
213            return
214
215        if ndim != self._ndim:
216            self._rebuild_for_ndim(ndim)
217
218    def _on_ndim_mode_changed(self, *args):
219        """Re-interpret the current image when the 'image dimensions' override changes.
220
221        Unlike selecting a different image, this keeps the embedding-widget inputs (model, tiling and
222        the override itself); it only re-normalizes, clears the now-invalid embeddings / prompts and
223        rebuilds the layers for the resulting dimensionality.
224        """
225        if self._suppress_selection_rebuild:
226            return
227        image_layer = self._embedding_widget.image_selection.get_value()
228        if image_layer is None:
229            return
230        try:
231            image_layer, ndim = self._maybe_normalize_image_layer(
232                image_layer, ndim=self._embedding_widget._ndim_override()
233            )
234        except ValueError as e:
235            # The chosen override (e.g. '3d' on a 2D image) cannot be applied: warn in a modal dialog,
236            # recommend 'auto', and revert the dropdown to 'auto' so the tool is not stuck on the
237            # invalid choice.
238            from qtpy import QtWidgets
239            QtWidgets.QMessageBox.warning(
240                self, "Invalid image dimensions",
241                f"{e}\n\nThis dimensionality cannot be applied to the selected image. "
242                "Switching back to 'auto', which is recommended for automatic dimensionality detection.",
243                QtWidgets.QMessageBox.Ok,
244            )
245            dropdown = self._embedding_widget.image_ndim_dropdown
246            dropdown.blockSignals(True)
247            dropdown.setCurrentText("auto")
248            self._embedding_widget.image_ndim_mode = "auto"
249            dropdown.blockSignals(False)
250            return
251
252        # No effective change (same layer and dimensionality): keep the current work.
253        if image_layer is getattr(self, "_last_image_layer", None) and ndim == self._ndim:
254            return
255
256        self._last_image_layer = image_layer
257        AnnotatorState().reset_state()
258        self._rebuild_for_ndim(ndim, force=True)

Unified annotator for 2D and 3D images.

This class handles both 2D and 3D annotation, with dimensionality controlled by the ndim parameter or auto-detected from the image.

Annotator( viewer: napari.viewer.Viewer, ndim: Optional[int] = None, reset_state: bool = True)
124    def __init__(
125        self,
126        viewer: "napari.viewer.Viewer",
127        ndim: Optional[int] = None,
128        reset_state: bool = True,
129    ) -> None:
130        """Create the annotator GUI.
131
132        Args:
133            viewer: The napari viewer.
134            ndim: The number of spatial dimensions (2 or 3). If None, auto-detected from the image.
135            reset_state: Whether to reset the annotator state.
136
137        Raises:
138            ValueError: If ndim is invalid or doesn't match the image shape.
139        """
140        # Auto-detect ndim when launched as a napari widget without an explicit ndim.
141        # Detect from an already-loaded image layer, defaulting to 2D when none is present
142        # (e.g. when the widget is opened from the napari Plugins menu before loading an image).
143        if ndim is None:
144            ndim = detect_ndim_from_viewer(viewer)
145
146        # Validate ndim
147        if ndim not in (2, 3):
148            raise ValueError(f"Invalid ndim: {ndim}. Expected 2 or 3.")
149
150        super().__init__(viewer=viewer, ndim=ndim)
151
152        # Set the expected annotator class to the state.
153        state = AnnotatorState()
154
155        # Reset the state.
156        if reset_state:
157            state.reset_state()
158
159        state.annotator = self
160
161        # Rebuild the annotator if an image with a different dimensionality is selected as input.
162        # This handles loading e.g. a 3D image after the widget was opened from the Plugins menu.
163        self._embedding_widget.image_selection.changed.connect(self._on_image_selection_changed)
164
165        # Re-normalize when the user changes the 'image dimensions' (ndim) override.
166        if getattr(self._embedding_widget, "ndim_choice", False):
167            self._embedding_widget.image_ndim_dropdown.currentTextChanged.connect(self._on_ndim_mode_changed)
168
169        # Normalize and align to any image that is already selected (e.g. opened from the
170        # Plugins menu after an image was loaded, so no selection-changed event will fire).
171        self._on_image_selection_changed()

Create the annotator GUI.

Arguments:
  • viewer: The napari viewer.
  • ndim: The number of spatial dimensions (2 or 3). If None, auto-detected from the image.
  • reset_state: Whether to reset the annotator state.
Raises:
  • ValueError: If ndim is invalid or doesn't match the image shape.
def annotator( image: numpy.ndarray, *, ndim: Optional[int] = None, embedding_path: Union[str, Dict[str, Any], NoneType] = None, segmentation_result: Optional[numpy.ndarray] = None, model_type: str = 'hvit_t_cells', tile_shape: Optional[Tuple[int, int]] = None, halo: Optional[Tuple[int, int]] = None, return_viewer: bool = False, viewer: Optional[napari.viewer.Viewer] = None, precompute_autoseg_state: bool = False, checkpoint_path: Optional[str] = None, decoder_path: Optional[str] = None, device: Union[str, torch.device, NoneType] = None, prefer_decoder: bool = True) -> Optional[napari.viewer.Viewer]:
261def annotator(
262    image: np.ndarray,
263    *,
264    ndim: Optional[int] = None,
265    embedding_path: Optional[Union[str, util.ImageEmbeddings]] = None,
266    segmentation_result: Optional[np.ndarray] = None,
267    model_type: str = DEFAULT_MODEL,
268    tile_shape: Optional[Tuple[int, int]] = None,
269    halo: Optional[Tuple[int, int]] = None,
270    return_viewer: bool = False,
271    viewer: Optional["napari.viewer.Viewer"] = None,
272    precompute_autoseg_state: bool = False,
273    checkpoint_path: Optional[str] = None,
274    decoder_path: Optional[str] = None,
275    device: Optional[Union[str, torch.device]] = None,
276    prefer_decoder: bool = True,
277) -> Optional["napari.viewer.Viewer"]:
278    """Start the annotation tool for a given image.
279
280    Args:
281        image: The image data (2D or 3D).
282        ndim: The number of spatial dimensions (2 or 3). If None, auto-detected from image shape.
283        embedding_path: Filepath where to save the embeddings
284            or the precompted image embeddings computed by `precompute_image_embeddings`.
285        segmentation_result: An initial segmentation to load.
286            This can be used to correct segmentations with Segment Anything or to save and load progress.
287            The segmentation will be loaded as the 'committed_objects' layer.
288        model_type: The Segment Anything 2 model to use. The name must start with 'hvit_'. For the available
289            models, see https://computational-cell-analytics.github.io/micro-sam/micro_sam.html#finetuned-models.
290        tile_shape: Shape of tiles for tiled embedding prediction. If `None`, reuse the tiling of
291            already cached embeddings, else use the default tiling for images exceeding the in-plane
292            size threshold, and pass smaller images to Segment Anything without tiling.
293        halo: Shape of the overlap between tiles, which is needed to segment objects on tile borders.
294            If `None`, use the default overlap whenever tiling is active.
295        return_viewer: Whether to return the napari viewer to further modify it before starting the tool.
296            By default, does not return the napari viewer.
297        viewer: The viewer to which the Segment Anything functionality should be added.
298            This enables using a pre-initialized viewer.
299        precompute_autoseg_state: Whether to precompute the automatic segmentation state (the decoder
300            predictions). Requires an embedding path and a model with a decoder; it is ignored for a
301            model without one. This will take more time when precomputing embeddings, but will then
302            make automatic segmentation much faster. By default, set to 'False'.
303        checkpoint_path: Path to a custom checkpoint from which to load the SAM model.
304        decoder_path: Path to a custom decoder checkpoint from which to load the `micro-sam` decoder.
305        device: The computational device to use for the SAM model.
306            By default, automatically chooses the best available device.
307        prefer_decoder: Whether to use decoder based instance segmentation if
308            the model used has an additional decoder for instance segmentation.
309            By default, set to 'True'.
310
311    Returns:
312        The napari viewer, only returned if `return_viewer=True`.
313
314    Raises:
315        ValueError: If the model is not a Segment Anything 2 model. Also if ndim is not valid or does not
316            match the image shape.
317    """
318    # Normalize the image: squeeze singletons and map the channel axis to RGB. The optional 'ndim'
319    # override disambiguates multi-channel inputs (e.g. reads a channels-first (C, H, W) array as a
320    # 2d image), consistent with the GUI's 'image dimensions' control. With ndim=None it is
321    # auto-detected. 'prepare_annotation_image' raises if the override cannot be applied to the shape.
322    _validate_sam2_model_type(model_type, "segmentation")
323    image, ndim, rgb = vutil.prepare_annotation_image(image, ndim=ndim)
324
325    # Extract image shape (strip RGB channel if present)
326    state = AnnotatorState()
327    state.image_shape = image.shape[:-1] if rgb else image.shape
328
329    # The API / CLI computes embeddings before creating the widget, so apply the same
330    # size heuristic here. Reuse these resolved settings when syncing the widget below.
331    tile_shape, halo = resolve_default_tiling(state.image_shape, tile_shape, halo, embedding_path)
332
333    # Initialize the predictor state
334    state.initialize_predictor(
335        image,
336        model_type=model_type,
337        save_path=embedding_path,
338        halo=halo,
339        tile_shape=tile_shape,
340        precompute_autoseg_state=precompute_autoseg_state,
341        ndim=ndim,
342        checkpoint_path=checkpoint_path,
343        decoder_path=decoder_path,
344        device=device,
345        prefer_decoder=prefer_decoder,
346        use_cli=True,
347    )
348
349    # Create or get viewer
350    if viewer is None:
351        viewer = napari.Viewer()
352
353    viewer.add_image(image, name="image", rgb=rgb)
354    annotator_instance = Annotator(viewer, ndim=ndim, reset_state=False)
355
356    # Trigger layer update of the annotator so that layers have the correct shape.
357    # And initialize the 'committed_objects' with the segmentation result if it was given.
358    annotator_instance._update_image(segmentation_result=segmentation_result)
359
360    # Add the annotator widget to the viewer and sync widgets.
361    viewer.window.add_dock_widget(annotator_instance, name=get_dock_title("segmentation"))
362    _sync_embedding_widget(
363        widget=state.widgets["embeddings"],
364        model_type=(
365            model_type
366            if checkpoint_path is None
367            else state.predictor.model_type
368        ),
369        save_path=embedding_path,
370        checkpoint_path=checkpoint_path,
371        device=device,
372        tile_shape=tile_shape,
373        halo=halo,
374    )
375
376    if return_viewer:
377        return viewer
378
379    napari.run()

Start the annotation tool for a given image.

Arguments:
  • image: The image data (2D or 3D).
  • ndim: The number of spatial dimensions (2 or 3). If None, auto-detected from image shape.
  • embedding_path: Filepath where to save the embeddings or the precompted image embeddings computed by precompute_image_embeddings.
  • segmentation_result: An initial segmentation to load. This can be used to correct segmentations with Segment Anything or to save and load progress. The segmentation will be loaded as the 'committed_objects' layer.
  • model_type: The Segment Anything 2 model to use. The name must start with 'hvit_'. For the available models, see https://computational-cell-analytics.github.io/micro-sam/micro_sam.html#finetuned-models.
  • tile_shape: Shape of tiles for tiled embedding prediction. If None, reuse the tiling of already cached embeddings, else use the default tiling for images exceeding the in-plane size threshold, and pass smaller images to Segment Anything without tiling.
  • halo: Shape of the overlap between tiles, which is needed to segment objects on tile borders. If None, use the default overlap whenever tiling is active.
  • return_viewer: Whether to return the napari viewer to further modify it before starting the tool. By default, does not return the napari viewer.
  • viewer: The viewer to which the Segment Anything functionality should be added. This enables using a pre-initialized viewer.
  • precompute_autoseg_state: Whether to precompute the automatic segmentation state (the decoder predictions). Requires an embedding path and a model with a decoder; it is ignored for a model without one. This will take more time when precomputing embeddings, but will then make automatic segmentation much faster. By default, set to 'False'.
  • checkpoint_path: Path to a custom checkpoint from which to load the SAM model.
  • decoder_path: Path to a custom decoder checkpoint from which to load the micro-sam decoder.
  • device: The computational device to use for the SAM model. By default, automatically chooses the best available device.
  • prefer_decoder: Whether to use decoder based instance segmentation if the model used has an additional decoder for instance segmentation. By default, set to 'True'.
Returns:

The napari viewer, only returned if return_viewer=True.

Raises:
  • ValueError: If the model is not a Segment Anything 2 model. Also if ndim is not valid or does not match the image shape.