micro_sam.sam_annotator.annotator_tracking

  1import os
  2from typing import List, Optional, Tuple, Union
  3
  4import numpy as np
  5import imageio.v3 as imageio
  6
  7import torch
  8
  9import napari
 10from magicgui.widgets import ComboBox, Container
 11
 12from . import util as vutil
 13from . import _widgets as widgets
 14from ._state import AnnotatorState
 15from ._tooltips import get_tooltip
 16from ._titles import get_dock_title
 17from ._annotator import _AnnotatorBase
 18from ..util import prepare_annotation_image
 19from ._batch import BatchAnnotatorTask, run_batch
 20from ..v2.util import DEFAULT_MODEL, resolve_default_tiling
 21
 22# Cyan (track) and Magenta (division)
 23STATE_COLOR_CYCLE = [
 24    "#00FFFF",
 25    "#FF00FF",
 26]
 27"""@private"""
 28
 29
 30# This solution is a bit hacky, so I won't move it to _widgets.py yet.
 31def create_tracking_menu(
 32    points_layer, box_layer, states, track_ids, point_labels=None, tracking_widget=None, viewer=None
 33):
 34    """@private"""
 35    state = AnnotatorState()
 36
 37    def _get_widget_menu(container, label):
 38        for w in container:
 39            if isinstance(w, ComboBox) and w.label == label:
 40                return w
 41        raise ValueError(f"ComboBox with label '{label}' not found.")
 42
 43    if tracking_widget is None:
 44        # The prompt label menu (positive / negative point prompts) shares this container with the
 45        # track id / track state menus so that all three dropdowns align in a single label column.
 46        label_menu = ComboBox(
 47            label="prompt",
 48            choices=point_labels,
 49            tooltip=get_tooltip("prompt_menu", "labels"),
 50        )
 51        state_menu = ComboBox(
 52            label="track_state",
 53            choices=states,
 54            tooltip=get_tooltip("annotator_tracking", "track_state"),
 55        )
 56        track_id_menu = ComboBox(
 57            label="track_id",
 58            choices=list(map(str, track_ids)),
 59            tooltip=get_tooltip("annotator_tracking", "track_id"),
 60        )
 61        tracking_widget = Container(widgets=[label_menu, state_menu, track_id_menu])
 62    else:
 63        label_menu = _get_widget_menu(tracking_widget, "prompt")
 64        state_menu = _get_widget_menu(tracking_widget, "track_state")
 65        track_id_menu = _get_widget_menu(tracking_widget, "track_id")
 66
 67    # Keep the prompt label menu in sync with the point layer's current label.
 68    def update_label_menu(event):
 69        new_label = str(points_layer.current_properties["label"][0])
 70        if new_label != label_menu.value:
 71            label_menu.value = new_label
 72
 73    def label_changed(new_label):
 74        # Keep both prompt layers on the selected label so the next scribble also uses it. Only the
 75        # layer in use relabels its selected scribbles, see 'relabels_selection'.
 76        for layer in (points_layer, box_layer):
 77            vutil.set_prompt_label(
 78                layer, new_label, relabel_selected=vutil.relabels_selection(layer, viewer)
 79            )
 80
 81    points_layer.events.current_properties.connect(update_label_menu)
 82    label_menu.changed.connect(label_changed)
 83
 84    def update_state(event):
 85        if "state" in points_layer.current_properties:
 86            new_state = str(points_layer.current_properties["state"][0])
 87            if new_state != state_menu.value:
 88                state_menu.value = new_state
 89
 90    def update_track_id(event):
 91        if "track_id" in points_layer.current_properties:
 92            new_id = str(points_layer.current_properties["track_id"][0])
 93            if new_id != track_id_menu.value:
 94                track_id_menu.value = new_id
 95                state.current_track_id = int(new_id)
 96
 97    # def update_state_boxes(event):
 98    #     new_state = str(box_layer.current_properties["state"][0])
 99    #     if new_state != state_menu.value:
100    #         state_menu.value = new_state
101
102    # napari 0.9 no longer syncs 'current_properties' with the selection on shape layers (napari/napari#9221).
103    def update_track_id_boxes(*args):
104        if "track_id" not in box_layer.properties:
105            return
106        selected = list(box_layer.selected_data)
107        track_ids = set(box_layer.properties["track_id"][selected])
108        if len(track_ids) != 1:  # A mixed selection would relabel every selected box.
109            return
110        new_id = str(track_ids.pop())
111        if new_id != track_id_menu.value:
112            track_id_menu.value = new_id
113            state.current_track_id = int(new_id)
114
115    points_layer.events.current_properties.connect(update_state)
116    points_layer.events.current_properties.connect(update_track_id)
117    # box_layer.events.current_properties.connect(update_state_boxes)
118    box_layer.selected_data.events.items_changed.connect(update_track_id_boxes)
119
120    def state_changed(new_state):
121        current_properties = points_layer.current_properties
122        current_properties["state"] = np.array([new_state])
123        points_layer.current_properties = current_properties
124        points_layer.refresh_colors()
125
126    def track_id_changed(new_track_id):
127        current_properties = points_layer.current_properties
128        current_properties["track_id"] = np.array([new_track_id])
129        # Note: this fails with a key error after committing a lineage with multiple tracks.
130        # I think this does not cause any further errors, so we just skip this.
131        try:
132            points_layer.current_properties = current_properties
133        except KeyError:
134            pass
135        state.current_track_id = int(new_track_id)
136
137    # def state_changed_boxes(new_state):
138    #     current_properties = box_layer.current_properties
139    #     current_properties["state"] = np.array([new_state])
140    #     box_layer.current_properties = current_properties
141    #     box_layer.refresh_colors()
142
143    def track_id_changed_boxes(new_track_id):
144        current_properties = box_layer.current_properties
145        current_properties["track_id"] = np.array([new_track_id])
146        box_layer.current_properties = current_properties
147        state.current_track_id = int(new_track_id)
148
149    state_menu.changed.connect(state_changed)
150    track_id_menu.changed.connect(track_id_changed)
151    # state_menu.changed.connect(state_changed_boxes)
152    track_id_menu.changed.connect(track_id_changed_boxes)
153
154    state_menu.set_choice("track")
155    return tracking_widget
156
157
158class AnnotatorTracking(_AnnotatorBase):
159
160    def _create_embedding_widget(self):
161        return widgets.EmbeddingWidget(is_timeseries=True)
162
163    # The tracking annotator needs different settings for the prompt layers
164    # to support the additional tracking state.
165    # That's why we over-ride this function.
166    def _require_layers(self, layer_choices: Optional[List[str]] = None):
167
168        # Check whether the image is initialized already. And use the image shape and scale for the layers.
169        state = AnnotatorState()
170        shape = self._shape if state.image_shape is None else state.image_shape
171
172        # Add the label layers for the current object, the automatic segmentation and the committed segmentation.
173        dummy_data = np.zeros(shape, dtype="uint32")
174        image_scale = state.image_scale
175
176        # Before adding new layers, we always check whether a layer with this name already exists or not.
177        if "current_object" not in self._viewer.layers:
178            if (
179                layer_choices and "current_object" in layer_choices
180            ):  # Check at 'commit' call button.
181                widgets._validation_window_for_missing_layer("current_object")
182            self._viewer.add_labels(data=dummy_data, name="current_object")
183            if image_scale is not None:
184                self._viewer.layers["current_object"].scale = image_scale
185
186        if "auto_segmentation" not in self._viewer.layers:
187            if (
188                layer_choices and "auto_segmentation" in layer_choices
189            ):  # Check at 'commit' call button.
190                widgets._validation_window_for_missing_layer(
191                    "auto_segmentation"
192                )
193            self._viewer.add_labels(data=dummy_data, name="auto_segmentation")
194            if image_scale is not None:
195                self._viewer.layers["auto_segmentation"].scale = image_scale
196
197        if "committed_objects" not in self._viewer.layers:
198            if (
199                layer_choices and "committed_objects" in layer_choices
200            ):  # Check at 'commit' call button.
201                widgets._validation_window_for_missing_layer(
202                    "committed_objects"
203                )
204            self._viewer.add_labels(data=dummy_data, name="committed_objects")
205            # Randomize colors so it is easy to see when object committed.
206            self._viewer.layers["committed_objects"].new_colormap()
207            if image_scale is not None:
208                self._viewer.layers["committed_objects"].scale = image_scale
209
210        # Add the point prompts layer.
211        self._point_labels = ["positive", "negative"]
212        self._track_state_labels = ["track", "division"]
213        _point_prompt_property_choices = {
214            "label": self._point_labels,
215            "state": self._track_state_labels,
216            "track_id": ["1"],  # we use string to avoid pandas warning
217        }
218
219        point_layer_mismatch = True
220        if "point_prompts" in self._viewer.layers:
221            # Check whether the 'property_choices' match or not.
222            curr_property_choices = self._viewer.layers[
223                "point_prompts"
224            ].property_choices
225            point_layer_mismatch = set(curr_property_choices.keys()) != set(
226                _point_prompt_property_choices.keys()
227            )
228
229        if point_layer_mismatch and "point_prompts" not in self._viewer.layers:
230            self._point_prompt_layer = self._viewer.add_points(
231                name="point_prompts",
232                property_choices=_point_prompt_property_choices,
233                border_color="label",
234                border_color_cycle=vutil.LABEL_COLOR_CYCLE,
235                symbol="o",
236                face_color="state",
237                face_color_cycle=STATE_COLOR_CYCLE,
238                border_width=0.4,
239                size=12,
240                ndim=self._ndim,
241            )
242            self._point_prompt_layer.border_color_mode = "cycle"
243            self._point_prompt_layer.face_color_mode = "cycle"
244            _new_point_layer = True
245        else:
246            self._point_prompt_layer = self._viewer.layers["point_prompts"]
247            _new_point_layer = False
248
249        # Add the layer for the box and scribble prompts. It carries a positive or negative 'label'
250        # (for open scribbles) next to the 'track_id', so one layer supports boxes and scribbles.
251        _box_prompt_property_choices = {"track_id": ["1"], "label": self._point_labels}
252
253        box_layer_mismatch = True
254        if "prompts" in self._viewer.layers:
255            # Check whether the 'property_choices' match or not.
256            curr_property_choices = self._viewer.layers[
257                "prompts"
258            ].property_choices
259            box_layer_mismatch = set(curr_property_choices.keys()) != set(
260                _box_prompt_property_choices.keys()
261            )
262
263        if box_layer_mismatch and "prompts" not in self._viewer.layers:
264            # Using the box layer to set divisions currently doesn't work.
265            # That's why some of the code below is commented out.
266            # Boxes stay green (positive). The 'label' color cycle shows open scribbles as green or red.
267            self._box_prompt_layer = self._viewer.add_shapes(
268                shape_type="rectangle",
269                edge_width=4,
270                ndim=self._ndim,
271                face_color="transparent",
272                name="prompts",
273                edge_color="label",
274                edge_color_cycle=vutil.LABEL_COLOR_CYCLE,
275                property_choices=_box_prompt_property_choices,
276                # property_choices={"track_id": ["1"], "state": self._track_state_labels},
277                # edge_color_cycle=STATE_COLOR_CYCLE,
278            )
279            self._box_prompt_layer.edge_color_mode = "cycle"
280            _new_box_layer = True
281        else:
282            self._box_prompt_layer = self._viewer.layers["prompts"]
283            _new_box_layer = False
284
285        # A box layer that already exists has no 'label' property, so fill it in. Then connect the
286        # scribble label helpers (green and red coloring, non-scribble normalization), like the
287        # base annotator does.
288        if "label" not in self._box_prompt_layer.properties:
289            properties = dict(self._box_prompt_layer.properties)
290            properties["label"] = np.full(len(self._box_prompt_layer.data), "positive", dtype=object)
291            self._box_prompt_layer.properties = properties
292            current_properties = self._box_prompt_layer.current_properties
293            current_properties["label"] = np.array(["positive"])
294            self._box_prompt_layer.current_properties = current_properties
295            self._box_prompt_layer.edge_color_cycle = vutil.LABEL_COLOR_CYCLE
296            self._box_prompt_layer.edge_color = "label"
297            self._box_prompt_layer.edge_color_mode = "cycle"
298        if not self._box_prompt_layer.metadata.get("micro_sam_prompt_labels_configured", False):
299            self._box_prompt_layer.events.data.connect(vutil.normalize_prompt_shape_labels)
300            self._box_prompt_layer.events.mode.connect(vutil.sync_prompt_shape_current_color)
301            self._box_prompt_layer.events.current_properties.connect(vutil.sync_prompt_shape_current_color)
302            self._box_prompt_layer.metadata["micro_sam_prompt_labels_configured"] = True
303        vutil.normalize_prompt_shape_labels(self._box_prompt_layer)
304        vutil.sync_prompt_shape_current_color(self._box_prompt_layer)
305
306        # Trigger a new connection for the tracking state menu only when a new layer is (re)created.
307        if _new_point_layer or _new_box_layer:
308            self._tracking_widget = create_tracking_menu(
309                points_layer=self._point_prompt_layer,
310                box_layer=self._box_prompt_layer,
311                states=self._track_state_labels,
312                track_ids=list(state.lineage.keys()),
313                point_labels=self._point_labels,
314                tracking_widget=getattr(self, "_tracking_widget", None),
315                viewer=self._viewer,
316            )
317
318    def _get_widgets(self):
319        self._require_layers()
320
321        # Ensure the tracking state menu exists. '_require_layers' creates it when it recreates the
322        # layers. Create it here as a fallback otherwise.
323        if getattr(self, "_tracking_widget", None) is None:
324            self._tracking_widget = create_tracking_menu(
325                points_layer=self._point_prompt_layer,
326                box_layer=self._box_prompt_layer,
327                states=self._track_state_labels,
328                track_ids=list(AnnotatorState().lineage.keys()),
329                point_labels=self._point_labels,
330                viewer=self._viewer,
331            )
332
333        # The prompt menu, the track id / track state menus and the segment / clear controls all
334        # live in a single merged container, mirroring the segmentation annotator.
335        interactive = widgets.InteractiveTrackingWidget(
336            self._viewer, tracking_widget=self._tracking_widget,
337        )
338        autotrack = widgets.AutoTrackWidget(
339            self._viewer, with_decoder=self._with_decoder, volumetric=True
340        )
341        return {
342            "interactive": interactive,
343            "autosegment": autotrack,
344            "commit": widgets.commit_track(),
345            "export": widgets.export_track(),
346        }
347
348    def _create_keybindings(self):
349        interactive = self._widgets["interactive"]
350
351        @self._viewer.bind_key("s", overwrite=True)
352        def _segment(viewer):
353            interactive.segment(viewer)
354
355        # We also need to over-write the keybindings for the prompt layers.
356        # See https://github.com/napari/napari/issues/7302 for details.
357        prompt_layer = self._viewer.layers["prompts"]
358        point_prompt_layer = self._viewer.layers["point_prompts"]
359
360        @prompt_layer.bind_key("s", overwrite=True)
361        def _segment_prompts(event):
362            interactive.segment(self._viewer)
363
364        @point_prompt_layer.bind_key("s", overwrite=True)
365        def _segment_point_prompts(event):
366            interactive.segment(self._viewer)
367
368        # The layer the key reached is the active one, so it goes first: only it relabels a selected
369        # scribble. The viewer-level fallback below has no active prompt layer, so it relabels none.
370        @prompt_layer.bind_key("t", overwrite=True)
371        def _toggle_shape_prompt_label(event=None):
372            vutil.toggle_label(self._box_prompt_layer, self._point_prompt_layer)
373
374        @point_prompt_layer.bind_key("t", overwrite=True)
375        def _toggle_point_prompt_label(event=None):
376            vutil.toggle_label(self._point_prompt_layer, self._box_prompt_layer)
377
378        @self._viewer.bind_key("c", overwrite=True)
379        def _commit(viewer):
380            self._widgets["commit"](viewer)
381
382        @self._viewer.bind_key("t", overwrite=True)
383        def _toggle_label(event=None):
384            vutil.toggle_label(self._point_prompt_layer, self._box_prompt_layer)
385
386        @self._viewer.bind_key("Shift-C", overwrite=True)
387        def _clear_annotations(viewer):
388            interactive.clear(viewer)
389
390    def __init__(
391        self, viewer: "napari.viewer.Viewer", reset_state: bool = True
392    ) -> None:
393        # Initialize the state for tracking.
394        self._init_track_state()
395        # At startup the decoder is not loaded yet. Also treat the default model as decoder-capable
396        # when it has a registered decoder, so the default mode is correct before 'Compute Embeddings'.
397        from ..v2.util import has_registered_decoder
398        self._with_decoder = AnnotatorState().decoder is not None or has_registered_decoder(DEFAULT_MODEL)
399        super().__init__(viewer=viewer, ndim=3)
400        # Go to t=0.
401        self._viewer.dims.current_step = (0, 0, 0) + tuple(
402            sh // 2 for sh in self._shape[1:]
403        )
404
405        # Set the expected annotator class to the state.
406        state = AnnotatorState()
407
408        # Reset the state.
409        if reset_state:
410            state.reset_state()
411
412        state.annotator = self
413
414    def _init_track_state(self):
415        state = AnnotatorState()
416        state.current_track_id = 1
417        state.lineage = {1: []}
418        state.committed_lineages = []
419
420    def _update_image(self):
421        super()._update_image()
422        self._init_track_state()
423
424
425def annotator_tracking(
426    image: np.ndarray,
427    embedding_path: Optional[str] = None,
428    # tracking_result: Optional[str] = None,
429    model_type: str = DEFAULT_MODEL,
430    tile_shape: Optional[Tuple[int, int]] = None,
431    halo: Optional[Tuple[int, int]] = None,
432    return_viewer: bool = False,
433    viewer: Optional["napari.viewer.Viewer"] = None,
434    precompute_autoseg_state: bool = False,
435    checkpoint_path: Optional[str] = None,
436    decoder_path: Optional[str] = None,
437    device: Optional[Union[str, torch.device]] = None,
438) -> Optional["napari.viewer.Viewer"]:
439    """Start the tracking annotation tool fora given timeseries.
440
441    Args:
442        image: The image data.
443        embedding_path: Filepath for saving the precomputed embeddings.
444        model_type: The Segment Anything model to use. For details on the available models check out
445            https://computational-cell-analytics.github.io/micro-sam/micro_sam.html#finetuned-models.
446        tile_shape: Shape of tiles for tiled embedding prediction. If `None`, reuse the tiling of
447            already cached embeddings, else use the default tiling for images exceeding the in-plane
448            size threshold, and pass smaller images to Segment Anything without tiling.
449        halo: Shape of the overlap between tiles, which is needed to segment objects on tile borders.
450            If `None`, use the default overlap whenever tiling is active.
451        return_viewer: Whether to return the napari viewer to further modify it before starting the tool.
452            By default, does not return the napari viewer.
453        viewer: The viewer to which the Segment Anything functionality should be added.
454            This enables using a pre-initialized viewer.
455        precompute_autoseg_state: Whether to precompute the automatic segmentation state (the decoder
456            predictions). Requires an embedding path and a model with a decoder; it is ignored for a
457            model without one. This will take more time when precomputing embeddings, but will then
458            make automatic segmentation much faster. By default, set to 'False'.
459        checkpoint_path: Path to a custom checkpoint from which to load the SAM model.
460        decoder_path: Path to a custom decoder checkpoint from which to load the 'micro-sam` decoder.
461        device: The computational device to use for the SAM model.
462            By default, automatically chooses the best available device.
463
464    Returns:
465        The napari viewer, only returned if `return_viewer=True`.
466    """
467    vutil._validate_sam2_model_type(model_type, "tracking")
468
469    # Prepare the image in the same way as the annotator. A timeseries is read as a volume (T, H, W).
470    image, _, rgb = prepare_annotation_image(image, ndim=3)
471
472    # Initialize the predictor state.
473    state = AnnotatorState()
474    state.image_shape = image.shape[:3]
475
476    # The API / CLI computes embeddings before creating the widget, so apply the same size
477    # heuristic here. Reuse these resolved settings when syncing the widget below.
478    tile_shape, halo = resolve_default_tiling(state.image_shape, tile_shape, halo, embedding_path)
479
480    state.initialize_predictor(
481        image,
482        model_type=model_type,
483        save_path=embedding_path,
484        halo=halo,
485        tile_shape=tile_shape,
486        prefer_decoder=True,
487        ndim=3,
488        checkpoint_path=checkpoint_path,
489        decoder_path=decoder_path,
490        device=device,
491        precompute_autoseg_state=precompute_autoseg_state,
492        use_cli=True,
493    )
494
495    if viewer is None:
496        viewer = napari.Viewer()
497
498    viewer.add_image(image, name="image", rgb=rgb)
499    annotator = AnnotatorTracking(viewer, reset_state=False)
500
501    # Trigger layer update of the annotator so that layers have the correct shape.
502    annotator._update_image()
503
504    # Add the annotator widget to the viewer and sync widgets.
505    viewer.window.add_dock_widget(annotator, name=get_dock_title("tracking"))
506    vutil._sync_embedding_widget(
507        widget=state.widgets["embeddings"],
508        model_type=(
509            model_type
510            if checkpoint_path is None
511            else state.predictor.model_type
512        ),
513        save_path=embedding_path,
514        checkpoint_path=checkpoint_path,
515        device=device,
516        tile_shape=tile_shape,
517        halo=halo,
518    )
519
520    if return_viewer:
521        return viewer
522
523    napari.run()
524
525
526class TrackingBatchTask(BatchAnnotatorTask):
527    """Batch task for tracking: each item is a TYX timeseries tracked independently."""
528
529    empty_item_message = "Nothing is tracked yet. Do you wish to continue to the next timeseries?"
530
531    # A timeseries is loaded as a volume (T, H, W).
532    ndim = 3
533
534    def __init__(
535        self, *, model_type, embedding_path=None, tile_shape=None, halo=None,
536        checkpoint_path=None, decoder_path=None, device=None,
537        precompute_autoseg_state=False, batch_size=1,
538    ):
539        vutil._validate_sam2_model_type(model_type, "tracking")
540        self.model_type = model_type
541        self.embedding_path = embedding_path
542        self.tile_shape = tile_shape
543        self.halo = halo
544        self.checkpoint_path = checkpoint_path
545        self.decoder_path = decoder_path
546        self.device = device
547        self.precompute_autoseg_state = precompute_autoseg_state
548        self.batch_size = batch_size
549
550    def result_filename(self, entry, index):
551        if self.have_inputs_as_arrays:
552            return f"tracks_{index:05}.tif"
553        return os.path.splitext(os.path.basename(entry))[0] + "_tracks.tif"
554
555    def precompute(self, images):
556        # The SAM2 video embeddings are computed lazily per video in start/advance. When an embedding
557        # folder is given, derive one per-video zarr path inside it. Otherwise keep them in memory.
558        if self.embedding_path is None:
559            return [None] * len(images)
560        os.makedirs(self.embedding_path, exist_ok=True)
561        if self.have_inputs_as_arrays:
562            return [os.path.join(self.embedding_path, f"tracking_{i:05}.zarr") for i in range(len(images))]
563        return [
564            os.path.join(self.embedding_path, os.path.splitext(os.path.basename(p))[0] + ".zarr") for p in images
565        ]
566
567    def _init_predictor(self, image, embedding_path, reuse):
568        state = AnnotatorState()
569        # Reuse the loaded model and decoder on subsequent videos (only the embeddings and the
570        # interactive segmenter are rebuilt per video).
571        if reuse and state.predictor is not None:
572            kwargs = dict(predictor=state.predictor, decoder=state.decoder, prefer_decoder=False)
573        else:
574            kwargs = dict(prefer_decoder=True)
575        # The image is prepared by 'load_batch_image', so a channel axis is always the last one.
576        state.image_shape = image.shape[:3]
577        # Resolve the tiling per timeseries, since the shapes can differ across the batch.
578        tile_shape, halo = resolve_default_tiling(state.image_shape, self.tile_shape, self.halo, embedding_path)
579        state.initialize_predictor(
580            image, model_type=self.model_type, save_path=embedding_path, halo=halo,
581            tile_shape=tile_shape, ndim=3, checkpoint_path=self.checkpoint_path,
582            decoder_path=self.decoder_path, device=self.device, batch_size=self.batch_size,
583            precompute_autoseg_state=self.precompute_autoseg_state,
584            use_cli=True, **kwargs,
585        )
586        return tile_shape, halo
587
588    def start(self, viewer, entry, image, embedding_path, index):
589        tile_shape, halo = self._init_predictor(image, embedding_path, reuse=False)
590        viewer.add_image(image, name="image", rgb=image.ndim > 3)
591        AnnotatorState().image_scale = tuple(viewer.layers["image"].scale)
592
593        annotator = AnnotatorTracking(viewer, reset_state=False)
594        annotator._update_image()
595
596        state = AnnotatorState()
597        viewer.window.add_dock_widget(annotator, name=get_dock_title("batch_tracking"))
598        vutil._sync_embedding_widget(
599            widget=state.widgets["embeddings"],
600            model_type=self.model_type if self.checkpoint_path is None else state.predictor.model_type,
601            save_path=embedding_path, checkpoint_path=self.checkpoint_path,
602            device=self.device, tile_shape=tile_shape, halo=halo,
603        )
604        return annotator
605
606    def advance(self, viewer, annotator, entry, image, embedding_path, index):
607        viewer.layers["image"].data = image
608        tile_shape, halo = self._init_predictor(image, embedding_path, reuse=True)
609        vutil._sync_tiling_widget(AnnotatorState().widgets["embeddings"], tile_shape, halo)
610        AnnotatorState().image_scale = tuple(viewer.layers["image"].scale)
611        annotator._update_image()
612
613    def has_unsaved_content(self, viewer):
614        return viewer.layers["committed_objects"].data.sum() != 0
615
616    def save_item(self, viewer, entry, index):
617        save_path = os.path.join(self.output_folder, self.result_filename(entry, index))
618        imageio.imwrite(save_path, viewer.layers["committed_objects"].data, compression="zlib")
619
620
621def batch_tracking_annotator(
622    images: Union[List[Union[os.PathLike, str]], List[np.ndarray]],
623    output_folder: str,
624    *,
625    model_type: str = DEFAULT_MODEL,
626    embedding_path: Optional[str] = None,
627    tile_shape: Optional[Tuple[int, int]] = None,
628    halo: Optional[Tuple[int, int]] = None,
629    checkpoint_path: Optional[str] = None,
630    decoder_path: Optional[str] = None,
631    device: Optional[Union[str, torch.device]] = None,
632    precompute_autoseg_state: bool = False,
633    viewer: Optional["napari.viewer.Viewer"] = None,
634    return_viewer: bool = False,
635    skip_done: bool = True,
636    batch_size: Optional[int] = 1,
637) -> Optional["napari.viewer.Viewer"]:
638    """Run the tracking annotation tool for a batch of timeseries (each item is one TYX video).
639
640    Args:
641        images: List of timeseries (TYX arrays) or file paths, each tracked independently.
642        output_folder: The folder where the per-video tracking results are saved.
643        model_type: The Segment Anything 2 model to use. The name must start with 'hvit_'.
644        embedding_path: Folder where to save/load the per-video embeddings.
645        tile_shape: Shape of tiles for tiled embedding prediction. If `None`, reuse the tiling of
646            already cached embeddings, else use the default tiling for images exceeding the in-plane
647            size threshold, and pass smaller images to Segment Anything without tiling.
648        halo: Shape of the overlap between tiles, which is needed to segment objects on tile borders.
649            If `None`, use the default overlap whenever tiling is active.
650        checkpoint_path: Path to a custom checkpoint from which to load the SAM model.
651        decoder_path: Path to a custom decoder checkpoint from which to load the `micro-sam` decoder.
652        device: The computational device to use for the SAM model.
653            By default, automatically chooses the best available device.
654        precompute_autoseg_state: Whether to precompute the automatic segmentation state (the decoder
655            predictions). Requires an embedding path and a model with a decoder.
656        viewer: The viewer to which the functionality should be added.
657        return_viewer: Whether to return the napari viewer instead of starting the event loop.
658        skip_done: Whether to skip videos whose tracking result already exists in `output_folder`.
659        batch_size: The number of tiles / slices per model call when computing the embeddings.
660            Only has an effect on a GPU. Pass None to select it per device from the free VRAM
661            (SAM2 only). By default a single tile / slice is used.
662
663    Returns:
664        The napari viewer, only returned if `return_viewer=True`.
665    """
666    have_inputs_as_arrays = isinstance(images[0], np.ndarray)
667    task = TrackingBatchTask(
668        model_type=model_type, embedding_path=embedding_path, tile_shape=tile_shape, halo=halo,
669        checkpoint_path=checkpoint_path, decoder_path=decoder_path, device=device,
670        precompute_autoseg_state=precompute_autoseg_state, batch_size=batch_size,
671    )
672    return run_batch(
673        images, output_folder, task, have_inputs_as_arrays=have_inputs_as_arrays,
674        viewer=viewer, return_viewer=return_viewer, skip_done=skip_done,
675    )
class AnnotatorTracking(micro_sam.sam_annotator._annotator._AnnotatorBase):
159class AnnotatorTracking(_AnnotatorBase):
160
161    def _create_embedding_widget(self):
162        return widgets.EmbeddingWidget(is_timeseries=True)
163
164    # The tracking annotator needs different settings for the prompt layers
165    # to support the additional tracking state.
166    # That's why we over-ride this function.
167    def _require_layers(self, layer_choices: Optional[List[str]] = None):
168
169        # Check whether the image is initialized already. And use the image shape and scale for the layers.
170        state = AnnotatorState()
171        shape = self._shape if state.image_shape is None else state.image_shape
172
173        # Add the label layers for the current object, the automatic segmentation and the committed segmentation.
174        dummy_data = np.zeros(shape, dtype="uint32")
175        image_scale = state.image_scale
176
177        # Before adding new layers, we always check whether a layer with this name already exists or not.
178        if "current_object" not in self._viewer.layers:
179            if (
180                layer_choices and "current_object" in layer_choices
181            ):  # Check at 'commit' call button.
182                widgets._validation_window_for_missing_layer("current_object")
183            self._viewer.add_labels(data=dummy_data, name="current_object")
184            if image_scale is not None:
185                self._viewer.layers["current_object"].scale = image_scale
186
187        if "auto_segmentation" not in self._viewer.layers:
188            if (
189                layer_choices and "auto_segmentation" in layer_choices
190            ):  # Check at 'commit' call button.
191                widgets._validation_window_for_missing_layer(
192                    "auto_segmentation"
193                )
194            self._viewer.add_labels(data=dummy_data, name="auto_segmentation")
195            if image_scale is not None:
196                self._viewer.layers["auto_segmentation"].scale = image_scale
197
198        if "committed_objects" not in self._viewer.layers:
199            if (
200                layer_choices and "committed_objects" in layer_choices
201            ):  # Check at 'commit' call button.
202                widgets._validation_window_for_missing_layer(
203                    "committed_objects"
204                )
205            self._viewer.add_labels(data=dummy_data, name="committed_objects")
206            # Randomize colors so it is easy to see when object committed.
207            self._viewer.layers["committed_objects"].new_colormap()
208            if image_scale is not None:
209                self._viewer.layers["committed_objects"].scale = image_scale
210
211        # Add the point prompts layer.
212        self._point_labels = ["positive", "negative"]
213        self._track_state_labels = ["track", "division"]
214        _point_prompt_property_choices = {
215            "label": self._point_labels,
216            "state": self._track_state_labels,
217            "track_id": ["1"],  # we use string to avoid pandas warning
218        }
219
220        point_layer_mismatch = True
221        if "point_prompts" in self._viewer.layers:
222            # Check whether the 'property_choices' match or not.
223            curr_property_choices = self._viewer.layers[
224                "point_prompts"
225            ].property_choices
226            point_layer_mismatch = set(curr_property_choices.keys()) != set(
227                _point_prompt_property_choices.keys()
228            )
229
230        if point_layer_mismatch and "point_prompts" not in self._viewer.layers:
231            self._point_prompt_layer = self._viewer.add_points(
232                name="point_prompts",
233                property_choices=_point_prompt_property_choices,
234                border_color="label",
235                border_color_cycle=vutil.LABEL_COLOR_CYCLE,
236                symbol="o",
237                face_color="state",
238                face_color_cycle=STATE_COLOR_CYCLE,
239                border_width=0.4,
240                size=12,
241                ndim=self._ndim,
242            )
243            self._point_prompt_layer.border_color_mode = "cycle"
244            self._point_prompt_layer.face_color_mode = "cycle"
245            _new_point_layer = True
246        else:
247            self._point_prompt_layer = self._viewer.layers["point_prompts"]
248            _new_point_layer = False
249
250        # Add the layer for the box and scribble prompts. It carries a positive or negative 'label'
251        # (for open scribbles) next to the 'track_id', so one layer supports boxes and scribbles.
252        _box_prompt_property_choices = {"track_id": ["1"], "label": self._point_labels}
253
254        box_layer_mismatch = True
255        if "prompts" in self._viewer.layers:
256            # Check whether the 'property_choices' match or not.
257            curr_property_choices = self._viewer.layers[
258                "prompts"
259            ].property_choices
260            box_layer_mismatch = set(curr_property_choices.keys()) != set(
261                _box_prompt_property_choices.keys()
262            )
263
264        if box_layer_mismatch and "prompts" not in self._viewer.layers:
265            # Using the box layer to set divisions currently doesn't work.
266            # That's why some of the code below is commented out.
267            # Boxes stay green (positive). The 'label' color cycle shows open scribbles as green or red.
268            self._box_prompt_layer = self._viewer.add_shapes(
269                shape_type="rectangle",
270                edge_width=4,
271                ndim=self._ndim,
272                face_color="transparent",
273                name="prompts",
274                edge_color="label",
275                edge_color_cycle=vutil.LABEL_COLOR_CYCLE,
276                property_choices=_box_prompt_property_choices,
277                # property_choices={"track_id": ["1"], "state": self._track_state_labels},
278                # edge_color_cycle=STATE_COLOR_CYCLE,
279            )
280            self._box_prompt_layer.edge_color_mode = "cycle"
281            _new_box_layer = True
282        else:
283            self._box_prompt_layer = self._viewer.layers["prompts"]
284            _new_box_layer = False
285
286        # A box layer that already exists has no 'label' property, so fill it in. Then connect the
287        # scribble label helpers (green and red coloring, non-scribble normalization), like the
288        # base annotator does.
289        if "label" not in self._box_prompt_layer.properties:
290            properties = dict(self._box_prompt_layer.properties)
291            properties["label"] = np.full(len(self._box_prompt_layer.data), "positive", dtype=object)
292            self._box_prompt_layer.properties = properties
293            current_properties = self._box_prompt_layer.current_properties
294            current_properties["label"] = np.array(["positive"])
295            self._box_prompt_layer.current_properties = current_properties
296            self._box_prompt_layer.edge_color_cycle = vutil.LABEL_COLOR_CYCLE
297            self._box_prompt_layer.edge_color = "label"
298            self._box_prompt_layer.edge_color_mode = "cycle"
299        if not self._box_prompt_layer.metadata.get("micro_sam_prompt_labels_configured", False):
300            self._box_prompt_layer.events.data.connect(vutil.normalize_prompt_shape_labels)
301            self._box_prompt_layer.events.mode.connect(vutil.sync_prompt_shape_current_color)
302            self._box_prompt_layer.events.current_properties.connect(vutil.sync_prompt_shape_current_color)
303            self._box_prompt_layer.metadata["micro_sam_prompt_labels_configured"] = True
304        vutil.normalize_prompt_shape_labels(self._box_prompt_layer)
305        vutil.sync_prompt_shape_current_color(self._box_prompt_layer)
306
307        # Trigger a new connection for the tracking state menu only when a new layer is (re)created.
308        if _new_point_layer or _new_box_layer:
309            self._tracking_widget = create_tracking_menu(
310                points_layer=self._point_prompt_layer,
311                box_layer=self._box_prompt_layer,
312                states=self._track_state_labels,
313                track_ids=list(state.lineage.keys()),
314                point_labels=self._point_labels,
315                tracking_widget=getattr(self, "_tracking_widget", None),
316                viewer=self._viewer,
317            )
318
319    def _get_widgets(self):
320        self._require_layers()
321
322        # Ensure the tracking state menu exists. '_require_layers' creates it when it recreates the
323        # layers. Create it here as a fallback otherwise.
324        if getattr(self, "_tracking_widget", None) is None:
325            self._tracking_widget = create_tracking_menu(
326                points_layer=self._point_prompt_layer,
327                box_layer=self._box_prompt_layer,
328                states=self._track_state_labels,
329                track_ids=list(AnnotatorState().lineage.keys()),
330                point_labels=self._point_labels,
331                viewer=self._viewer,
332            )
333
334        # The prompt menu, the track id / track state menus and the segment / clear controls all
335        # live in a single merged container, mirroring the segmentation annotator.
336        interactive = widgets.InteractiveTrackingWidget(
337            self._viewer, tracking_widget=self._tracking_widget,
338        )
339        autotrack = widgets.AutoTrackWidget(
340            self._viewer, with_decoder=self._with_decoder, volumetric=True
341        )
342        return {
343            "interactive": interactive,
344            "autosegment": autotrack,
345            "commit": widgets.commit_track(),
346            "export": widgets.export_track(),
347        }
348
349    def _create_keybindings(self):
350        interactive = self._widgets["interactive"]
351
352        @self._viewer.bind_key("s", overwrite=True)
353        def _segment(viewer):
354            interactive.segment(viewer)
355
356        # We also need to over-write the keybindings for the prompt layers.
357        # See https://github.com/napari/napari/issues/7302 for details.
358        prompt_layer = self._viewer.layers["prompts"]
359        point_prompt_layer = self._viewer.layers["point_prompts"]
360
361        @prompt_layer.bind_key("s", overwrite=True)
362        def _segment_prompts(event):
363            interactive.segment(self._viewer)
364
365        @point_prompt_layer.bind_key("s", overwrite=True)
366        def _segment_point_prompts(event):
367            interactive.segment(self._viewer)
368
369        # The layer the key reached is the active one, so it goes first: only it relabels a selected
370        # scribble. The viewer-level fallback below has no active prompt layer, so it relabels none.
371        @prompt_layer.bind_key("t", overwrite=True)
372        def _toggle_shape_prompt_label(event=None):
373            vutil.toggle_label(self._box_prompt_layer, self._point_prompt_layer)
374
375        @point_prompt_layer.bind_key("t", overwrite=True)
376        def _toggle_point_prompt_label(event=None):
377            vutil.toggle_label(self._point_prompt_layer, self._box_prompt_layer)
378
379        @self._viewer.bind_key("c", overwrite=True)
380        def _commit(viewer):
381            self._widgets["commit"](viewer)
382
383        @self._viewer.bind_key("t", overwrite=True)
384        def _toggle_label(event=None):
385            vutil.toggle_label(self._point_prompt_layer, self._box_prompt_layer)
386
387        @self._viewer.bind_key("Shift-C", overwrite=True)
388        def _clear_annotations(viewer):
389            interactive.clear(viewer)
390
391    def __init__(
392        self, viewer: "napari.viewer.Viewer", reset_state: bool = True
393    ) -> None:
394        # Initialize the state for tracking.
395        self._init_track_state()
396        # At startup the decoder is not loaded yet. Also treat the default model as decoder-capable
397        # when it has a registered decoder, so the default mode is correct before 'Compute Embeddings'.
398        from ..v2.util import has_registered_decoder
399        self._with_decoder = AnnotatorState().decoder is not None or has_registered_decoder(DEFAULT_MODEL)
400        super().__init__(viewer=viewer, ndim=3)
401        # Go to t=0.
402        self._viewer.dims.current_step = (0, 0, 0) + tuple(
403            sh // 2 for sh in self._shape[1:]
404        )
405
406        # Set the expected annotator class to the state.
407        state = AnnotatorState()
408
409        # Reset the state.
410        if reset_state:
411            state.reset_state()
412
413        state.annotator = self
414
415    def _init_track_state(self):
416        state = AnnotatorState()
417        state.current_track_id = 1
418        state.lineage = {1: []}
419        state.committed_lineages = []
420
421    def _update_image(self):
422        super()._update_image()
423        self._init_track_state()

