micro_sam.sam_annotator.util

  1import os
  2import warnings
  3from dataclasses import dataclass
  4from typing import List, Optional, Tuple
  5
  6import numpy as np
  7from skimage import draw
  8
  9import napari
 10
 11from .. import util
 12
 13# Green and Red
 14LABEL_COLOR_CYCLE = ["#00FF00", "#FF0000"]
 15"""@private"""
 16
 17SCRIBBLE_SHAPE_TYPES = ("path", "line")
 18"""Napari shape types interpreted as sparse scribble prompts."""
 19
 20SCRIBBLE_DRAW_MODES = ("add_path", "add_polyline", "add_line")
 21"""Napari Shapes modes that create open scribble prompts."""
 22
 23
 24#
 25# Misc helper functions
 26#
 27
 28
 29# The image normalization is shared with the headless entry points, so the GUI and the CLI read the
 30# same array the same way. It lives in 'micro_sam.util', which does not import napari.
 31prepare_annotation_image = util.prepare_annotation_image
 32
 33
 34def _validate_sam2_model_type(model_type: str, tool: str) -> None:
 35    """Check that the model is a Segment Anything 2 model.
 36
 37    Only the classification tools support other models.
 38
 39    Args:
 40        model_type: The name of the model.
 41        tool: The name of the annotation tool, for example 'segmentation' or 'tracking'.
 42
 43    Raises:
 44        ValueError: If the model is not a Segment Anything 2 model.
 45    """
 46    if not model_type.startswith("hvit_"):
 47        raise ValueError(
 48            f"The {tool} annotator does not support the model '{model_type}'. Use a (ยต)SAM2 model ('hvit_*')."
 49        )
 50
 51
 52def set_prompt_label(layer, new_label, relabel_selected: bool = True):
 53    """Set the current prompt label and relabel selected shapes consistently.
 54
 55    Napari Points applies ``current_properties`` changes to selected points in all modes. Shapes,
 56    however, only applies them to selected shapes in select or pan/zoom mode. Explicitly updating
 57    the selected open shapes here keeps changing the prompt menu or pressing ``T`` consistent for
 58    both layer types, including immediately after drawing a path, polyline or line.
 59
 60    Args:
 61        layer: The prompt layer.
 62        new_label: The label to set as the drawing default.
 63        relabel_selected: Whether the layer's selected scribbles also take the new label. Pass False
 64            for a layer the user is not working in: napari leaves a freshly drawn scribble selected,
 65            so a polarity change aimed at another layer would otherwise silently relabel it.
 66    """
 67    if isinstance(layer, napari.layers.Shapes):
 68        # Napari may briefly retain a selected shape index after the corresponding geometry and
 69        # feature row have been removed. Setting current_properties in that state tries to update a
 70        # missing pandas row. Drop these stale indices before applying the new drawing label.
 71        valid_selection = {
 72            index for index in layer.selected_data if 0 <= index < len(layer.data)
 73        }
 74        if valid_selection != layer.selected_data:
 75            layer.selected_data = valid_selection
 76
 77    is_shapes = isinstance(layer, napari.layers.Shapes)
 78    if not relabel_selected and layer.selected_data:
 79        # Napari applies current_properties to the selection itself - to selected points in every mode,
 80        # and to selected shapes in select and pan/zoom mode - and it selects a prompt right after it is
 81        # placed. A prompt that has to keep its own label therefore cannot stay selected while the
 82        # drawing default changes. Dropping the selection is right here anyway: that prompt is finished
 83        # and the user has moved to the other layer.
 84        layer.selected_data = set()
 85
 86    current_properties = layer.current_properties
 87    current_properties["label"] = np.array([new_label])
 88    layer.current_properties = current_properties
 89
 90    if relabel_selected and is_shapes and layer.selected_data:
 91        properties = dict(layer.properties)
 92        labels = np.asarray(properties.get("label", []), dtype=object).copy()
 93        shape_types = list(layer.shape_type)
 94        if len(labels) == len(shape_types):
 95            for index in layer.selected_data:
 96                if shape_types[index] in SCRIBBLE_SHAPE_TYPES:
 97                    labels[index] = new_label
 98            properties["label"] = labels
 99            layer.properties = properties