Base class for micro_sam annotation plugins.

Implements the logic for the 2d, 3d and tracking annotator. The annotators differ in their data dimensionality and the widgets.

AnnotatorTracking(viewer: napari.viewer.Viewer, reset_state: bool = True)
391    def __init__(
392        self, viewer: "napari.viewer.Viewer", reset_state: bool = True
393    ) -> None:
394        # Initialize the state for tracking.
395        self._init_track_state()
396        # At startup the decoder is not loaded yet. Also treat the default model as decoder-capable
397        # when it has a registered decoder, so the default mode is correct before 'Compute Embeddings'.
398        from ..v2.util import has_registered_decoder
399        self._with_decoder = AnnotatorState().decoder is not None or has_registered_decoder(DEFAULT_MODEL)
400        super().__init__(viewer=viewer, ndim=3)
401        # Go to t=0.
402        self._viewer.dims.current_step = (0, 0, 0) + tuple(
403            sh // 2 for sh in self._shape[1:]
404        )
405
406        # Set the expected annotator class to the state.
407        state = AnnotatorState()
408
409        # Reset the state.
410        if reset_state:
411            state.reset_state()
412
413        state.annotator = self

Create the annotator GUI.

Arguments:
  • viewer: The napari viewer.
  • ndim: The number of spatial dimension of the image data (2 or 3).
def annotator_tracking( image: numpy.ndarray, embedding_path: Optional[str] = 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) -> Optional[napari.viewer.Viewer]:
426def annotator_tracking(
427    image: np.ndarray,
428    embedding_path: Optional[str] = None,
429    # tracking_result: Optional[str] = None,
430    model_type: str = DEFAULT_MODEL,
431    tile_shape: Optional[Tuple[int, int]] = None,
432    halo: Optional[Tuple[int, int]] = None,
433    return_viewer: bool = False,
434    viewer: Optional["napari.viewer.Viewer"] = None,
435    precompute_autoseg_state: bool = False,
436    checkpoint_path: Optional[str] = None,
437    decoder_path: Optional[str] = None,
438    device: Optional[Union[str, torch.device]] = None,
439) -> Optional["napari.viewer.Viewer"]:
440    """Start the tracking annotation tool fora given timeseries.
441
442    Args:
443        image: The image data.
444        embedding_path: Filepath for saving the precomputed embeddings.
445        model_type: The Segment Anything model to use. For details on the available models check out
446            https://computational-cell-analytics.github.io/micro-sam/micro_sam.html#finetuned-models.
447        tile_shape: Shape of tiles for tiled embedding prediction. If `None`, reuse the tiling of
448            already cached embeddings, else use the default tiling for images exceeding the in-plane
449            size threshold, and pass smaller images to Segment Anything without tiling.
450        halo: Shape of the overlap between tiles, which is needed to segment objects on tile borders.
451            If `None`, use the default overlap whenever tiling is active.
452        return_viewer: Whether to return the napari viewer to further modify it before starting the tool.
453            By default, does not return the napari viewer.
454        viewer: The viewer to which the Segment Anything functionality should be added.
455            This enables using a pre-initialized viewer.
456        precompute_autoseg_state: Whether to precompute the automatic segmentation state (the decoder
457            predictions). Requires an embedding path and a model with a decoder; it is ignored for a
458            model without one. This will take more time when precomputing embeddings, but will then
459            make automatic segmentation much faster. By default, set to 'False'.
460        checkpoint_path: Path to a custom checkpoint from which to load the SAM model.
461        decoder_path: Path to a custom decoder checkpoint from which to load the 'micro-sam` decoder.
462        device: The computational device to use for the SAM model.
463            By default, automatically chooses the best available device.
464
465    Returns:
466        The napari viewer, only returned if `return_viewer=True`.
467    """
468    vutil._validate_sam2_model_type(model_type, "tracking")
469
470    # Prepare the image in the same way as the annotator. A timeseries is read as a volume (T, H, W).
471    image, _, rgb = prepare_annotation_image(image, ndim=3)
472
473    # Initialize the predictor state.
474    state = AnnotatorState()
475    state.image_shape = image.shape[:3]
476
477    # The API / CLI computes embeddings before creating the widget, so apply the same size
478    # heuristic here. Reuse these resolved settings when syncing the widget below.
479    tile_shape, halo = resolve_default_tiling(state.image_shape, tile_shape, halo, embedding_path)
480
481    state.initialize_predictor(
482        image,
483        model_type=model_type,
484        save_path=embedding_path,
485        halo=halo,
486        tile_shape=tile_shape,
487        prefer_decoder=True,
488        ndim=3,
489        checkpoint_path=checkpoint_path,
490        decoder_path=decoder_path,
491        device=device,
492        precompute_autoseg_state=precompute_autoseg_state,
493        use_cli=True,
494    )
495
496    if viewer is None:
497        viewer = napari.Viewer()
498
499    viewer.add_image(image, name="image", rgb=rgb)
500    annotator = AnnotatorTracking(viewer, reset_state=False)
501
502    # Trigger layer update of the annotator so that layers have the correct shape.
503    annotator._update_image()
504
505    # Add the annotator widget to the viewer and sync widgets.
506    viewer.window.add_dock_widget(annotator, name=get_dock_title("tracking"))
507    vutil._sync_embedding_widget(
508        widget=state.widgets["embeddings"],
509        model_type=(
510            model_type
511            if checkpoint_path is None
512            else state.predictor.model_type
513        ),
514        save_path=embedding_path,
515        checkpoint_path=checkpoint_path,
516        device=device,
517        tile_shape=tile_shape,
518        halo=halo,
519    )
520
521    if return_viewer:
522        return viewer
523
524    napari.run()