100
101            # Keep the drawing default on the requested label. Updating the feature table above
102            # may infer a current value from the edited selection.
103            current_properties = layer.current_properties
104            current_properties["label"] = np.array([new_label])
105            layer.current_properties = current_properties
106
107    layer.refresh()
108    if isinstance(layer, napari.layers.Shapes):
109        # During layer reset/teardown napari can briefly clear shape geometry before shrinking the
110        # feature table. Refreshing mapped colors in that transient state raises because the color
111        # array and ShapeList have different lengths. The subsequent data/features event will
112        # refresh once they are aligned again.
113        n_shapes = len(layer.data)
114        if any(len(values) != n_shapes for values in layer.properties.values()):
115            return
116    layer.refresh_colors()
117
118
119def relabels_selection(layer, viewer) -> bool:
120    """Whether a polarity change may also relabel this layer's selected scribbles.
121
122    Only the layer the user is working in may: napari leaves a freshly drawn scribble selected, so a
123    polarity change aimed at another layer would otherwise reach back and relabel it. Without a viewer
124    to ask, the caller already knows which layer is active and this stays permissive.
125
126    Args:
127        layer: The prompt layer about to take a new label.
128        viewer: The napari viewer, or None when the active layer cannot be determined.
129
130    Returns:
131        Whether the layer's selected scribbles should take the new label too.
132    """
133    if viewer is None:
134        return True
135    # Compare by name: napari hands out layers wrapped in a public-only proxy, so the active layer is
136    # not always the same object as the one in 'viewer.layers'.
137    active = viewer.layers.selection.active
138    return active is not None and layer.name == active.name
139
140
141def toggle_label(active_prompts, *linked_prompts):
142    """Toggle the positive/negative label of the active prompt layer, and follow with the linked ones.
143
144    The polarity itself is global: it becomes the drawing default for every prompt layer, so the shared
145    prompt menu keeps describing all of them. Only the active layer also relabels its selected
146    scribbles - napari leaves a freshly drawn scribble selected, so flipping the polarity for the next
147    point would otherwise reach back and relabel it.
148
149    Args:
150        active_prompts: The prompt layer the toggle came from, and the source of the current label.
151        linked_prompts: The other prompt layers, which follow the new drawing default.
152    """
153    current_label = active_prompts.current_properties["label"][0]
154    new_label = "negative" if current_label == "positive" else "positive"
155    set_prompt_label(active_prompts, new_label)
156    for layer in linked_prompts:
157        set_prompt_label(layer, new_label, relabel_selected=False)
158
159
160def normalize_prompt_shape_labels(layer_or_event):
161    """Keep closed shape prompts positive while preserving labels for open scribbles.
162
163    The shared Shapes layer uses its ``label`` property for edge coloring. Boxes and dense mask
164    shapes do not support negative semantics, so they are normalized to positive after creation.
165    The function then restores the current drawing defaults. A box that you draw does not change
166    the label for the next point or scribble. In the tracking annotator it also keeps the current
167    ``track_id``.
168    """
169    layer = layer_or_event if hasattr(layer_or_event, "shape_type") else layer_or_event.source
170    shape_types = list(layer.shape_type)
171    labels = np.asarray(layer.properties.get("label", []), dtype=object)
172    if len(shape_types) != len(labels):
173        return
174
175    normalized = labels.copy()
176    for index, shape_type in enumerate(shape_types):
177        if shape_type not in SCRIBBLE_SHAPE_TYPES:
178            normalized[index] = "positive"
179    if np.array_equal(labels, normalized):
180        return
181
182    # Save the drawing defaults first. An assignment to 'layer.properties' resets the current
183    # value of every column. This would otherwise drop the current 'track_id' on the tracking layer.
184    current_properties = dict(layer.current_properties)
185    properties = dict(layer.properties)
186    properties["label"] = normalized
187    layer.properties = properties
188    layer.current_properties = current_properties
189    layer.refresh_colors()
190
191
192def sync_prompt_shape_current_color(layer_or_event):
193    """Synchronize the Shapes drawing color with the current scribble label and tool."""
194    layer = layer_or_event if hasattr(layer_or_event, "shape_type") else layer_or_event.source
195    label = layer.current_properties.get("label", np.array(["positive"]))[0]
196    is_scribble_tool = layer.mode in SCRIBBLE_DRAW_MODES
197    color_index = 1 if is_scribble_tool and label == "negative" else 0
198    layer.current_edge_color = LABEL_COLOR_CYCLE[color_index]
199
200
201def current_slice(viewer: napari.Viewer, layer) -> int:
202    """@private
203
204    The index of the slice that the viewer shows, in the data coordinates of a layer. The viewer
205    position is in world coordinates, which differ from the index when the layer has a scale.
206    """
207    return int(round(layer.world_to_data(viewer.dims.point)[0]))
208
209
210def clear_annotations(viewer: napari.Viewer, clear_segmentations=True) -> None:
211    """@private"""
212    point_layer = viewer.layers["point_prompts"]
213    point_layer.selected_data = set(range(len(point_layer.data)))
214    point_layer.remove_selected()
215    point_layer.refresh()
216    if "prompts" in viewer.layers:
217        # Select all prompts and then remove them.
218        # This is how it worked before napari 0.5.
219        # viewer.layers["prompts"].data = []
220        viewer.layers["prompts"].selected_data = set(range(len(viewer.layers["prompts"].data)))
221        viewer.layers["prompts"].remove_selected()
222        viewer.layers["prompts"].refresh()
223    if not clear_segmentations:
224        return
225    viewer.layers["current_object"].data = np.zeros(viewer.layers["current_object"].data.shape, dtype="uint32")
226    viewer.layers["current_object"].refresh()
227
228
229def clear_annotations_slice(viewer: napari.Viewer, i: int, clear_segmentations=True) -> None:
230    """@private"""
231    point_layer = viewer.layers["point_prompts"]
232    point_layer.selected_data = set(np.flatnonzero(point_layer.data[:, 0] == i))
233    point_layer.remove_selected()
234    point_layer.refresh()
235    if "prompts" in viewer.layers:
236        prompt_layer = viewer.layers["prompts"]
237        prompt_layer.selected_data = {
238            index for index, prompt in enumerate(prompt_layer.data) if (prompt[:, 0] == i).all()
239        }
240        prompt_layer.remove_selected()
241        prompt_layer.refresh()
242    if not clear_segmentations:
243        return
244    viewer.layers["current_object"].data[i] = 0
245    viewer.layers["current_object"].refresh()
246
247
248#
249# Helper functions to extract prompts from napari layers.
250#
251
252
253def point_layer_to_prompts(
254    layer: napari.layers.Points, i=None, track_id=None, with_stop_annotation=True, exclude_states=None,
255) -> Optional[Tuple[np.ndarray, np.ndarray]]:
256    """Extract point prompts for SAM from a napari point layer.
257
258    Args:
259        layer: The point layer from which to extract the prompts.
260        i: Index for the data (required for 3d or timeseries data).
261        track_id: Id of the current track (required for tracking data).
262        with_stop_annotation: Whether a single negative point will be interpreted
263            as stop annotation or just returned as normal prompt.
264        exclude_states: Track-states to drop (e.g. ('division',)); such points mark a lineage
265            event rather than a segmentation prompt and must not be fed to the predictor.
266
267    Returns:
268        The point coordinates for the prompts.
269        The labels (positive or negative / 1 or 0) for the prompts.
270    """
271
272    points = layer.data
273    labels = layer.properties["label"]
274    assert len(points) == len(labels)
275
276    # Drop points tagged with an excluded track-state (division markers are not prompts).
277    keep = np.ones(len(points), dtype=bool)
278    if exclude_states is not None and "state" in layer.properties:
279        keep = ~np.isin(np.asarray(layer.properties["state"]), list(exclude_states))
280
281    if i is None:
282        assert points.shape[1] == 2, f"{points.shape}"
283        this_points, this_labels = points[keep], labels[keep]
284    else:
285        assert points.shape[1] == 3, f"{points.shape}"
286        mask = (np.round(points[:, 0]) == i) & keep
287        this_points = points[mask][:, 1:]
288        this_labels = labels[mask]
289    assert len(this_points) == len(this_labels)
290
291    if track_id is not None:
292        assert i is not None
293        track_ids = np.array(list(map(int, layer.properties["track_id"])))[mask]
294        track_id_mask = track_ids == track_id
295        this_labels, this_points = this_labels[track_id_mask], this_points[track_id_mask]
296    assert len(this_points) == len(this_labels)
297
298    this_labels = np.array([1 if label == "positive" else 0 for label in this_labels])
299    # a single point with a negative label is interpreted as 'stop' signal
300    # in this case we return None
301    if with_stop_annotation and (len(this_points) == 1 and this_labels[0] == 0):
302        return None
303
304    return this_points, this_labels
305
306
307def _scribble_geometry(vertices, image_shape, spacing):
308    """Return normalized stroke geometry and bend information for adaptive sampling."""
309    vertices = np.asarray(vertices, dtype="float64")
310    if vertices.ndim != 2 or vertices.shape[1] != 2 or len(vertices) == 0:
311        raise ValueError("A scribble must have shape (N, 2) with at least one vertex.")
312
313    image_shape = np.asarray(image_shape, dtype="float64")
314    if image_shape.shape != (2,) or np.any(image_shape <= 0):
315        raise ValueError(f"Invalid 2D image shape: {tuple(image_shape)}.")
316
317    # SAM2 embeds prompts in a square 1024-pixel input frame. Measuring the stroke there makes the
318    # sampling density independent of the source image resolution and aspect ratio.
319    model_vertices = vertices * (1024.0 / image_shape)
320
321    # Remove consecutive duplicate vertices before measuring length or curvature. Freehand paths
322    # may contain these when the mouse briefly stops moving.
323    if len(model_vertices) > 1:
324        keep = np.concatenate([[True], np.linalg.norm(np.diff(model_vertices, axis=0), axis=1) > 0])
325        model_vertices = model_vertices[keep]
326
327    segment_lengths = np.linalg.norm(np.diff(model_vertices, axis=0), axis=1)
328    cumulative = np.concatenate([[0.0], np.cumsum(segment_lengths)])
329    total_length = float(cumulative[-1])
330
331    # Ramer-Douglas-Peucker simplification removes freehand jitter before curvature is measured.
332    # The retained inner vertices are meaningful bends that we try to preserve in the samples.
333    bend_indices = np.empty((0,), dtype="int64")
334    bend_angles = np.empty((0,), dtype="float64")
335    if len(model_vertices) > 2 and total_length > 0:
336        tolerance = spacing / 4.0
337        retained = {0, len(model_vertices) - 1}
338        pending = [(0, len(model_vertices) - 1)]
339        while pending:
340            start, stop = pending.pop()
341            if stop <= start + 1:
342                continue
343            start_point, stop_point = model_vertices[start], model_vertices[stop]
344            direction = stop_point - start_point
345            relative = model_vertices[start + 1:stop] - start_point
346            length_squared = float(np.dot(direction, direction))
347            if length_squared == 0:
348                distances = np.linalg.norm(relative, axis=1)
349            else:
350                fractions = np.clip(relative @ direction / length_squared, 0.0, 1.0)
351                projections = start_point + fractions[:, None] * direction
352                distances = np.linalg.norm(model_vertices[start + 1:stop] - projections, axis=1)
353            split = int(np.argmax(distances)) + start + 1
354            if distances[split - start - 1] > tolerance:
355                retained.add(split)
356                pending.extend([(start, split), (split, stop)])
357
358        retained = np.asarray(sorted(retained), dtype="int64")
359        simplified = model_vertices[retained]
360        if len(simplified) > 2:
361            incoming = simplified[1:-1] - simplified[:-2]
362            outgoing = simplified[2:] - simplified[1:-1]
363            cosine = np.sum(incoming * outgoing, axis=1) / (
364                np.linalg.norm(incoming, axis=1) * np.linalg.norm(outgoing, axis=1)
365            )
366            bend_indices = retained[1:-1]
367            bend_angles = np.arccos(np.clip(cosine, -1.0, 1.0))
368
369    return model_vertices, image_shape, cumulative, total_length, bend_indices, bend_angles
370
371
372def _scribble_sample_count(vertices, image_shape, spacing):
373    """Determine the sample demand from a stroke's length and simplified curvature."""
374    geometry = _scribble_geometry(vertices, image_shape, spacing)
375    total_length, bend_angles = geometry[3], geometry[5]
376    if total_length == 0:
377        return 1, total_length
378
379    length_samples = max(2, int(np.ceil(total_length / spacing)) + 1)
380    # Add one sample per 90 degrees of accumulated, de-jittered turning. This gives compact curved
381    # strokes more representation without letting every raw freehand vertex consume the budget.
382    curvature_samples = int(np.ceil(bend_angles.sum() / (np.pi / 2.0))) if len(bend_angles) else 0
383    return length_samples + curvature_samples, total_length
384
385
386def _allocate_scribble_samples(desired_counts, lengths, max_points):
387    """Share a global sample budget fairly, favouring strokes with greater demand."""
388    desired_counts = np.asarray(desired_counts, dtype="int64")
389    lengths = np.asarray(lengths, dtype="float64")
390    if len(desired_counts) == 0:
391        return desired_counts
392
393    # Every stroke must influence the prediction. If there are more strokes than the configured
394    # budget, expand it just enough to retain one representative point from each instead of
395    # silently dropping annotations.
396    budget = max(int(max_points), len(desired_counts))
397    if desired_counts.sum() <= budget:
398        return desired_counts
399
400    allocated = np.ones_like(desired_counts)
401    remaining = budget - len(allocated)
402
403    # Preserve both endpoints where the budget permits, prioritizing longer strokes if it does not.
404    endpoint_candidates = np.flatnonzero(desired_counts > 1)
405    endpoint_candidates = endpoint_candidates[np.argsort(-lengths[endpoint_candidates], kind="stable")]
406    n_endpoints = min(remaining, len(endpoint_candidates))
407    allocated[endpoint_candidates[:n_endpoints]] += 1
408    remaining -= n_endpoints
409    if remaining == 0:
410        return allocated
411
412    # Allocate the rest proportionally to each stroke's unmet length/curvature demand. Largest
413    # remainders make the result deterministic while using the complete budget.
414    demand = desired_counts - allocated
415    quotas = remaining * demand / demand.sum()
416    additions = np.floor(quotas).astype("int64")
417    allocated += additions
418    remaining -= int(additions.sum())
419    if remaining:
420        residual = quotas - additions
421        candidates = np.flatnonzero(demand > additions)
422        candidates = candidates[np.argsort(-residual[candidates], kind="stable")]
423        allocated[candidates[:remaining]] += 1
424    return allocated
425
426
427def _resample_scribble(vertices, image_shape, spacing, n_points):
428    """Resample one stroke while preserving endpoints and its strongest bends."""
429    model_vertices, image_shape, cumulative, total_length, bend_indices, bend_angles = (
430        _scribble_geometry(vertices, image_shape, spacing)
431    )
432    if total_length == 0:
433        return model_vertices[:1] * (image_shape / 1024.0)
434    if n_points == 1:
435        sample_distances = np.array([total_length / 2.0])
436    else:
437        n_bends = min(max(0, n_points - 2), len(bend_indices))
438        if n_bends:
439            strongest = np.argsort(-bend_angles, kind="stable")[:n_bends]
440            mandatory = np.concatenate([[0.0], cumulative[bend_indices[strongest]], [total_length]])
441            mandatory = np.unique(mandatory)
442        else:
443            mandatory = np.array([0.0, total_length])
444
445        n_extra = n_points - len(mandatory)
446        if n_extra > 0:
447            interval_lengths = np.diff(mandatory)
448            quotas = n_extra * interval_lengths / total_length
449            per_interval = np.floor(quotas).astype("int64")
450            remainder = n_extra - int(per_interval.sum())
451            if remainder:
452                order = np.argsort(-(quotas - per_interval), kind="stable")
453                per_interval[order[:remainder]] += 1
454
455            extra_distances = []
456            for start, stop, count in zip(mandatory[:-1], mandatory[1:], per_interval):
457                if count:
458                    extra_distances.extend(np.linspace(start, stop, count + 2)[1:-1])
459            sample_distances = np.sort(np.concatenate([mandatory, extra_distances]))
460        else:
461            sample_distances = mandatory
462
463    segment_ids = np.searchsorted(cumulative, sample_distances, side="right") - 1
464    segment_ids = np.clip(segment_ids, 0, len(model_vertices) - 2)
465
466    local_lengths = sample_distances - cumulative[segment_ids]
467    segment_lengths = np.diff(cumulative)
468    fractions = np.divide(
469        local_lengths,
470        segment_lengths[segment_ids],
471        out=np.zeros_like(local_lengths),
472        where=segment_lengths[segment_ids] > 0,
473    )
474    sampled_model = model_vertices[segment_ids] + fractions[:, None] * (
475        model_vertices[segment_ids + 1] - model_vertices[segment_ids]
476    )
477    return sampled_model * (image_shape / 1024.0)
478
479
480def scribble_layer_to_prompts(
481    layer: napari.layers.Shapes,
482    image_shape: Tuple[int, int],
483    i=None,
484    spacing: float = 32.0,
485    max_points_per_stroke: Optional[int] = None,
486    max_points: int = 64,
487    deduplication_distance: float = 4.0,
488    track_id=None,
489) -> Tuple[np.ndarray, np.ndarray]:
490    """Convert positive/negative open strokes into sparse SAM point prompts.
491
492    Napari stores both its freehand path and click-defined polyline tools as ``path`` shapes; a
493    two-vertex stroke is stored as ``line``. Each accepted stroke is resampled uniformly by arc
494    length in SAM's normalized 1024-pixel input space. A global prompt budget is shared according
495    to stroke length and simplified curvature, and nearby same-label samples from overlapping
496    strokes are collapsed. This keeps prompt density stable across source resolutions without
497    undersampling every long stroke at the same per-stroke cutoff.
498
499    Args:
500        layer: The shared ``prompts`` Shapes layer. Non-scribble shapes are ignored.
501        image_shape: The ``(height, width)`` of the image or volume slice.
502        i: Slice index for a 3D layer. Must be omitted for a 2D layer.
503        spacing: Approximate spacing between samples in SAM's 1024-pixel input space.
504        max_points_per_stroke: Optional compatibility cap for each stroke. By default there is no
505            per-stroke cap and ``max_points`` governs all strokes together.
506        max_points: Target maximum number of samples across all accepted scribbles. If there are
507            more strokes than this limit, it expands to retain one representative per stroke.
508        deduplication_distance: Distance in normalized model pixels below which samples from
509            overlapping strokes with the same label are considered duplicates.
510        track_id: Id of the current track. Required for tracking data. When given, the function
511            converts only the strokes whose ``track_id`` property matches.
512
513    Returns:
514        Sampled coordinates in ``(y, x)`` order and SAM labels (positive ``1``, negative ``0``).
515    """
516    if spacing <= 0:
517        raise ValueError("'spacing' must be positive.")
518    if max_points_per_stroke is not None and max_points_per_stroke <= 0:
519        raise ValueError("'max_points_per_stroke' must be positive.")
520    if max_points <= 0:
521        raise ValueError("'max_points' must be positive.")
522    if deduplication_distance < 0:
523        raise ValueError("'deduplication_distance' must be non-negative.")
524
525    shape_data = layer.data
526    shape_types = layer.shape_type
527    stroke_labels = layer.properties.get("label", [])
528    if not (len(shape_data) == len(shape_types) == len(stroke_labels)):
529        raise AssertionError("Scribble shapes, shape types and labels must have matching lengths.")
530
531    if track_id is None:
532        stroke_track_ids = [None] * len(shape_data)
533    else:
534        stroke_track_ids = list(map(int, layer.properties["track_id"]))
535        if len(stroke_track_ids) != len(shape_data):
536            raise AssertionError("Scribble shapes and track ids must have matching lengths.")
537
538    strokes = []
539    for vertices, shape_type, stroke_label, stroke_track_id in zip(
540        shape_data, shape_types, stroke_labels, stroke_track_ids
541    ):
542        if track_id is not None and stroke_track_id != track_id:
543            continue
544        if shape_type in ("rectangle", "ellipse", "polygon"):
545            continue
546        if shape_type not in SCRIBBLE_SHAPE_TYPES:
547            warnings.warn(
548                f"Shape type {shape_type} is not a scribble and will be ignored. "
549                "Use path, polyline or line in the 'prompts' layer.",
550                stacklevel=2,
551            )
552            continue
553        if stroke_label not in ("positive", "negative"):
554            warnings.warn(
555                f"Unknown scribble label {stroke_label!r}; the stroke will be ignored.", stacklevel=2
556            )
557            continue
558
559        vertices = np.asarray(vertices)
560        if i is None:
561            if vertices.ndim != 2 or vertices.shape[1] != 2:
562                raise ValueError("2D scribble vertices must have shape (N, 2).")
563            vertices_yx = vertices
564        else:
565            if vertices.ndim != 2 or vertices.shape[1] != 3:
566                raise ValueError("3D scribble vertices must have shape (N, 3).")
567            stroke_slices = np.round(vertices[:, 0]).astype(int)
568            if not np.all(stroke_slices == i):
569                continue
570            vertices_yx = vertices[:, 1:]
571
572        desired_count, length = _scribble_sample_count(vertices_yx, image_shape, spacing)
573        if max_points_per_stroke is not None:
574            desired_count = min(desired_count, max_points_per_stroke)
575        strokes.append((vertices_yx, stroke_label, desired_count, length))
576
577    if not strokes:
578        return np.empty((0, 2), dtype="float64"), np.empty((0,), dtype="int64")
579
580    sample_counts = _allocate_scribble_samples(
581        [stroke[2] for stroke in strokes], [stroke[3] for stroke in strokes], max_points
582    )
583    image_shape_array = np.asarray(image_shape, dtype="float64")
584    points, labels = [], []
585    previous_model_points = {0: [], 1: []}
586    for (vertices_yx, stroke_label, _, _), sample_count in zip(strokes, sample_counts):
587        sampled = _resample_scribble(
588            vertices_yx, image_shape=image_shape, spacing=spacing, n_points=sample_count
589        )
590        sam_label = 1 if stroke_label == "positive" else 0
591        current_model_points = []
592        for point in sampled:
593            model_point = point * (1024.0 / image_shape_array)
594            # Deduplicate only against earlier strokes so both endpoints of a very short individual
595            # stroke survive. Opposite-label conflicts are intentionally retained.
596            previous = previous_model_points[sam_label]
597            if previous and (
598                np.min(np.linalg.norm(np.asarray(previous) - model_point, axis=1)) <= deduplication_distance
599            ):
600                continue
601            if current_model_points and np.min(
602                np.linalg.norm(np.asarray(current_model_points) - model_point, axis=1)
603            ) == 0:
604                continue
605            current_model_points.append(model_point)
606            points.append(point)
607            labels.append(sam_label)
608        previous_model_points[sam_label].extend(current_model_points)
609
610    return np.asarray(points), np.asarray(labels, dtype="int64")
611
612
613def get_scribble_slices(layer: napari.layers.Shapes, track_id=None) -> np.ndarray:
614    """Return the sorted z-slices that contain open scribble shapes in a 3D Shapes layer.
615
616    When ``track_id`` is given, the function considers only scribbles whose ``track_id`` property matches.
617    """
618    shape_data = layer.data
619    shape_types = layer.shape_type
620    if len(shape_data) != len(shape_types):
621        raise AssertionError("Scribble shapes and shape types must have matching lengths.")
622
623    if track_id is None:
624        stroke_track_ids = [None] * len(shape_data)
625    else:
626        stroke_track_ids = list(map(int, layer.properties["track_id"]))
627
628    slices = []
629    for vertices, shape_type, stroke_track_id in zip(shape_data, shape_types, stroke_track_ids):
630        if shape_type not in SCRIBBLE_SHAPE_TYPES:
631            continue
632        if track_id is not None and stroke_track_id != track_id:
633            continue
634        vertices = np.asarray(vertices)
635        if vertices.ndim != 2 or vertices.shape[1] != 3:
636            continue
637        stroke_slices = np.round(vertices[:, 0]).astype(int)
638        if not np.all(stroke_slices == stroke_slices[0]):
639            warnings.warn("A 3D scribble must stay on one z-slice and will be ignored.", stacklevel=2)
640            continue
641        slices.append(stroke_slices[0])
642
643    return np.unique(slices).astype("int64") if slices else np.empty((0,), dtype="int64")
644
645
646def merge_point_prompts(*prompt_sets):
647    """Merge ``(points, labels)`` prompt tuples, preserving an empty ``(0, 2)`` convention."""
648    point_arrays, label_arrays = [], []
649    for points, labels in prompt_sets:
650        points = np.asarray(points).reshape(-1, 2)
651        labels = np.asarray(labels).reshape(-1)
652        if len(points) != len(labels):
653            raise AssertionError("The number of prompt coordinates and labels must match.")
654        if len(points):
655            point_arrays.append(points)
656            label_arrays.append(labels)
657    if not point_arrays:
658        return np.empty((0, 2), dtype="float64"), np.empty((0,), dtype="int64")
659    return np.concatenate(point_arrays), np.concatenate(label_arrays)
660
661
662@dataclass
663class FramePrompts:
664    """Every prompt annotated on a single frame (or on a 2d image), read from the napari layers.
665
666    Attributes:
667        points: The point prompts, including the points a scribble expands into, in (y, x) order.
668        labels: The label (1 positive, 0 negative) of each point.
669        boxes: The box prompts, one per rectangle, ellipse and polygon.
670        masks: The filled mask of each box, or None for a rectangle. Index-aligned with `boxes`.
671        is_stop: Whether the frame's sole segmentation cue is a stop annotation (a lone negative point).
672        have_scribbles: Whether the frame carries any scribble.
673    """
674    points: np.ndarray
675    labels: np.ndarray
676    boxes: List[np.ndarray]
677    masks: List[Optional[np.ndarray]]
678    is_stop: bool
679    have_scribbles: bool
680
681    def split_shapes(self) -> Tuple[List[np.ndarray], List[np.ndarray]]:
682        """Separate the rectangles (box prompts) from the shapes carrying a filled mask."""
683        boxes = [box for box, mask in zip(self.boxes, self.masks) if mask is None]
684        masks = [mask for mask in self.masks if mask is not None]
685        return boxes, masks
686
687
688def collect_frame_prompts(
689    point_layer: napari.layers.Points,
690    shape_layer: napari.layers.Shapes,
691    shape: Tuple[int, int],
692    i=None,
693    track_id=None,
694    exclude_states=None,
695    with_stop_annotation: bool = True,
696) -> FramePrompts:
697    """Read every prompt of one frame from the annotation layers.
698
699    The single place prompts are extracted, so the interactive, volumetric and tracking entry points
700    cannot drift apart. Scribbles and shapes are resolved first, so a lone negative point only counts
701    as a stop annotation when it is the frame's sole segmentation cue - beside a scribble, box or
702    mask it is a correction of that object. The points a scribble expands into are merged into the
703    point prompts.
704
705    Args:
706        point_layer: The napari point layer.
707        shape_layer: The napari shape layer, holding both the shape and the scribble prompts.
708        shape: The image shape (in-plane, without the frame axis).
709        i: Index for the data (required for 3d or timeseries data).
710        track_id: Id of the current track (required for tracking data).
711        exclude_states: Track-states to drop, e.g. ('division',). See `point_layer_to_prompts`.
712        with_stop_annotation: Whether a lone negative point may be read as a stop annotation.
713
714    Returns:
715        The prompts of the frame.
716    """
717    scribble_points, scribble_labels = scribble_layer_to_prompts(
718        shape_layer, image_shape=shape, i=i, track_id=track_id
719    )
720    have_scribbles = len(scribble_points) > 0
721    boxes, masks = shape_layer_to_prompts(shape_layer, shape, i=i, track_id=track_id)
722
723    prompts = point_layer_to_prompts(
724        point_layer, i=i, track_id=track_id, exclude_states=exclude_states,
725        with_stop_annotation=with_stop_annotation and not have_scribbles and not boxes,
726    )
727    if prompts is None:
728        return FramePrompts(
729            points=np.empty((0, 2), dtype="float64"), labels=np.empty((0,), dtype="int64"),
730            boxes=boxes, masks=masks, is_stop=True, have_scribbles=have_scribbles,
731        )
732
733    points, labels = merge_point_prompts(prompts, (scribble_points, scribble_labels))
734    return FramePrompts(
735        points=points, labels=labels, boxes=boxes, masks=masks,
736        is_stop=False, have_scribbles=have_scribbles,
737    )
738
739
740def shape_layer_to_prompts(
741    layer: napari.layers.Shapes, shape: Tuple[int, int], i=None, track_id=None
742) -> Tuple[List[np.ndarray], List[Optional[np.ndarray]]]:
743    """Extract prompts for SAM from a napari shape layer.
744
745    Extracts the bounding box for 'rectangle' shapes and the bounding box and corresponding mask
746    for 'ellipse' and 'polygon' shapes.
747
748    Args:
749        prompt_layer: The napari shape layer.
750        shape: The image shape.
751        i: Index for the data (required for 3d or timeseries data).
752        track_id: Id of the current track (required for tracking data).
753
754    Returns:
755        The box prompts.
756        The mask prompts.
757    """
758
759    def _to_prompts(shape_data, shape_types):
760        boxes, masks = [], []
761
762        for data, type_ in zip(shape_data, shape_types):
763
764            if type_ == "rectangle":
765                boxes.append(data)
766                masks.append(None)
767
768            elif type_ == "ellipse":
769                boxes.append(data)
770                center = np.mean(data, axis=0)
771                radius_r = ((data[2] - data[1]) / 2)[0]
772                radius_c = ((data[1] - data[0]) / 2)[1]
773                rr, cc = draw.ellipse(center[0], center[1], radius_r, radius_c, shape=shape)
774                mask = np.zeros(shape, dtype=bool)
775                mask[rr, cc] = 1
776                masks.append(mask)
777
778            elif type_ == "polygon":
779                boxes.append(data)
780                rr, cc = draw.polygon(data[:, 0], data[:, 1], shape=shape)
781                mask = np.zeros(shape, dtype=bool)
782                mask[rr, cc] = 1
783                masks.append(mask)
784
785            elif type_ in SCRIBBLE_SHAPE_TYPES:
786                continue
787
788            else:
789                warnings.warn(f"Shape type {type_} is not supported and will be ignored.")
790
791        # map to correct box format
792        boxes = [
793            np.array([box[:, 0].min(), box[:, 1].min(), box[:, 0].max(), box[:, 1].max()]) for box in boxes
794        ]
795        return boxes, masks
796
797    shape_data, shape_types = layer.data, layer.shape_type
798    assert len(shape_data) == len(shape_types)
799    if len(shape_data) == 0:
800        return [], []
801
802    if i is not None:
803        if track_id is None:
804            prompt_selection = [j for j, data in enumerate(shape_data) if (data[:, 0] == i).all()]
805        else:
806            track_ids = np.array(list(map(int, layer.properties["track_id"])))
807            prompt_selection = [
808                j for j, (data, this_track_id) in enumerate(zip(shape_data, track_ids))
809                if ((data[:, 0] == i).all() and this_track_id == track_id)
810            ]
811
812        shape_data = [shape_data[j][:, 1:] for j in prompt_selection]
813        shape_types = [shape_types[j] for j in prompt_selection]
814
815    boxes, masks = _to_prompts(shape_data, shape_types)
816    return boxes, masks
817
818
819def _sync_embedding_widget(widget, model_type, save_path, checkpoint_path, device, tile_shape, halo):
820
821    # VFM families (DINO / UNI / SAM3) live in the classification widget's advanced tier. Let the widget
822    # place the selection. The SAM family/size parsing below is skipped for these names: it parses the
823    # size positionally (vit_<size>), which does not apply and even index-errors on short names ('sam3').
824    from ..models.vfm import is_vfm_model
825    is_vfm = is_vfm_model(model_type)
826    if is_vfm and hasattr(widget, "set_model_family_size"):
827        family, size = widget._family_and_size_for_model(model_type)
828        widget.set_model_family_size(family, size)
829
830    if not is_vfm:
831        # Update the index for model family, eg. 'Natural Images (SAM)', 'Light Microscopy', etc.
832        supported_dropdown_maps = {
833            "lm": "Light Microscopy",
834            "em_organelles": "Electron Microscopy",
835            "medical_imaging": "Medical Imaging",
836            "histopathology": "Histopathology",
837        }
838
839        if model_type.startswith("hvit"):  # SAM2 models, eg. 'hvit_t'.
840            # Finetuned SAM2 families carry a suffix (e.g. 'hvit_t_cells' -> 'Microscopy'); the plain
841            # backbones ('hvit_t', ...) are natural-image models.
842            model_family = widget._family_for_sam2_model(model_type)
843        else:
844            model_family = "Natural Images (SAM)"  # No suffix match: stick to 'Natural Images (SAM)'.
845            for k, v in supported_dropdown_maps.items():
846                if model_type.endswith(k):
847                    model_family = v
848                    break
849
850        index = widget.model_family_dropdown.findText(model_family)
851        if index >= 0:
852            widget.model_family_dropdown.setCurrentIndex(index)
853
854        # Update the index for model size, eg. 'base', 'tiny', etc.
855        size_map = {"t": "tiny", "s": "small", "b": "base", "l": "large", "h": "huge"}
856        size_idx = 5 if model_type.startswith("hvit") else 4
857        model_size = size_map.get(model_type[size_idx])
858
859        if model_size is not None:
860            index = widget.model_size_dropdown.findText(model_size)
861            if index >= 0:
862                widget.model_size_dropdown.setCurrentIndex(index)
863
864    if save_path is not None and isinstance(save_path, str):
865        widget.embeddings_save_path_param.setText(str(save_path))
866
867    if checkpoint_path is not None:
868        widget.custom_weights_param.setText(str(checkpoint_path))
869
870    if device is not None:
871        widget.device = device
872        index = widget.device_dropdown.findText(device)
873        widget.device_dropdown.setCurrentIndex(index)
874
875    # Keep tiling as it is when nothing is passed: the caller may not know the settings (e.g. an
876    # old classifier spec without them), and the widget has already applied its own defaults.
877    _sync_tiling_widget(widget, tile_shape, halo, disable_when_none=False)
878
879
880def _sync_tiling_widget(widget, tile_shape, halo, disable_when_none=True):
881    """Show the tiling settings the embeddings were actually computed with in the embedding widget.
882
883    Args:
884        widget: The embedding widget.
885        tile_shape: The in-plane tile shape, None if the embeddings are computed without tiling.
886        halo: The in-plane tile overlap, None if the embeddings are computed without tiling.
887        disable_when_none: Whether `tile_shape=None` switches the tiling dropdown off. This is what
888            the annotation tools want, so the widget never claims a tiling that was not used. Pass
889            False where None just means 'unknown, leave the widget alone'.
890    """
891    if tile_shape is not None:
892        widget.tile_x_param.setValue(tile_shape[0])
893        widget.tile_y_param.setValue(tile_shape[1])
894        # Enable tiling so the loaded tile shape is used and shown.
895        widget.tiling_dropdown.setCurrentText("yes")
896    elif disable_when_none:
897        widget.tiling_dropdown.setCurrentText("no")
898
899    if halo is not None:
900        widget.halo_x_param.setValue(halo[0])
901        widget.halo_y_param.setValue(halo[1])
902
903
904# Read parameters from checkpoint path if it is given instead.
905def _sync_autosegment_widget(widget, model_type, checkpoint_path, update_decoder=None):
906    # The automatic segmentation widget builds its parameters from the backend defaults for the
907    # loaded model and mode (see 'AutoSegmentWidget._make_settings_widget'), so the things to sync
908    # here are which model is loaded and whether it can drive the widget at all.
909    if update_decoder is not None:
910        widget._reset_segmentation_mode(update_decoder, model_type=model_type)
911
912
913def _autoseg_state_descriptor(embedding_path, mode):
914    """Descriptor of the SAM2 automatic-segmentation state cache in the embedding Zarr.
915
916    Returns the embedding path and mode (the annotator only caches the 'ais' decoder predictions);
917    the state itself is loaded on demand by
918    `micro_sam.precompute_state.cache_autoseg_state`. The SAM2 automatic segmentation widget
919    reads/writes the cache directly, so this only records where it lives.
920    """
921    if embedding_path is None or not os.path.exists(embedding_path):
922        return {"embedding_path": None, "mode": mode}
923    return {"embedding_path": embedding_path, "mode": mode}
SCRIBBLE_SHAPE_TYPES = ('path', 'line')

Napari shape types interpreted as sparse scribble prompts.

SCRIBBLE_DRAW_MODES = ('add_path', 'add_polyline', 'add_line')

Napari Shapes modes that create open scribble prompts.

def prepare_annotation_image( image: numpy.ndarray, ndim: Optional[int] = None) -> Tuple[numpy.ndarray, int, bool]:
692def prepare_annotation_image(image: np.ndarray, ndim: Optional[int] = None) -> Tuple[np.ndarray, int, bool]:
693    """Normalize an image for annotation: squeeze singletons and map 2D channels to RGB.
694
695    Singleton axes (commonly exposed by formats like CZI) are squeezed out across all axes.
696    For a 2D image, the trailing channel axis is mapped to 3 channels: a 2-channel input is
697    padded with a zero channel and a 4-channel input is reduced to the first three (with a
698    warning). A 3D volume with a channel axis (3D+C) gets the same mapping on a trailing channel axis.
699
700    Args:
701        image: The input image data.
702        ndim: Optional override for the spatial dimensionality (2 or 3). A single-slice ``(1, H, W)``
703            volume keeps its z axis when ``3`` is passed. With ``None`` (the default)
704            the dimensionality is auto-detected from the shape (a trailing axis of size 3 -> RGB 2D,
705            of size 2 or 4 -> channels mapped to RGB 2D, otherwise a 3D volume). With ``2`` a 3D array
706            is read as a 2D multi-channel image, taking the smallest axis as the channel axis (so a
707            channels-first ``(C, H, W)`` array also works) and mapping the channels to RGB. With ``3``
708            a 3D array is read as a ``(Z, H, W)`` volume, and a 4D array as a volume with a channel
709            axis of size 2 to 4 at position 3, 1 or 0 (checked in that order), moved to the trailing
710            position. A 4D array with a trailing axis of size 2 to 4 is auto-detected as such a volume.
711
712    Returns:
713        A tuple of the normalized image, its spatial dimensionality (2 or 3), and whether
714        it has a trailing RGB channel axis.
715
716    Raises:
717        ValueError: If the (overridden) dimensionality cannot be applied to the image shape, or the
718            squeezed image is neither a 2D image nor a grayscale 3D volume.
719    """
720    if ndim not in (None, 2, 3):
721        raise ValueError(f"Invalid ndim override: {ndim}. Expected None, 2 or 3.")
722
723    input_ndim = image.ndim
724    image = np.squeeze(image)
725
726    # Forced 2D: read a 3D array as a 2D multi-channel image. The channel axis is taken to be the
727    # smallest axis (so both channels-first (C, H, W) and channels-last (H, W, C) work); it is moved
728    # to the trailing position and mapped to 3 channels.
729    if ndim == 2:
730        if image.ndim == 2:
731            return image, 2, False
732        if image.ndim == 3:
733            channel_axis = int(np.argmin(image.shape))
734            image = np.moveaxis(image, channel_axis, -1)
735            return _channels_to_rgb(image), 2, True
736        raise ValueError(f"Cannot interpret shape {image.shape} as a 2D image.")
737
738    # Forced 3D: read a 3D array as a (Z, H, W) volume, and a 4D array as a volume with a channel axis.
739    if ndim == 3:
740        if image.ndim == 3:
741            return image, 3, False
742        # A single-slice volume squeezes down to one plane; put the z axis back rather than reject
743        # it. A genuinely 2d input still raises: asking for a volume and passing a plane is an error.
744        if image.ndim == 2 and input_ndim == 3:
745            return image[None], 3, False
746        if image.ndim == 4:
747            # Channels-last (Z, H, W, C), channels-second (Z, C, H, W) or channels-first (C, Z, H, W).
748            channel_axis = next((axis for axis in (3, 1, 0) if image.shape[axis] in (2, 3, 4)), None)
749            if channel_axis is not None:
750                image = np.moveaxis(image, channel_axis, -1)
751                return _channels_to_rgb(image), 3, True
752        raise ValueError(f"Cannot interpret shape {image.shape} as a 3D volume.")
753
754    # Auto-detect. A 4D array with a trailing axis of size 2, 3 or 4 is a volume with channels
755    # (Z, H, W, C). Any other 4D array may be a volumetric time series (T, Z, H, W), which is not supported.
756    if image.ndim == 4:
757        if image.shape[-1] in (2, 3, 4):
758            return _channels_to_rgb(image), 3, True
759        raise ValueError(
760            f"Invalid image shape: {image.shape}. Expected 2D or 3D image data (3D+t is not supported). "
761            "Pass ndim=3 for a volume with a non-trailing channel axis."
762        )
763
764    # 2D image with a 2- or 4-channel trailing axis: map it to 3 channels. A trailing axis of any
765    # other size is left alone, so a size-3 axis stays RGB and anything else is treated as a volume.
766    if image.ndim == 3 and image.shape[-1] in (2, 4):
767        image = _channels_to_rgb(image)
768
769    # Map the (possibly normalized) shape to a spatial dimensionality and rgb flag.
770    if image.ndim == 2:
771        return image, 2, False
772    elif image.ndim == 3:
773        if image.shape[-1] == 3:
774            return image, 2, True
775        return image, 3, False
776    raise ValueError(f"Invalid image shape: {image.shape}. Expected 2D or 3D image data.")