Start the tracking annotation tool fora given timeseries.

Arguments:
  • image: The image data.
  • embedding_path: Filepath for saving the precomputed embeddings.
  • model_type: The Segment Anything model to use. For details on the available models check out 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.
Returns:

The napari viewer, only returned if return_viewer=True.

class TrackingBatchTask(micro_sam.sam_annotator._batch.BatchAnnotatorTask):
527class TrackingBatchTask(BatchAnnotatorTask):
528    """Batch task for tracking: each item is a TYX timeseries tracked independently."""
529
530    empty_item_message = "Nothing is tracked yet. Do you wish to continue to the next timeseries?"
531
532    # A timeseries is loaded as a volume (T, H, W).
533    ndim = 3
534
535    def __init__(
536        self, *, model_type, embedding_path=None, tile_shape=None, halo=None,
537        checkpoint_path=None, decoder_path=None, device=None,
538        precompute_autoseg_state=False, batch_size=1,
539    ):
540        vutil._validate_sam2_model_type(model_type, "tracking")
541        self.model_type = model_type
542        self.embedding_path = embedding_path
543        self.tile_shape = tile_shape
544        self.halo = halo
545        self.checkpoint_path = checkpoint_path
546        self.decoder_path = decoder_path
547        self.device = device
548        self.precompute_autoseg_state = precompute_autoseg_state
549        self.batch_size = batch_size
550
551    def result_filename(self, entry, index):
552        if self.have_inputs_as_arrays:
553            return f"tracks_{index:05}.tif"
554        return os.path.splitext(os.path.basename(entry))[0] + "_tracks.tif"
555
556    def precompute(self, images):
557        # The SAM2 video embeddings are computed lazily per video in start/advance. When an embedding
558        # folder is given, derive one per-video zarr path inside it. Otherwise keep them in memory.
559        if self.embedding_path is None:
560            return [None] * len(images)
561        os.makedirs(self.embedding_path, exist_ok=True)
562        if self.have_inputs_as_arrays:
563            return [os.path.join(self.embedding_path, f"tracking_{i:05}.zarr") for i in range(len(images))]
564        return [
565            os.path.join(self.embedding_path, os.path.splitext(os.path.basename(p))[0] + ".zarr") for p in images
566        ]
567
568    def _init_predictor(self, image, embedding_path, reuse):
569        state = AnnotatorState()
570        # Reuse the loaded model and decoder on subsequent videos (only the embeddings and the
571        # interactive segmenter are rebuilt per video).
572        if reuse and state.predictor is not None:
573            kwargs = dict(predictor=state.predictor, decoder=state.decoder, prefer_decoder=False)
574        else:
575            kwargs = dict(prefer_decoder=True)
576        # The image is prepared by 'load_batch_image', so a channel axis is always the last one.
577        state.image_shape = image.shape[:3]
578        # Resolve the tiling per timeseries, since the shapes can differ across the batch.
579        tile_shape, halo = resolve_default_tiling(state.image_shape, self.tile_shape, self.halo, embedding_path)
580        state.initialize_predictor(
581            image, model_type=self.model_type, save_path=embedding_path, halo=halo,
582            tile_shape=tile_shape, ndim=3, checkpoint_path=self.checkpoint_path,
583            decoder_path=self.decoder_path, device=self.device, batch_size=self.batch_size,
584            precompute_autoseg_state=self.precompute_autoseg_state,
585            use_cli=True, **kwargs,
586        )
587        return tile_shape, halo
588
589    def start(self, viewer, entry, image, embedding_path, index):
590        tile_shape, halo = self._init_predictor(image, embedding_path, reuse=False)
591        viewer.add_image(image, name="image", rgb=image.ndim > 3)
592        AnnotatorState().image_scale = tuple(viewer.layers["image"].scale)
593
594        annotator = AnnotatorTracking(viewer, reset_state=False)
595        annotator._update_image()
596
597        state = AnnotatorState()
598        viewer.window.add_dock_widget(annotator, name=get_dock_title("batch_tracking"))
599        vutil._sync_embedding_widget(
600            widget=state.widgets["embeddings"],
601            model_type=self.model_type if self.checkpoint_path is None else state.predictor.model_type,
602            save_path=embedding_path, checkpoint_path=self.checkpoint_path,
603            device=self.device, tile_shape=tile_shape, halo=halo,
604        )
605        return annotator
606
607    def advance(self, viewer, annotator, entry, image, embedding_path, index):
608        viewer.layers["image"].data = image
609        tile_shape, halo = self._init_predictor(image, embedding_path, reuse=True)
610        vutil._sync_tiling_widget(AnnotatorState().widgets["embeddings"], tile_shape, halo)
611        AnnotatorState().image_scale = tuple(viewer.layers["image"].scale)
612        annotator._update_image()
613
614    def has_unsaved_content(self, viewer):
615        return viewer.layers["committed_objects"].data.sum() != 0
616
617    def save_item(self, viewer, entry, index):
618        save_path = os.path.join(self.output_folder, self.result_filename(entry, index))
619        imageio.imwrite(save_path, viewer.layers["committed_objects"].data, compression="zlib")