Normalize an image for annotation: squeeze singletons and map 2D channels to RGB.

Singleton axes (commonly exposed by formats like CZI) are squeezed out across all axes. For a 2D image, the trailing channel axis is mapped to 3 channels: a 2-channel input is padded with a zero channel and a 4-channel input is reduced to the first three (with a warning). A 3D volume with a channel axis (3D+C) gets the same mapping on a trailing channel axis.

Arguments:
  • image: The input image data.
  • ndim: Optional override for the spatial dimensionality (2 or 3). A single-slice (1, H, W) volume keeps its z axis when 3 is passed. With None (the default) the dimensionality is auto-detected from the shape (a trailing axis of size 3 -> RGB 2D, of size 2 or 4 -> channels mapped to RGB 2D, otherwise a 3D volume). With 2 a 3D array is read as a 2D multi-channel image, taking the smallest axis as the channel axis (so a channels-first (C, H, W) array also works) and mapping the channels to RGB. With 3 a 3D array is read as a (Z, H, W) volume, and a 4D array as a volume with a channel axis of size 2 to 4 at position 3, 1 or 0 (checked in that order), moved to the trailing position. A 4D array with a trailing axis of size 2 to 4 is auto-detected as such a volume.
Returns:

A tuple of the normalized image, its spatial dimensionality (2 or 3), and whether it has a trailing RGB channel axis.

Raises:
  • ValueError: If the (overridden) dimensionality cannot be applied to the image shape, or the squeezed image is neither a 2D image nor a grayscale 3D volume.
def set_prompt_label(layer, new_label, relabel_selected: bool = True):
 53def set_prompt_label(layer, new_label, relabel_selected: bool = True):
 54    """Set the current prompt label and relabel selected shapes consistently.
 55
 56    Napari Points applies ``current_properties`` changes to selected points in all modes. Shapes,
 57    however, only applies them to selected shapes in select or pan/zoom mode. Explicitly updating
 58    the selected open shapes here keeps changing the prompt menu or pressing ``T`` consistent for
 59    both layer types, including immediately after drawing a path, polyline or line.
 60
 61    Args:
 62        layer: The prompt layer.
 63        new_label: The label to set as the drawing default.
 64        relabel_selected: Whether the layer's selected scribbles also take the new label. Pass False
 65            for a layer the user is not working in: napari leaves a freshly drawn scribble selected,
 66            so a polarity change aimed at another layer would otherwise silently relabel it.
 67    """
 68    if isinstance(layer, napari.layers.Shapes):
 69        # Napari may briefly retain a selected shape index after the corresponding geometry and
 70        # feature row have been removed. Setting current_properties in that state tries to update a
 71        # missing pandas row. Drop these stale indices before applying the new drawing label.
 72        valid_selection = {
 73            index for index in layer.selected_data if 0 <= index < len(layer.data)
 74        }
 75        if valid_selection != layer.selected_data:
 76            layer.selected_data = valid_selection
 77
 78    is_shapes = isinstance(layer, napari.layers.Shapes)
 79    if not relabel_selected and layer.selected_data:
 80        # Napari applies current_properties to the selection itself - to selected points in every mode,
 81        # and to selected shapes in select and pan/zoom mode - and it selects a prompt right after it is
 82        # placed. A prompt that has to keep its own label therefore cannot stay selected while the
 83        # drawing default changes. Dropping the selection is right here anyway: that prompt is finished
 84        # and the user has moved to the other layer.
 85        layer.selected_data = set()
 86
 87    current_properties = layer.current_properties
 88    current_properties["label"] = np.array([new_label])
 89    layer.current_properties = current_properties
 90
 91    if relabel_selected and is_shapes and layer.selected_data:
 92        properties = dict(layer.properties)
 93        labels = np.asarray(properties.get("label", []), dtype=object).copy()
 94        shape_types = list(layer.shape_type)
 95        if len(labels) == len(shape_types):
 96            for index in layer.selected_data:
 97                if shape_types[index] in SCRIBBLE_SHAPE_TYPES:
 98                    labels[index] = new_label
 99            properties["label"] = labels