Batch task for tracking: each item is a TYX timeseries tracked independently.

TrackingBatchTask( *, model_type, embedding_path=None, tile_shape=None, halo=None, checkpoint_path=None, decoder_path=None, device=None, precompute_autoseg_state=False, batch_size=1)
535    def __init__(
536        self, *, model_type, embedding_path=None, tile_shape=None, halo=None,
537        checkpoint_path=None, decoder_path=None, device=None,
538        precompute_autoseg_state=False, batch_size=1,
539    ):
540        vutil._validate_sam2_model_type(model_type, "tracking")
541        self.model_type = model_type
542        self.embedding_path = embedding_path
543        self.tile_shape = tile_shape
544        self.halo = halo
545        self.checkpoint_path = checkpoint_path
546        self.decoder_path = decoder_path
547        self.device = device
548        self.precompute_autoseg_state = precompute_autoseg_state
549        self.batch_size = batch_size
empty_item_message = 'Nothing is tracked yet. Do you wish to continue to the next timeseries?'
ndim = 3
model_type
embedding_path
tile_shape
halo
checkpoint_path
decoder_path
device
precompute_autoseg_state
batch_size
def result_filename(self, entry, index):
551    def result_filename(self, entry, index):
552        if self.have_inputs_as_arrays:
553            return f"tracks_{index:05}.tif"
554        return os.path.splitext(os.path.basename(entry))[0] + "_tracks.tif"