100            layer.properties = properties
101
102            # Keep the drawing default on the requested label. Updating the feature table above
103            # may infer a current value from the edited selection.
104            current_properties = layer.current_properties
105            current_properties["label"] = np.array([new_label])
106            layer.current_properties = current_properties
107
108    layer.refresh()
109    if isinstance(layer, napari.layers.Shapes):
110        # During layer reset/teardown napari can briefly clear shape geometry before shrinking the
111        # feature table. Refreshing mapped colors in that transient state raises because the color
112        # array and ShapeList have different lengths. The subsequent data/features event will
113        # refresh once they are aligned again.
114        n_shapes = len(layer.data)
115        if any(len(values) != n_shapes for values in layer.properties.values()):
116            return
117    layer.refresh_colors()

Set the current prompt label and relabel selected shapes consistently.

Napari Points applies current_properties changes to selected points in all modes. Shapes, however, only applies them to selected shapes in select or pan/zoom mode. Explicitly updating the selected open shapes here keeps changing the prompt menu or pressing T consistent for both layer types, including immediately after drawing a path, polyline or line.

Arguments:
  • layer: The prompt layer.
  • new_label: The label to set as the drawing default.
  • relabel_selected: Whether the layer's selected scribbles also take the new label. Pass False for a layer the user is not working in: napari leaves a freshly drawn scribble selected, so a polarity change aimed at another layer would otherwise silently relabel it.
def relabels_selection(layer, viewer) -> bool:
120def relabels_selection(layer, viewer) -> bool:
121    """Whether a polarity change may also relabel this layer's selected scribbles.
122
123    Only the layer the user is working in may: napari leaves a freshly drawn scribble selected, so a
124    polarity change aimed at another layer would otherwise reach back and relabel it. Without a viewer
125    to ask, the caller already knows which layer is active and this stays permissive.
126
127    Args:
128        layer: The prompt layer about to take a new label.
129        viewer: The napari viewer, or None when the active layer cannot be determined.
130
131    Returns:
132        Whether the layer's selected scribbles should take the new label too.
133    """
134    if viewer is None:
135        return True
136    # Compare by name: napari hands out layers wrapped in a public-only proxy, so the active layer is
137    # not always the same object as the one in 'viewer.layers'.
138    active = viewer.layers.selection.active
139    return active is not None and layer.name == active.name

Whether a polarity change may also relabel this layer's selected scribbles.

Only the layer the user is working in may: napari leaves a freshly drawn scribble selected, so a polarity change aimed at another layer would otherwise reach back and relabel it. Without a viewer to ask, the caller already knows which layer is active and this stays permissive.

Arguments:
  • layer: The prompt layer about to take a new label.
  • viewer: The napari viewer, or None when the active layer cannot be determined.
Returns:

Whether the layer's selected scribbles should take the new label too.

def toggle_label(active_prompts, *linked_prompts):
142def toggle_label(active_prompts, *linked_prompts):
143    """Toggle the positive/negative label of the active prompt layer, and follow with the linked ones.
144
145    The polarity itself is global: it becomes the drawing default for every prompt layer, so the shared
146    prompt menu keeps describing all of them. Only the active layer also relabels its selected
147    scribbles - napari leaves a freshly drawn scribble selected, so flipping the polarity for the next
148    point would otherwise reach back and relabel it.
149
150    Args:
151        active_prompts: The prompt layer the toggle came from, and the source of the current label.
152        linked_prompts: The other prompt layers, which follow the new drawing default.
153    """
154    current_label = active_prompts.current_properties["label"][0]
155    new_label = "negative" if current_label == "positive" else "positive"
156    set_prompt_label(active_prompts, new_label)
157    for layer in linked_prompts:
158        set_prompt_label(layer, new_label, relabel_selected=False)

Toggle the positive/negative label of the active prompt layer, and follow with the linked ones.

The polarity itself is global: it becomes the drawing default for every prompt layer, so the shared prompt menu keeps describing all of them. Only the active layer also relabels its selected scribbles - napari leaves a freshly drawn scribble selected, so flipping the polarity for the next point would otherwise reach back and relabel it.

Arguments:
  • active_prompts: The prompt layer the toggle came from, and the source of the current label.
  • linked_prompts: The other prompt layers, which follow the new drawing default.
def normalize_prompt_shape_labels(layer_or_event):
161def normalize_prompt_shape_labels(layer_or_event):
162    """Keep closed shape prompts positive while preserving labels for open scribbles.
163
164    The shared Shapes layer uses its ``label`` property for edge coloring. Boxes and dense mask
165    shapes do not support negative semantics, so they are normalized to positive after creation.
166    The function then restores the current drawing defaults. A box that you draw does not change
167    the label for the next point or scribble. In the tracking annotator it also keeps the current
168    ``track_id``.
169    """
170    layer = layer_or_event if hasattr(layer_or_event, "shape_type") else layer_or_event.source
171    shape_types = list(layer.shape_type)
172    labels = np.asarray(layer.properties.get("label", []), dtype=object)
173    if len(shape_types) != len(labels):
174        return
175
176    normalized = labels.copy()
177    for index, shape_type in enumerate(shape_types):
178        if shape_type not in SCRIBBLE_SHAPE_TYPES:
179            normalized[index] = "positive"
180    if np.array_equal(labels, normalized):
181        return
182
183    # Save the drawing defaults first. An assignment to 'layer.properties' resets the current
184    # value of every column. This would otherwise drop the current 'track_id' on the tracking layer.
185    current_properties = dict(layer.current_properties)
186    properties = dict(layer.properties)
187    properties["label"] = normalized
188    layer.properties = properties
189    layer.current_properties = current_properties
190    layer.refresh_colors()

Keep closed shape prompts positive while preserving labels for open scribbles.

The shared Shapes layer uses its label property for edge coloring. Boxes and dense mask shapes do not support negative semantics, so they are normalized to positive after creation. The function then restores the current drawing defaults. A box that you draw does not change the label for the next point or scribble. In the tracking annotator it also keeps the current track_id.

def sync_prompt_shape_current_color(layer_or_event):
193def sync_prompt_shape_current_color(layer_or_event):
194    """Synchronize the Shapes drawing color with the current scribble label and tool."""
195    layer = layer_or_event if hasattr(layer_or_event, "shape_type") else layer_or_event.source
196    label = layer.current_properties.get("label", np.array(["positive"]))[0]
197    is_scribble_tool = layer.mode in SCRIBBLE_DRAW_MODES
198    color_index = 1 if is_scribble_tool and label == "negative" else 0
199    layer.current_edge_color = LABEL_COLOR_CYCLE[color_index]

Synchronize the Shapes drawing color with the current scribble label and tool.

def point_layer_to_prompts( layer: napari.layers.points.points.Points, i=None, track_id=None, with_stop_annotation=True, exclude_states=None) -> Optional[Tuple[numpy.ndarray, numpy.ndarray]]:
254def point_layer_to_prompts(
255    layer: napari.layers.Points, i=None, track_id=None, with_stop_annotation=True, exclude_states=None,
256) -> Optional[Tuple[np.ndarray, np.ndarray]]:
257    """Extract point prompts for SAM from a napari point layer.
258
259    Args:
260        layer: The point layer from which to extract the prompts.
261        i: Index for the data (required for 3d or timeseries data).
262        track_id: Id of the current track (required for tracking data).
263        with_stop_annotation: Whether a single negative point will be interpreted
264            as stop annotation or just returned as normal prompt.
265        exclude_states: Track-states to drop (e.g. ('division',)); such points mark a lineage
266            event rather than a segmentation prompt and must not be fed to the predictor.
267
268    Returns:
269        The point coordinates for the prompts.
270        The labels (positive or negative / 1 or 0) for the prompts.
271    """
272
273    points = layer.data
274    labels = layer.properties["label"]
275    assert len(points) == len(labels)
276
277    # Drop points tagged with an excluded track-state (division markers are not prompts).
278    keep = np.ones(len(points), dtype=bool)
279    if exclude_states is not None and "state" in layer.properties:
280        keep = ~np.isin(np.asarray(layer.properties["state"]), list(exclude_states))
281
282    if i is None:
283        assert points.shape[1] == 2, f"{points.shape}"
284        this_points, this_labels = points[keep], labels[keep]
285    else:
286        assert points.shape[1] == 3, f"{points.shape}"
287        mask = (np.round(points[:, 0]) == i) & keep
288        this_points = points[mask][:, 1:]
289        this_labels = labels[mask]
290    assert len(this_points) == len(this_labels)
291
292    if track_id is not None:
293        assert i is not None
294        track_ids = np.array(list(map(int, layer.properties["track_id"])))[mask]
295        track_id_mask = track_ids == track_id
296        this_labels, this_points = this_labels[track_id_mask], this_points[track_id_mask]
297    assert len(this_points) == len(this_labels)
298
299    this_labels = np.array([1 if label == "positive" else 0 for label in this_labels])
300    # a single point with a negative label is interpreted as 'stop' signal
301    # in this case we return None
302    if with_stop_annotation and (len(this_points) == 1 and this_labels[0] == 0):
303        return None
304
305    return this_points, this_labels

Extract point prompts for SAM from a napari point layer.

Arguments:
  • layer: The point layer from which to extract the prompts.
  • i: Index for the data (required for 3d or timeseries data).
  • track_id: Id of the current track (required for tracking data).
  • with_stop_annotation: Whether a single negative point will be interpreted as stop annotation or just returned as normal prompt.
  • exclude_states: Track-states to drop (e.g. ('division',)); such points mark a lineage event rather than a segmentation prompt and must not be fed to the predictor.
Returns:

The point coordinates for the prompts. The labels (positive or negative / 1 or 0) for the prompts.

def scribble_layer_to_prompts( layer: napari.layers.shapes.shapes.Shapes, image_shape: Tuple[int, int], i=None, spacing: float = 32.0, max_points_per_stroke: Optional[int] = None, max_points: int = 64, deduplication_distance: float = 4.0, track_id=None) -> Tuple[numpy.ndarray, numpy.ndarray]:
481def scribble_layer_to_prompts(
482    layer: napari.layers.Shapes,
483    image_shape: Tuple[int, int],
484    i=None,
485    spacing: float = 32.0,
486    max_points_per_stroke: Optional[int] = None,
487    max_points: int = 64,
488    deduplication_distance: float = 4.0,
489    track_id=None,
490) -> Tuple[np.ndarray, np.ndarray]:
491    """Convert positive/negative open strokes into sparse SAM point prompts.
492
493    Napari stores both its freehand path and click-defined polyline tools as ``path`` shapes; a
494    two-vertex stroke is stored as ``line``. Each accepted stroke is resampled uniformly by arc
495    length in SAM's normalized 1024-pixel input space. A global prompt budget is shared according
496    to stroke length and simplified curvature, and nearby same-label samples from overlapping
497    strokes are collapsed. This keeps prompt density stable across source resolutions without
498    undersampling every long stroke at the same per-stroke cutoff.
499
500    Args:
501        layer: The shared ``prompts`` Shapes layer. Non-scribble shapes are ignored.
502        image_shape: The ``(height, width)`` of the image or volume slice.
503        i: Slice index for a 3D layer. Must be omitted for a 2D layer.
504        spacing: Approximate spacing between samples in SAM's 1024-pixel input space.
505        max_points_per_stroke: Optional compatibility cap for each stroke. By default there is no
506            per-stroke cap and ``max_points`` governs all strokes together.
507        max_points: Target maximum number of samples across all accepted scribbles. If there are
508            more strokes than this limit, it expands to retain one representative per stroke.
509        deduplication_distance: Distance in normalized model pixels below which samples from
510            overlapping strokes with the same label are considered duplicates.
511        track_id: Id of the current track. Required for tracking data. When given, the function
512            converts only the strokes whose ``track_id`` property matches.
513
514    Returns:
515        Sampled coordinates in ``(y, x)`` order and SAM labels (positive ``1``, negative ``0``).
516    """
517    if spacing <= 0:
518        raise ValueError("'spacing' must be positive.")
519    if max_points_per_stroke is not None and max_points_per_stroke <= 0:
520        raise ValueError("'max_points_per_stroke' must be positive.")
521    if max_points <= 0:
522        raise ValueError("'max_points' must be positive.")
523    if deduplication_distance < 0:
524        raise ValueError("'deduplication_distance' must be non-negative.")
525
526    shape_data = layer.data
527    shape_types = layer.shape_type
528    stroke_labels = layer.properties.get("label", [])
529    if not (len(shape_data) == len(shape_types) == len(stroke_labels)):
530        raise AssertionError("Scribble shapes, shape types and labels must have matching lengths.")
531
532    if track_id is None:
533        stroke_track_ids = [None] * len(shape_data)
534    else:
535        stroke_track_ids = list(map(int, layer.properties["track_id"]))
536        if len(stroke_track_ids) != len(shape_data):
537            raise AssertionError("Scribble shapes and track ids must have matching lengths.")
538
539    strokes = []
540    for vertices, shape_type, stroke_label, stroke_track_id in zip(
541        shape_data, shape_types, stroke_labels, stroke_track_ids
542    ):
543        if track_id is not None and stroke_track_id != track_id:
544            continue
545        if shape_type in ("rectangle", "ellipse", "polygon"):
546            continue
547        if shape_type not in SCRIBBLE_SHAPE_TYPES:
548            warnings.warn(
549                f"Shape type {shape_type} is not a scribble and will be ignored. "
550                "Use path, polyline or line in the 'prompts' layer.",
551                stacklevel=2,
552            )
553            continue
554        if stroke_label not in ("positive", "negative"):
555            warnings.warn(
556                f"Unknown scribble label {stroke_label!r}; the stroke will be ignored.", stacklevel=2
557            )
558            continue
559
560        vertices = np.asarray(vertices)
561        if i is None:
562            if vertices.ndim != 2 or vertices.shape[1] != 2:
563                raise ValueError("2D scribble vertices must have shape (N, 2).")
564            vertices_yx = vertices
565        else:
566            if vertices.ndim != 2 or vertices.shape[1] != 3:
567                raise ValueError("3D scribble vertices must have shape (N, 3).")
568            stroke_slices = np.round(vertices[:, 0]).astype(int)
569            if not np.all(stroke_slices == i):
570                continue
571            vertices_yx = vertices[:, 1:]
572
573        desired_count, length = _scribble_sample_count(vertices_yx, image_shape, spacing)
574        if max_points_per_stroke is not None:
575            desired_count = min(desired_count, max_points_per_stroke)
576        strokes.append((vertices_yx, stroke_label, desired_count, length))
577
578    if not strokes:
579        return np.empty((0, 2), dtype="float64"), np.empty((0,), dtype="int64")
580
581    sample_counts = _allocate_scribble_samples(
582        [stroke[2] for stroke in strokes], [stroke[3] for stroke in strokes], max_points
583    )
584    image_shape_array = np.asarray(image_shape, dtype="float64")
585    points, labels = [], []
586    previous_model_points = {0: [], 1: []}
587    for (vertices_yx, stroke_label, _, _), sample_count in zip(strokes, sample_counts):
588        sampled = _resample_scribble(
589            vertices_yx, image_shape=image_shape, spacing=spacing, n_points=sample_count
590        )
591        sam_label = 1 if stroke_label == "positive" else 0
592        current_model_points = []
593        for point in sampled:
594            model_point = point * (1024.0 / image_shape_array)
595            # Deduplicate only against earlier strokes so both endpoints of a very short individual
596            # stroke survive. Opposite-label conflicts are intentionally retained.
597            previous = previous_model_points[sam_label]
598            if previous and (
599                np.min(np.linalg.norm(np.asarray(previous) - model_point, axis=1)) <= deduplication_distance
600            ):
601                continue
602            if current_model_points and np.min(
603                np.linalg.norm(np.asarray(current_model_points) - model_point, axis=1)
604            ) == 0:
605                continue
606            current_model_points.append(model_point)
607            points.append(point)
608            labels.append(sam_label)
609        previous_model_points[sam_label].extend(current_model_points)
610
611    return np.asarray(points), np.asarray(labels, dtype="int64")

Convert positive/negative open strokes into sparse SAM point prompts.

Napari stores both its freehand path and click-defined polyline tools as path shapes; a two-vertex stroke is stored as line. Each accepted stroke is resampled uniformly by arc length in SAM's normalized 1024-pixel input space. A global prompt budget is shared according to stroke length and simplified curvature, and nearby same-label samples from overlapping strokes are collapsed. This keeps prompt density stable across source resolutions without undersampling every long stroke at the same per-stroke cutoff.

Arguments:
  • layer: The shared prompts Shapes layer. Non-scribble shapes are ignored.
  • image_shape: The (height, width) of the image or volume slice.
  • i: Slice index for a 3D layer. Must be omitted for a 2D layer.
  • spacing: Approximate spacing between samples in SAM's 1024-pixel input space.
  • max_points_per_stroke: Optional compatibility cap for each stroke. By default there is no per-stroke cap and max_points governs all strokes together.
  • max_points: Target maximum number of samples across all accepted scribbles. If there are more strokes than this limit, it expands to retain one representative per stroke.
  • deduplication_distance: Distance in normalized model pixels below which samples from overlapping strokes with the same label are considered duplicates.
  • track_id: Id of the current track. Required for tracking data. When given, the function converts only the strokes whose track_id property matches.
Returns:

Sampled coordinates in (y, x) order and SAM labels (positive 1, negative 0).

def get_scribble_slices( layer: napari.layers.shapes.shapes.Shapes, track_id=None) -> numpy.ndarray:
614def get_scribble_slices(layer: napari.layers.Shapes, track_id=None) -> np.ndarray:
615    """Return the sorted z-slices that contain open scribble shapes in a 3D Shapes layer.
616
617    When ``track_id`` is given, the function considers only scribbles whose ``track_id`` property matches.
618    """
619    shape_data = layer.data
620    shape_types = layer.shape_type
621    if len(shape_data) != len(shape_types):
622        raise AssertionError("Scribble shapes and shape types must have matching lengths.")
623
624    if track_id is None:
625        stroke_track_ids = [None] * len(shape_data)
626    else:
627        stroke_track_ids = list(map(int, layer.properties["track_id"]))
628
629    slices = []
630    for vertices, shape_type, stroke_track_id in zip(shape_data, shape_types, stroke_track_ids):
631        if shape_type not in SCRIBBLE_SHAPE_TYPES:
632            continue
633        if track_id is not None and stroke_track_id != track_id:
634            continue
635        vertices = np.asarray(vertices)
636        if vertices.ndim != 2 or vertices.shape[1] != 3:
637            continue
638        stroke_slices = np.round(vertices[:, 0]).astype(int)
639        if not np.all(stroke_slices == stroke_slices[0]):
640            warnings.warn("A 3D scribble must stay on one z-slice and will be ignored.", stacklevel=2)
641            continue
642        slices.append(stroke_slices[0])
643
644    return np.unique(slices).astype("int64") if slices else np.empty((0,), dtype="int64")

Return the sorted z-slices that contain open scribble shapes in a 3D Shapes layer.

When track_id is given, the function considers only scribbles whose track_id property matches.

def merge_point_prompts(*prompt_sets):
647def merge_point_prompts(*prompt_sets):
648    """Merge ``(points, labels)`` prompt tuples, preserving an empty ``(0, 2)`` convention."""
649    point_arrays, label_arrays = [], []
650    for points, labels in prompt_sets:
651        points = np.asarray(points).reshape(-1, 2)
652        labels = np.asarray(labels).reshape(-1)
653        if len(points) != len(labels):
654            raise AssertionError("The number of prompt coordinates and labels must match.")
655        if len(points):
656            point_arrays.append(points)
657            label_arrays.append(labels)
658    if not point_arrays:
659        return np.empty((0, 2), dtype="float64"), np.empty((0,), dtype="int64")
660    return np.concatenate(point_arrays), np.concatenate(label_arrays)