Return the filename (relative to output_folder) of this item's saved result.

Used to skip items that are already done. entry is the raw batch entry (an array or a file path), index its position in the batch.

def precompute(self, images):
556    def precompute(self, images):
557        # The SAM2 video embeddings are computed lazily per video in start/advance. When an embedding
558        # folder is given, derive one per-video zarr path inside it. Otherwise keep them in memory.
559        if self.embedding_path is None:
560            return [None] * len(images)
561        os.makedirs(self.embedding_path, exist_ok=True)
562        if self.have_inputs_as_arrays:
563            return [os.path.join(self.embedding_path, f"tracking_{i:05}.zarr") for i in range(len(images))]
564        return [
565            os.path.join(self.embedding_path, os.path.splitext(os.path.basename(p))[0] + ".zarr") for p in images
566        ]

Prepare the shared model and per-item embeddings.

Returns a list with one embedding path (or None) per image, aligned to images.

def start(self, viewer, entry, image, embedding_path, index):
589    def start(self, viewer, entry, image, embedding_path, index):
590        tile_shape, halo = self._init_predictor(image, embedding_path, reuse=False)
591        viewer.add_image(image, name="image", rgb=image.ndim > 3)
592        AnnotatorState().image_scale = tuple(viewer.layers["image"].scale)
593
594        annotator = AnnotatorTracking(viewer, reset_state=False)
595        annotator._update_image()
596
597        state = AnnotatorState()
598        viewer.window.add_dock_widget(annotator, name=get_dock_title("batch_tracking"))
599        vutil._sync_embedding_widget(
600            widget=state.widgets["embeddings"],
601            model_type=self.model_type if self.checkpoint_path is None else state.predictor.model_type,
602            save_path=embedding_path, checkpoint_path=self.checkpoint_path,
603            device=self.device, tile_shape=tile_shape, halo=halo,
604        )
605        return annotator

Initialize the predictor/state for the first item, dock the annotator and return it.

def advance(self, viewer, annotator, entry, image, embedding_path, index):
607    def advance(self, viewer, annotator, entry, image, embedding_path, index):
608        viewer.layers["image"].data = image
609        tile_shape, halo = self._init_predictor(image, embedding_path, reuse=True)
610        vutil._sync_tiling_widget(AnnotatorState().widgets["embeddings"], tile_shape, halo)
611        AnnotatorState().image_scale = tuple(viewer.layers["image"].scale)
612        annotator._update_image()

Load a subsequent item into the existing viewer and annotator.

def has_unsaved_content(self, viewer):
614    def has_unsaved_content(self, viewer):
615        return viewer.layers["committed_objects"].data.sum() != 0

Whether the user produced anything worth saving for the current item.

def save_item(self, viewer, entry, index):
617    def save_item(self, viewer, entry, index):
618        save_path = os.path.join(self.output_folder, self.result_filename(entry, index))
619        imageio.imwrite(save_path, viewer.layers["committed_objects"].data, compression="zlib")

Persist the current item's result into output_folder.

def batch_tracking_annotator( images: Union[List[Union[os.PathLike, str]], List[numpy.ndarray]], output_folder: str, *, model_type: str = 'hvit_t_cells', embedding_path: Optional[str] = None, tile_shape: Optional[Tuple[int, int]] = None, halo: Optional[Tuple[int, int]] = None, checkpoint_path: Optional[str] = None, decoder_path: Optional[str] = None, device: Union[str, torch.device, NoneType] = None, precompute_autoseg_state: bool = False, viewer: Optional[napari.viewer.Viewer] = None, return_viewer: bool = False, skip_done: bool = True, batch_size: Optional[int] = 1) -> Optional[napari.viewer.Viewer]:
622def batch_tracking_annotator(
623    images: Union[List[Union[os.PathLike, str]], List[np.ndarray]],
624    output_folder: str,
625    *,
626    model_type: str = DEFAULT_MODEL,
627    embedding_path: Optional[str] = None,
628    tile_shape: Optional[Tuple[int, int]] = None,
629    halo: Optional[Tuple[int, int]] = None,
630    checkpoint_path: Optional[str] = None,
631    decoder_path: Optional[str] = None,
632    device: Optional[Union[str, torch.device]] = None,
633    precompute_autoseg_state: bool = False,
634    viewer: Optional["napari.viewer.Viewer"] = None,
635    return_viewer: bool = False,
636    skip_done: bool = True,
637    batch_size: Optional[int] = 1,
638) -> Optional["napari.viewer.Viewer"]:
639    """Run the tracking annotation tool for a batch of timeseries (each item is one TYX video).
640
641    Args:
642        images: List of timeseries (TYX arrays) or file paths, each tracked independently.
643        output_folder: The folder where the per-video tracking results are saved.
644        model_type: The Segment Anything 2 model to use. The name must start with 'hvit_'.
645        embedding_path: Folder where to save/load the per-video embeddings.
646        tile_shape: Shape of tiles for tiled embedding prediction. If `None`, reuse the tiling of
647            already cached embeddings, else use the default tiling for images exceeding the in-plane
648            size threshold, and pass smaller images to Segment Anything without tiling.
649        halo: Shape of the overlap between tiles, which is needed to segment objects on tile borders.
650            If `None`, use the default overlap whenever tiling is active.
651        checkpoint_path: Path to a custom checkpoint from which to load the SAM model.
652        decoder_path: Path to a custom decoder checkpoint from which to load the `micro-sam` decoder.
653        device: The computational device to use for the SAM model.
654            By default, automatically chooses the best available device.
655        precompute_autoseg_state: Whether to precompute the automatic segmentation state (the decoder
656            predictions). Requires an embedding path and a model with a decoder.
657        viewer: The viewer to which the functionality should be added.
658        return_viewer: Whether to return the napari viewer instead of starting the event loop.
659        skip_done: Whether to skip videos whose tracking result already exists in `output_folder`.
660        batch_size: The number of tiles / slices per model call when computing the embeddings.
661            Only has an effect on a GPU. Pass None to select it per device from the free VRAM
662            (SAM2 only). By default a single tile / slice is used.
663
664    Returns:
665        The napari viewer, only returned if `return_viewer=True`.
666    """
667    have_inputs_as_arrays = isinstance(images[0], np.ndarray)
668    task = TrackingBatchTask(
669        model_type=model_type, embedding_path=embedding_path, tile_shape=tile_shape, halo=halo,
670        checkpoint_path=checkpoint_path, decoder_path=decoder_path, device=device,
671        precompute_autoseg_state=precompute_autoseg_state, batch_size=batch_size,
672    )
673    return run_batch(
674        images, output_folder, task, have_inputs_as_arrays=have_inputs_as_arrays,
675        viewer=viewer, return_viewer=return_viewer, skip_done=skip_done,
676    )

Run the tracking annotation tool for a batch of timeseries (each item is one TYX video).

Arguments:
  • images: List of timeseries (TYX arrays) or file paths, each tracked independently.
  • output_folder: The folder where the per-video tracking results are saved.
  • model_type: The Segment Anything 2 model to use. The name must start with 'hvit_'.
  • embedding_path: Folder where to save/load the per-video embeddings.
  • 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.
  • 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.
  • precompute_autoseg_state: Whether to precompute the automatic segmentation state (the decoder predictions). Requires an embedding path and a model with a decoder.
  • viewer: The viewer to which the functionality should be added.
  • return_viewer: Whether to return the napari viewer instead of starting the event loop.
  • skip_done: Whether to skip videos whose tracking result already exists in output_folder.
  • batch_size: The number of tiles / slices per model call when computing the embeddings. Only has an effect on a GPU. Pass None to select it per device from the free VRAM (SAM2 only). By default a single tile / slice is used.
Returns:

The napari viewer, only returned if return_viewer=True.