Merge (points, labels) prompt tuples, preserving an empty (0, 2) convention.

@dataclass
class FramePrompts:
663@dataclass
664class FramePrompts:
665    """Every prompt annotated on a single frame (or on a 2d image), read from the napari layers.
666
667    Attributes:
668        points: The point prompts, including the points a scribble expands into, in (y, x) order.
669        labels: The label (1 positive, 0 negative) of each point.
670        boxes: The box prompts, one per rectangle, ellipse and polygon.
671        masks: The filled mask of each box, or None for a rectangle. Index-aligned with `boxes`.
672        is_stop: Whether the frame's sole segmentation cue is a stop annotation (a lone negative point).
673        have_scribbles: Whether the frame carries any scribble.
674    """
675    points: np.ndarray
676    labels: np.ndarray
677    boxes: List[np.ndarray]
678    masks: List[Optional[np.ndarray]]
679    is_stop: bool
680    have_scribbles: bool
681
682    def split_shapes(self) -> Tuple[List[np.ndarray], List[np.ndarray]]:
683        """Separate the rectangles (box prompts) from the shapes carrying a filled mask."""
684        boxes = [box for box, mask in zip(self.boxes, self.masks) if mask is None]
685        masks = [mask for mask in self.masks if mask is not None]
686        return boxes, masks

Every prompt annotated on a single frame (or on a 2d image), read from the napari layers.

Attributes:
  • points: The point prompts, including the points a scribble expands into, in (y, x) order.
  • labels: The label (1 positive, 0 negative) of each point.
  • boxes: The box prompts, one per rectangle, ellipse and polygon.
  • masks: The filled mask of each box, or None for a rectangle. Index-aligned with boxes.
  • is_stop: Whether the frame's sole segmentation cue is a stop annotation (a lone negative point).
  • have_scribbles: Whether the frame carries any scribble.
FramePrompts( points: numpy.ndarray, labels: numpy.ndarray, boxes: List[numpy.ndarray], masks: List[Optional[numpy.ndarray]], is_stop: bool, have_scribbles: bool)
points: numpy.ndarray
labels: numpy.ndarray
boxes: List[numpy.ndarray]
masks: List[Optional[numpy.ndarray]]
is_stop: bool
have_scribbles: bool
def split_shapes(self) -> Tuple[List[numpy.ndarray], List[numpy.ndarray]]:
682    def split_shapes(self) -> Tuple[List[np.ndarray], List[np.ndarray]]:
683        """Separate the rectangles (box prompts) from the shapes carrying a filled mask."""
684        boxes = [box for box, mask in zip(self.boxes, self.masks) if mask is None]
685        masks = [mask for mask in self.masks if mask is not None]
686        return boxes, masks

Separate the rectangles (box prompts) from the shapes carrying a filled mask.

def collect_frame_prompts( point_layer: napari.layers.points.points.Points, shape_layer: napari.layers.shapes.shapes.Shapes, shape: Tuple[int, int], i=None, track_id=None, exclude_states=None, with_stop_annotation: bool = True) -> FramePrompts:
689def collect_frame_prompts(
690    point_layer: napari.layers.Points,
691    shape_layer: napari.layers.Shapes,
692    shape: Tuple[int, int],
693    i=None,
694    track_id=None,
695    exclude_states=None,
696    with_stop_annotation: bool = True,
697) -> FramePrompts:
698    """Read every prompt of one frame from the annotation layers.
699
700    The single place prompts are extracted, so the interactive, volumetric and tracking entry points
701    cannot drift apart. Scribbles and shapes are resolved first, so a lone negative point only counts
702    as a stop annotation when it is the frame's sole segmentation cue - beside a scribble, box or
703    mask it is a correction of that object. The points a scribble expands into are merged into the
704    point prompts.
705
706    Args:
707        point_layer: The napari point layer.
708        shape_layer: The napari shape layer, holding both the shape and the scribble prompts.
709        shape: The image shape (in-plane, without the frame axis).
710        i: Index for the data (required for 3d or timeseries data).
711        track_id: Id of the current track (required for tracking data).
712        exclude_states: Track-states to drop, e.g. ('division',). See `point_layer_to_prompts`.
713        with_stop_annotation: Whether a lone negative point may be read as a stop annotation.
714
715    Returns:
716        The prompts of the frame.
717    """
718    scribble_points, scribble_labels = scribble_layer_to_prompts(
719        shape_layer, image_shape=shape, i=i, track_id=track_id
720    )
721    have_scribbles = len(scribble_points) > 0
722    boxes, masks = shape_layer_to_prompts(shape_layer, shape, i=i, track_id=track_id)
723
724    prompts = point_layer_to_prompts(
725        point_layer, i=i, track_id=track_id, exclude_states=exclude_states,
726        with_stop_annotation=with_stop_annotation and not have_scribbles and not boxes,
727    )
728    if prompts is None:
729        return FramePrompts(
730            points=np.empty((0, 2), dtype="float64"), labels=np.empty((0,), dtype="int64"),
731            boxes=boxes, masks=masks, is_stop=True, have_scribbles=have_scribbles,
732        )
733
734    points, labels = merge_point_prompts(prompts, (scribble_points, scribble_labels))
735    return FramePrompts(
736        points=points, labels=labels, boxes=boxes, masks=masks,
737        is_stop=False, have_scribbles=have_scribbles,
738    )

Read every prompt of one frame from the annotation layers.

The single place prompts are extracted, so the interactive, volumetric and tracking entry points cannot drift apart. Scribbles and shapes are resolved first, so a lone negative point only counts as a stop annotation when it is the frame's sole segmentation cue - beside a scribble, box or mask it is a correction of that object. The points a scribble expands into are merged into the point prompts.

Arguments:
  • point_layer: The napari point layer.
  • shape_layer: The napari shape layer, holding both the shape and the scribble prompts.
  • shape: The image shape (in-plane, without the frame axis).
  • i: Index for the data (required for 3d or timeseries data).
  • track_id: Id of the current track (required for tracking data).
  • exclude_states: Track-states to drop, e.g. ('division',). See point_layer_to_prompts.
  • with_stop_annotation: Whether a lone negative point may be read as a stop annotation.
Returns:

The prompts of the frame.

def shape_layer_to_prompts( layer: napari.layers.shapes.shapes.Shapes, shape: Tuple[int, int], i=None, track_id=None) -> Tuple[List[numpy.ndarray], List[Optional[numpy.ndarray]]]:
741def shape_layer_to_prompts(
742    layer: napari.layers.Shapes, shape: Tuple[int, int], i=None, track_id=None
743) -> Tuple[List[np.ndarray], List[Optional[np.ndarray]]]:
744    """Extract prompts for SAM from a napari shape layer.
745
746    Extracts the bounding box for 'rectangle' shapes and the bounding box and corresponding mask
747    for 'ellipse' and 'polygon' shapes.
748
749    Args:
750        prompt_layer: The napari shape layer.
751        shape: The image shape.
752        i: Index for the data (required for 3d or timeseries data).
753        track_id: Id of the current track (required for tracking data).
754
755    Returns:
756        The box prompts.
757        The mask prompts.
758    """
759
760    def _to_prompts(shape_data, shape_types):
761        boxes, masks = [], []
762
763        for data, type_ in zip(shape_data, shape_types):
764
765            if type_ == "rectangle":
766                boxes.append(data)
767                masks.append(None)
768
769            elif type_ == "ellipse":
770                boxes.append(data)
771                center = np.mean(data, axis=0)
772                radius_r = ((data[2] - data[1]) / 2)[0]
773                radius_c = ((data[1] - data[0]) / 2)[1]
774                rr, cc = draw.ellipse(center[0], center[1], radius_r, radius_c, shape=shape)
775                mask = np.zeros(shape, dtype=bool)
776                mask[rr, cc] = 1
777                masks.append(mask)
778
779            elif type_ == "polygon":
780                boxes.append(data)
781                rr, cc = draw.polygon(data[:, 0], data[:, 1], shape=shape)
782                mask = np.zeros(shape, dtype=bool)
783                mask[rr, cc] = 1
784                masks.append(mask)
785
786            elif type_ in SCRIBBLE_SHAPE_TYPES:
787                continue
788
789            else:
790                warnings.warn(f"Shape type {type_} is not supported and will be ignored.")
791
792        # map to correct box format
793        boxes = [
794            np.array([box[:, 0].min(), box[:, 1].min(), box[:, 0].max(), box[:, 1].max()]) for box in boxes
795        ]
796        return boxes, masks
797
798    shape_data, shape_types = layer.data, layer.shape_type
799    assert len(shape_data) == len(shape_types)
800    if len(shape_data) == 0:
801        return [], []
802
803    if i is not None:
804        if track_id is None:
805            prompt_selection = [j for j, data in enumerate(shape_data) if (data[:, 0] == i).all()]
806        else:
807            track_ids = np.array(list(map(int, layer.properties["track_id"])))
808            prompt_selection = [
809                j for j, (data, this_track_id) in enumerate(zip(shape_data, track_ids))
810                if ((data[:, 0] == i).all() and this_track_id == track_id)
811            ]
812
813        shape_data = [shape_data[j][:, 1:] for j in prompt_selection]
814        shape_types = [shape_types[j] for j in prompt_selection]
815
816    boxes, masks = _to_prompts(shape_data, shape_types)
817    return boxes, masks

Extract prompts for SAM from a napari shape layer.

Extracts the bounding box for 'rectangle' shapes and the bounding box and corresponding mask for 'ellipse' and 'polygon' shapes.

Arguments:
  • prompt_layer: The napari shape layer.
  • shape: The image shape.
  • i: Index for the data (required for 3d or timeseries data).
  • track_id: Id of the current track (required for tracking data).
Returns:

The box prompts. The mask prompts.