micro_sam.v2.evaluation.inference

  1import os
  2import shutil
  3import warnings
  4from pathlib import Path
  5from typing import Union, Optional, List, Tuple
  6
  7import numpy as np
  8from tqdm import tqdm
  9import imageio.v3 as imageio
 10from sam2.automatic_mask_generator import SAM2AutomaticMaskGenerator
 11
 12import torch
 13
 14from elf.io import open_file
 15
 16from torch_em.util.segmentation import size_filter
 17
 18from bioimage_cpp.segmentation import label as connected_components
 19
 20from micro_sam.v2.normalization import to_image
 21from micro_sam.util import segmentation_to_one_hot, mask_data_to_segmentation
 22from micro_sam.prompt_generators import CenterIterativePromptGenerator, IterativePromptGenerator
 23from micro_sam.v1.evaluation.inference import (
 24    _get_batched_prompts, _get_batched_iterative_prompts, _save_segmentation,
 25)
 26from micro_sam.v2.util import (
 27    _get_device, configure_image_predictor, encode_image, get_sam2_image_predictor, get_sam2_model,
 28    precompute_image_embeddings,
 29)
 30
 31
 32def _embedding_tensors_to_numpy(embeddings):
 33    """Move SAM2 video embeddings to CPU arrays for CustomVideoPredictor.init_state."""
 34    def _convert(value):
 35        if hasattr(value, "detach"):
 36            return value.detach().cpu().numpy()
 37        if isinstance(value, list):
 38            return [_convert(v) for v in value]
 39        if isinstance(value, tuple):
 40            return tuple(_convert(v) for v in value)
 41        if isinstance(value, dict):
 42            return {k: _convert(v) for k, v in value.items()}
 43        return value
 44
 45    return _convert(embeddings)
 46
 47
 48#
 49# Automatic Mask Generation (AMG) for Images
 50#
 51
 52
 53def run_amg(
 54    image_paths: List[Union[os.PathLike, str]],
 55    image_key: Optional[str],
 56    experiment_folder: Union[os.PathLike, str],
 57    model_type: str,
 58    checkpoint_path: Union[os.PathLike, str],
 59    device: Optional[Union[torch.device, str]] = None,
 60    min_object_size: int = 0,
 61    ensure_8bit: bool = True,
 62):
 63    """Run automatic mask generation (AMG) of SAM2 on 2d images and save the segmentations.
 64
 65    The function saves one tif file per image in '<experiment_folder>/amg/inference'. It skips images
 66    that are already segmented.
 67
 68    Args:
 69        image_paths: The paths of the images.
 70        image_key: The key of the image data in container files, e.g. hdf5 or zarr. None for image files, e.g. tif.
 71        experiment_folder: The folder where the segmentations are saved.
 72        model_type: The SAM2 model, e.g. 'hvit_t_cells'.
 73        checkpoint_path: Optional path of the model weights. By default the weights of `model_type` are used.
 74        device: The torch device. By default the best available device is used.
 75        min_object_size: The minimum size of objects in pixels. Smaller objects are removed.
 76        ensure_8bit: Whether to normalize the images to 8 bit, as in training. Otherwise only grayscale
 77            images are converted to RGB.
 78
 79    Returns:
 80        The folder of the segmentations.
 81    """
 82    # where the predictions are saved
 83    prediction_dir = os.path.join(experiment_folder, "amg", "inference")
 84    os.makedirs(prediction_dir, exist_ok=True)
 85
 86    for image_path in tqdm(image_paths, desc="Run inference for automatic mask generation"):
 87        image_name = Path(os.path.basename(image_path)).with_suffix(".tif")
 88
 89        # We skip the images that are already segmented.
 90        prediction_path = os.path.join(prediction_dir, image_name)
 91        if os.path.exists(prediction_path):
 92            continue
 93
 94        if image_key is None:
 95            image = imageio.imread(image_path)
 96        else:
 97            image = open_file(image_path)[image_key][:]
 98
 99        if ensure_8bit:
100            image = to_image(image)
101        elif image.ndim == 2:  # Convert single channel images to RGB images.
102            image = np.stack([image] * 3, axis=-1)
103
104        model = get_sam2_model(model_type=model_type, device=device, checkpoint_path=checkpoint_path)
105
106        mask_generator = SAM2AutomaticMaskGenerator(
107            model=model,
108            pred_iou_thresh=0.6,  # default: 0.8
109            stability_score_thresh=0.6,  # default: 0.95
110        )
111        configure_image_predictor(mask_generator.predictor)
112
113        outputs = mask_generator.generate(image.astype("uint8"))  # NOTE: Done as this is what SAM2 expects as inputs.
114
115        if len(outputs) == 0:  # i.e. no segmentations were found.
116            segmentation = np.zeros(image.shape[:2], dtype="uint32")
117        else:
118            segmentation = mask_data_to_segmentation(
119                masks=outputs, with_background=True, min_object_size=min_object_size
120            )
121
122        imageio.imwrite(prediction_path, segmentation, compression=5)
123
124    return prediction_dir
125
126
127#
128# Interactive Segmentation for Images
129#
130
131
132@torch.no_grad()
133def _run_interactive_segmentation_2d_per_image(
134    image: np.ndarray,
135    gt: np.ndarray,
136    prediction_paths: Union[os.PathLike, str],
137    predictor,
138    start_with_box_prompt: bool = False,
139    dilation: int = 5,
140    device: Optional[Union[torch.device, str]] = None,
141    n_iterations: int = 8,
142    use_masks: bool = False,
143    batch_size: int = 32,
144    mask_threshold: float = 0.0,
145    seed: int = 0,
146    click_protocol: str = "random",
147) -> None:
148    """Functionality for interactive segmentation per 2d image.
149    """
150    if click_protocol not in ("random", "center"):
151        raise ValueError(f"Invalid click protocol '{click_protocol}', choose 'random' or 'center'.")
152    device = _get_device(device)
153
154    # The prompt generators sample from the global numpy RNG. Seeding it per image makes the clicks,
155    # and with them the results, independent of the image order, the sharding and any resumption.
156    np.random.seed(seed)
157
158    # Let's define the iterative prompt generator.
159    prompt_generator = CenterIterativePromptGenerator() if click_protocol == "center" else IterativePromptGenerator()
160
161    # Preparing prompts for the first iteration: use multimasking only if we have a single positive prompt without box
162    if start_with_box_prompt:
163        use_boxes, use_points = True, False
164        n_positive = 0
165        multimasking = False
166    else:
167        use_boxes, use_points = False, True
168        n_positive = 1
169        multimasking = click_protocol == "random"
170
171    # Expects RGB-style images.
172    encode_image(predictor, image.astype("uint8"))  # uint8 is what SAM2 expects as input.
173
174    gt_ids = np.setdiff1d(np.unique(gt), [0])
175
176    points, point_labels, boxes = _get_batched_prompts(
177        gt=gt,
178        gt_ids=gt_ids,
179        use_points=use_points,
180        use_boxes=use_boxes,
181        n_positives=n_positive,
182        n_negatives=0,
183        dilation=dilation,
184    )
185
186    # The prompt generator scans the full masks per object, which is ~7x faster on the GPU.
187    sampled_binary_y = segmentation_to_one_hot(segmentation=gt.astype("int64"), segmentation_ids=gt_ids).to(device)
188
189    for iteration in range(n_iterations):
190        if iteration == 0:  # logits masks cannot be used for the first iteration.
191            logits_masks = None
192        else:
193            if not use_masks:  # logits masks should not be used when not desired.
194                logits_masks = None
195
196        # scripts for batched inference
197        # TODO: we move this in a separate script the same as micro-sam
198        n_prompts = boxes.shape[0] if use_boxes else points.shape[0]
199        n_batches = int(np.ceil(float(n_prompts) / batch_size))
200
201        masks, logits = [], []
202        for batch_idx in range(n_batches):
203            batch_start = batch_idx * batch_size
204            batch_stop = min((batch_idx + 1) * batch_size, n_prompts)
205
206            batch_boxes = boxes[batch_start: batch_stop] if use_boxes else None
207            batch_points = points[batch_start: batch_stop] if (use_points or points is not None) else None
208            batch_point_labels = point_labels[batch_start: batch_stop] if (use_points or point_labels is not None) \
209                else None
210            batch_logits_masks = logits_masks[batch_start: batch_stop] if use_masks and logits_masks is not None \
211                else None
212
213            batch_masks, batch_scores, batch_logits = predictor.predict(
214                point_coords=batch_points,
215                point_labels=batch_point_labels,
216                box=batch_boxes,
217                mask_input=batch_logits_masks,
218                multimask_output=multimasking,
219                return_logits=True,
220            )
221
222            if batch_scores.ndim == 2:
223                max_index = batch_scores.argmax(axis=1)
224            elif batch_scores.ndim == 1:
225                max_index = batch_scores.argmax()
226                max_index = np.array([max_index])
227                batch_masks, batch_logits = batch_masks[None], batch_logits[None]
228            else:
229                raise ValueError
230
231            if multimasking:
232                batch_masks = np.stack([batch_masks[i, max_id][None] for i, max_id in enumerate(max_index)])
233                batch_logits = np.stack([batch_logits[i, max_id][None] for i, max_id in enumerate(max_index)])
234
235            masks.append(batch_masks)
236            logits.append(batch_logits)
237
238        # 'masks' holds logits so far, since a threshold above the SAM2 default of 0 counteracts
239        # the over-segmentation that the mask feedback otherwise compounds across iterations.
240        masks = np.concatenate(masks) > mask_threshold
241        logits_masks = np.concatenate(logits)
242
243        # switching off multimasking after first iter, as next iters (with multiple prompts) don't expect multimasking
244        multimasking = False
245
246        next_coords, next_labels = _get_batched_iterative_prompts(
247            sampled_binary_gt=sampled_binary_y,
248            masks=torch.from_numpy(masks).to(device=device, dtype=torch.float32),
249            batch_size=batch_size,
250            prompt_generator=prompt_generator
251        )
252        next_coords, next_labels = next_coords.detach().cpu().numpy(), next_labels.detach().cpu().numpy()
253
254        if points is not None:
255            points = np.concatenate([points, next_coords], axis=1)
256        else:
257            points = next_coords
258
259        if point_labels is not None:
260            point_labels = np.concatenate([point_labels, next_labels], axis=1)
261        else:
262            point_labels = next_labels
263
264        _save_segmentation(masks=torch.from_numpy(masks), prediction_path=prediction_paths[iteration])
265
266
267def get_prediction_dir_2d(
268    prediction_dir: Union[os.PathLike, str], start_with_box_prompt: bool, use_masks: bool
269) -> str:
270    """Return the folder that `run_interactive_segmentation_2d` writes its 'iterationNN' folders to.
271
272    Args:
273        prediction_dir: The root folder of the predictions.
274        start_with_box_prompt: Whether the iterative prompting starts with a box prompt.
275        use_masks: Whether the iterative prompting uses the mask logits of the previous iteration.
276
277    Returns:
278        The folder of the predictions.
279    """
280    box_or_pt = "start_with_box" if start_with_box_prompt else "start_with_point"
281    return os.path.join(prediction_dir, box_or_pt, "with_masks" if use_masks else "without_masks")
282
283
284def run_interactive_segmentation_2d(
285    image_paths: List[Union[os.PathLike, str]],
286    gt_paths: List[Union[os.PathLike, str]],
287    image_key: Optional[str],
288    gt_key: Optional[str],
289    prediction_dir: Union[os.PathLike, str],
290    model_type: str,
291    checkpoint_path: Union[os.PathLike, str],
292    start_with_box_prompt: bool = False,
293    device: Optional[Union[torch.device, str]] = None,
294    n_iterations: int = 8,
295    dilation: int = 5,
296    batch_size: int = 32,
297    use_masks: bool = True,
298    ensure_8bit: bool = True,
299    mask_threshold: float = 0.0,
300    seed: int = 0,
301    click_protocol: str = "random",
302):
303    """Functionality for interactive segmentation in 2d images using iterative prompting.
304
305    `use_masks` defaults to True because SAM2 is trained with the previous mask logits alongside every
306    correction click, see 'SAM2Train._iter_correct_pt_sampling'. Without them the predictions degrade
307    with each iteration. `seed` seeds the prompt sampling of every image.
308
309    `click_protocol` chooses the correction clicks: 'random' samples them at random positions in the
310    error regions and picks the best of 3 masks for a first point prompt. 'center' places them at the
311    centers of the largest error regions and predicts a single mask for a first point prompt.
312
313    Args:
314        image_paths: The paths of the images.
315        gt_paths: The paths of the ground-truth instance segmentations, in the same order as `image_paths`.
316        image_key: The key of the image data in container files, e.g. hdf5 or zarr. None for image files, e.g. tif.
317        gt_key: The key of the ground-truth data in container files. None for image files.
318        prediction_dir: The root folder of the predictions, see `get_prediction_dir_2d`.
319        model_type: The SAM2 model, e.g. 'hvit_t_cells'.
320        checkpoint_path: Optional path of the model weights. By default the weights of `model_type` are used.
321        start_with_box_prompt: Whether the iterative prompting starts with a box prompt. Otherwise it starts
322            with a point prompt.
323        device: The torch device. By default the best available device is used.
324        n_iterations: The number of iterations for iterative prompting.
325        dilation: The dilation factor for the radius around the ground-truth object around which
326            points will not be sampled.
327        batch_size: The number of objects that are segmented together.
328        use_masks: Whether to use the mask logits of the previous iteration as a prompt.
329        ensure_8bit: Whether to normalize the images to 8 bit, as in training. Otherwise only grayscale
330            images are converted to RGB.
331        mask_threshold: The threshold for the mask logits.
332        seed: The seed of the prompt sampling of every image.
333        click_protocol: The correction clicks, 'random' or 'center', see above.
334
335    Returns:
336        The folder of the predictions. It holds one subfolder per iteration: 'iteration00', 'iteration01' and so on.
337    """
338    if len(image_paths) != len(gt_paths):
339        raise ValueError(f"Expect same number of images and gt images, got {len(image_paths)}, {len(gt_paths)}")
340
341    # create all prediction folders for all intermediate iterations'
342    prediction_dir = get_prediction_dir_2d(prediction_dir, start_with_box_prompt, use_masks)
343    if use_masks:
344        print("The iterative prompting will make use of logits masks from previous iterations.")
345
346    for i in range(n_iterations):
347        os.makedirs(os.path.join(prediction_dir, f"iteration{i:02}"), exist_ok=True)
348
349    model = get_sam2_model(model_type=model_type, device=device, checkpoint_path=checkpoint_path)
350    predictor = get_sam2_image_predictor(model)
351
352    for image_path, gt_path in tqdm(
353        zip(image_paths, gt_paths), total=len(image_paths), desc="Run inference with iterative prompting",
354    ):
355        assert os.path.exists(image_path), image_path
356        assert os.path.exists(gt_path), gt_path
357
358        image_name = Path(os.path.basename(image_path)).with_suffix(".tif")
359
360        # We skip the images that have already been segmented
361        prediction_paths = [os.path.join(prediction_dir, f"iteration{i:02}", image_name) for i in range(n_iterations)]
362        if all(os.path.exists(prediction_path) for prediction_path in prediction_paths):
363            continue
364
365        if image_key is None:
366            image = imageio.imread(image_path)
367        else:
368            image = open_file(image_path)[image_key][:]
369
370        if ensure_8bit:
371            image = to_image(image)
372        elif image.ndim == 2:
373            image = np.stack([image] * 3, axis=-1)
374
375        if gt_key is None:
376            gt = imageio.imread(gt_path)
377        else:
378            gt = open_file(gt_path)[gt_key][:]
379
380        # Run connected components on labels
381        gt = connected_components(gt).astype("uint32")
382
383        # Skip the image if it has no labels. An image that one object covers has no background, but it
384        # still has a label to prompt.
385        if gt.max() == 0:
386            continue
387
388        _run_interactive_segmentation_2d_per_image(
389            image=image,
390            gt=gt,
391            prediction_paths=prediction_paths,
392            predictor=predictor,
393            start_with_box_prompt=start_with_box_prompt,
394            device=device,
395            dilation=dilation,
396            n_iterations=n_iterations,
397            use_masks=use_masks,
398            batch_size=batch_size,
399            mask_threshold=mask_threshold,
400            seed=seed,
401            click_protocol=click_protocol,
402        )
403
404    return prediction_dir
405
406
407#
408# Interactive Segmentation for Multi-Dimensional Inputs
409#
410
411
412def _convert_volumes_to_frames(raw, frames_dir):
413    """Converts whole volumes to individual frames and stores them sequentially in a directory.
414    """
415    # Let's convert the inputs to individual slices as tifs and pair them with it's respective labels
416    if os.path.exists(frames_dir):  # We remove the previously stored frames.
417        shutil.rmtree(frames_dir)
418
419    image_dir = os.path.join(frames_dir, "images")  # Store slices in the directory.
420    os.makedirs(image_dir, exist_ok=True)
421
422    # Save all slices in order.
423    [imageio.imwrite(os.path.join(image_dir, f"{i:04}.tif"), fraw) for i, fraw in enumerate(raw)]
424
425    return image_dir
426
427
428def get_prediction_paths_3d(
429    prediction_dir: Union[os.PathLike, str], prediction_fname: str, start_with_box_prompt: bool, n_iterations: int,
430) -> Tuple[str, List[str]]:
431    """Return the folder and the per-iteration files that `run_interactive_segmentation_3d` writes.
432
433    Args:
434        prediction_dir: The root folder of the predictions.
435        prediction_fname: The name of the segmentation file.
436        start_with_box_prompt: Whether the iterative prompting starts with a box prompt.
437        n_iterations: The number of iterations for iterative prompting.
438
439    Returns:
440        The folder of the predictions and the path of the segmentation for each iteration.
441    """
442    box_or_pt = "start_with_box" if start_with_box_prompt else "start_with_point"
443    prediction_dir = os.path.join(prediction_dir, "interactive_segmentation_3d", box_or_pt, "without_masks")
444    fname = Path(prediction_fname).with_suffix(".tif")
445    return prediction_dir, [os.path.join(prediction_dir, f"iteration{i}", fname) for i in range(n_iterations)]
446
447
448def run_interactive_segmentation_3d(
449    raw: np.ndarray,
450    labels: np.ndarray,
451    model_type: str,
452    checkpoint_path: Union[os.PathLike, str],
453    start_with_box_prompt: bool,
454    prediction_dir: Union[os.PathLike, str],
455    prediction_fname: str = "segmentation",
456    dilation: int = 5,
457    device: Optional[Union[torch.device, str]] = None,
458    first_prompt_at_center: bool = True,  # NOTE: With our current schema, we always put the first prompt in center.
459    min_size: int = 0,
460    batch_size: int = 16,
461    n_iterations: int = 8,
462    run_connected_components: bool = True,
463    seed: int = 0,
464    correction_margin: float = 0.0,
465    click_protocol: str = "random",
466) -> str:
467    """Run interactive segmentation on 3d inputs using Segment Anything 2.
468
469    Args:
470        raw: The raw input array.
471        labels: The corresponding ground-truth array with instance labels.
472        model_type: The choice of Segment Anything 2 model.
473        checkpoint_path: The filepath to the model checkpoints.
474        start_with_box_prompt: Whether the iterative prompting starts with 'box' as first prompt
475            (else 'points' will be used).
476        prediction_dir: The filepath where the predictions will be stored.
477        prediction_fname: The name for storing the segmentations.
478        dilation: The dilation factor for the radius around the ground-truth object around which
479            points will not be sampled.
480        device: The torch device.
481        first_prompt_at_center: Whether to place the first prompt at center.
482        min_size: The minimum pixel criterion to accept instance objects for interactive segmentation.
483        batch_size: The batch size to compute prompts.
484        n_iterations: The number of iterations for iterative prompting.
485        run_connected_components: Whether to ensure individual instances and filter out small objects.
486        seed: The seed of the prompt sampling of the volume.
487        correction_margin: The fraction of each object's z-extent at either end that is excluded when the slice
488            for the next correction click is chosen. 0 chooses among all slices of the object.
489        click_protocol: The correction clicks on the worst slice of an object: 'random' samples them at random
490            positions in the error regions, 'center' places them at the centers of the largest error regions.
491
492    Returns:
493        The folder where segmentations are stored.
494    """
495    prediction_dir, prediction_paths = get_prediction_paths_3d(
496        prediction_dir, prediction_fname, start_with_box_prompt, n_iterations
497    )
498    if all([os.path.exists(_path) for _path in prediction_paths]):
499        cached = imageio.imread(prediction_paths[0])
500        if cached.shape == labels.shape:
501            print(f"The results are stored at '{prediction_dir}'.")
502            return prediction_dir
503        warnings.warn(
504            f"Stale cache: '{prediction_paths[0]}' has shape {cached.shape} "
505            f"but labels have shape {labels.shape}. Deleting and recomputing."
506        )
507        for path in prediction_paths:
508            if os.path.exists(path):
509                os.remove(path)
510
511    # Get the device.
512    device = _get_device(device)
513
514    if run_connected_components:
515        # Ensuring sequential instance labels.
516        labels = connected_components(labels).astype(labels.dtype)
517        # NOTE: There are some objects covering very few pixels, eg. in lucchi, causing troubles in iterative prompting.
518        labels = size_filter(seg=labels, min_size=min_size)
519
520    # Preparing prompts for the first iteration
521    if start_with_box_prompt:
522        use_boxes, use_points = True, False
523        n_positive = 0
524    else:
525        use_boxes, use_points = False, True
526        n_positive = 1
527
528    # Get the SAM2 predictor.
529    predictor = get_sam2_model(
530        model_type=model_type, device=device, checkpoint_path=checkpoint_path, input_type="videos",
531    )
532    # Match training: frames that receive correction clicks become conditioning frames so
533    # their corrected predictions are preserved and used as memory for neighboring frames.
534    predictor.add_all_frames_to_correct_as_cond = True
535
536    # Initialize the inference state
537    volume_embeddings = _embedding_tensors_to_numpy(
538        precompute_image_embeddings(predictor=predictor, input_=raw, ndim=3)
539    )
540    inference_state = predictor.init_state(volume=raw, volume_embeddings=volume_embeddings)
541
542    # The prompt generators sample from the global numpy RNG. Seeding it per volume makes the clicks,
543    # and with them the results, reproducible.
544    np.random.seed(seed)
545
546    gt_ids = list(np.setdiff1d(np.unique(labels), [0]))  # Ignoring the background label
547    # An empty volume has nothing to prompt, so all iterations stay empty.
548    segmentation = [np.zeros(labels.shape, dtype="uint64") for _ in range(n_iterations)]
549    # The area of the object that holds each label, per iteration, to resolve overlaps.
550    areas = [np.full(int(max(gt_ids, default=0)) + 1, np.inf) for _ in range(n_iterations)]
551    for gt_id in tqdm(gt_ids, desc="Segmenting per object in the volume"):
552        _per_iter_segmentation = _run_interactive_segmentation_3d_per_object(
553            gt_ids=gt_id,
554            labels=labels,
555            predictor=predictor,
556            inference_state=inference_state,
557            first_prompt_at_center=first_prompt_at_center,
558            use_points=use_points,
559            use_boxes=use_boxes,
560            n_positive=n_positive,
561            dilation=dilation,
562            batch_size=batch_size,
563            n_iterations=n_iterations,
564            correction_margin=correction_margin,
565            click_protocol=click_protocol,
566        )
567
568        # Merge the incoming object. Where objects overlap, the smaller one is kept, as in the 2d
569        # evaluation (see 'mask_data_to_segmentation'). Adding the labels would turn an overlap into the
570        # sum of both ids, i.e. into a third object.
571        for _iter in range(n_iterations):
572            mask = _per_iter_segmentation[_iter] > 0
573            area = mask.sum()
574            existing = segmentation[_iter][mask]
575            segmentation[_iter][mask] = np.where(areas[_iter][existing] > area, gt_id, existing)
576            areas[_iter][gt_id] = area
577
578    # Each file is written under a temporary name and then renamed, so a job killed during the write
579    # leaves no truncated file that a rerun would accept as complete.
580    for i, prediction_path in enumerate(prediction_paths):
581        os.makedirs(Path(prediction_path).parent, exist_ok=True)
582        partial_path = Path(prediction_path).with_suffix(".partial.tif")
583        imageio.imwrite(partial_path, segmentation[i], compression="zlib")
584        os.replace(partial_path, prediction_path)
585
586    return prediction_dir
587
588
589@torch.no_grad()
590def _run_interactive_segmentation_3d_per_object(
591    gt_ids: Union[List[int], int],
592    labels: np.ndarray,
593    predictor,
594    inference_state,
595    first_prompt_at_center: bool,
596    use_points: bool,
597    use_boxes: bool,
598    n_positive: int,
599    dilation: int = 5,
600    batch_size: int = 32,
601    n_iterations: int = 8,
602    correction_margin: float = 0.0,
603    click_protocol: str = "random",
604):
605    """Functionality for interactive segmentation using iterative prompting.
606    """
607    if not isinstance(gt_ids, list):
608        gt_ids = [gt_ids]
609
610    # Get prompts for the desired frame and desired object id for the first iteration.
611    id_to_prompts = _extract_prompts_per_object(
612        labels=labels,
613        gt_ids=gt_ids,
614        first_prompt_at_center=first_prompt_at_center,
615        use_points=use_points,
616        use_boxes=use_boxes,
617        n_positive=n_positive,
618        dilation=dilation,
619    )
620
621    # Get segmentation for iterative prompting per object.
622    preds_per_object = _get_iteratively_prompted_segmentation_per_image_dir(
623        inference_state=inference_state,
624        labels=labels,
625        id_to_prompts=id_to_prompts,
626        predictor=predictor,
627        batch_size=batch_size,
628        n_iterations=n_iterations,
629        correction_margin=correction_margin,
630        click_protocol=click_protocol,
631    )
632
633    assert len(gt_ids) == len(preds_per_object), "The number of label ids must match the number of objects segmented."
634
635    seg_per_iterations = []
636    for gt_id, _preds_per_iters in zip(gt_ids, preds_per_object):  # Access interactive segmentation per object.
637        assert len(_preds_per_iters) == n_iterations
638
639        for _iter in range(n_iterations):  # Acces per-object per-iteration predictions.
640            _pred_per_iter = _preds_per_iters[_iter]
641            assert isinstance(_pred_per_iter, np.ndarray)
642
643            # Replace the id of foreground with the expect object id
644            _pred_per_iter[_pred_per_iter > 0] = gt_id
645
646            # Let's merge the prediction per iteration at label id.
647            if gt_id == gt_ids[0]:  # If the array is not a part of the list.
648                seg_per_iterations.append(_pred_per_iter)
649            else:  # If this is a existing array, we merge the incoming labels
650                seg_per_iterations[_iter] += _pred_per_iter
651
652    for seg in seg_per_iterations:
653        if seg.shape != labels.shape:
654            raise AssertionError(f"'{seg.shape}' not equal to the expect shape: '{labels.shape}'")
655
656    return seg_per_iterations
657
658
659def _extract_prompts_per_object(
660    labels, gt_ids, first_prompt_at_center, use_points, use_boxes, n_positive, dilation,
661):
662    """Extracts input prompts per object for interactive segmentation.
663    """
664    ids_to_prompts = {}
665    for gt_id in gt_ids:
666        # The first thing to do is find where all the objects start from and end to
667        z_slices = np.where(labels == gt_id)[0]
668        z_range = (z_slices.min(), z_slices.max())
669
670        if first_prompt_at_center:  # choose the middle slice of the object
671            z_choice = int(np.ceil(np.mean(z_range)))
672        else:  # choose the first slice of the object
673            z_choice = z_range[0]
674
675        points, point_labels, boxes = _get_batched_prompts(
676            gt=(labels[z_choice] == gt_id).astype("uint32"),  # binary label of the particular slice per object
677            gt_ids=[1],  # see above line: binary labels per object
678            use_points=use_points, use_boxes=use_boxes, n_positives=n_positive, n_negatives=0, dilation=dilation,
679        )
680        ids_to_prompts[gt_id] = [z_choice, points, point_labels, boxes]
681
682    return ids_to_prompts
683
684
685@torch.no_grad()
686def _get_iteratively_prompted_segmentation_per_image_dir(
687    inference_state, labels, id_to_prompts, predictor, batch_size=32, n_iterations=8, correction_margin=0.0,
688    click_protocol="random",
689):
690    """Functionality for inference of 3d interactive segmentation.
691    """
692    # Let's define the iterative prompt generator.
693    if click_protocol not in ("random", "center"):
694        raise ValueError(f"Invalid click protocol '{click_protocol}', choose 'random' or 'center'.")
695    prompt_generator = CenterIterativePromptGenerator() if click_protocol == "center" else IterativePromptGenerator()
696
697    pred_per_object = []
698    for _obj_id, _input_prompts in id_to_prompts.items():
699        z_cond, _point, _label, _box = _input_prompts  # z_cond stays fixed for all iterations
700
701        list_of_iterations = list(range(n_iterations))
702        pred_per_iteration = []
703        _corr_points = None  # (x,y) correction points for the next iteration
704        _corr_labels = None
705        _corr_frame = None  # z-slice where corrections will be applied
706
707        for iteration in list_of_iterations:
708            if iteration == 0:
709                # First iteration: initial box or point at the conditioning frame.
710                _, out_obj_ids, out_mask_logits = predictor.add_new_points_or_box(
711                    inference_state=inference_state, frame_idx=z_cond, obj_id=_obj_id,
712                    points=_point, labels=_label, box=_box,
713                )
714            else:
715                # Subsequent iterations: add corrective points at the worst-predicted frame.
716                # The video predictor automatically loads prev_sam_mask_logits from the
717                # previous propagation at that frame, matching the mask_inputs feedback used
718                # during training (SAM2Train._iter_correct_pt_sampling, line 492).
719                for per_point, per_label in zip(_corr_points, _corr_labels):
720                    # The 'center' clicks pad a missing error type with the label -1.
721                    if per_label < 0:
722                        continue
723                    _, out_obj_ids, out_mask_logits = predictor.add_new_points_or_box(
724                        inference_state=inference_state, frame_idx=_corr_frame, obj_id=_obj_id,
725                        points=np.array([per_point]), labels=np.array([per_label]),
726                        box=None, clear_old_points=False,
727                    )
728
729            # Propagate the masklets throughout the frames using the input prompts in selected frames
730            forward_video_segments = {}
731            for out_frame_idx, out_obj_ids, out_mask_logits in predictor.propagate_in_video(inference_state):
732                forward_video_segments[out_frame_idx] = {
733                    out_obj_id: (out_mask_logits[i] > 0.0).cpu().numpy() for i, out_obj_id in enumerate(out_obj_ids)
734                }
735
736            # Propagate reverse in time if needed.
737            reverse_video_segments = {}
738            if len(forward_video_segments) < labels.shape[0]:
739                for out_frame_idx, out_obj_ids, out_mask_logits in predictor.propagate_in_video(
740                    inference_state, reverse=True,
741                ):
742                    reverse_video_segments[out_frame_idx] = {
743                        out_obj_id: (out_mask_logits[i] > 0.0).cpu().numpy() for i, out_obj_id in enumerate(out_obj_ids)
744                    }
745                reverse_video_segments = dict(reversed(list(reverse_video_segments.items())))
746
747            video_segments = {**reverse_video_segments, **forward_video_segments}
748
749            height, width = labels.shape[-2:]
750            segmentation = []
751            for slice_idx in video_segments.keys():
752                per_slice_seg = np.zeros((height, width))
753                for _instance_idx, _instance_mask in video_segments[slice_idx].items():
754                    # Non-square frames are padded to a square, see '_load_frame_as_tensor'.
755                    per_slice_seg[_instance_mask.squeeze()[:height, :width]] = _instance_idx
756                segmentation.append(per_slice_seg)
757
758            segmentation = (np.stack(segmentation) > 0).astype("uint64")
759            pred_per_iteration.append(segmentation)
760
761            if len(list_of_iterations) > 1 and iteration < list_of_iterations[-1]:
762                # Find the z-slice where the prediction is worst for this object.
763                # Restrict to slices where the object exists so IterativePromptGenerator
764                # always has FN pixels (or overlap) to sample a positive point from.
765                gt_3d = (labels == _obj_id)
766                obj_z_slices = np.where(gt_3d.any(axis=(1, 2)))[0]
767                if correction_margin > 0:
768                    # A correction on an end slice of the object turns its small cross-section into a
769                    # conditioning frame, which degrades the other slices of the object.
770                    margin = correction_margin * (obj_z_slices.max() - obj_z_slices.min())
771                    inner = obj_z_slices[
772                        (obj_z_slices >= obj_z_slices.min() + margin) & (obj_z_slices <= obj_z_slices.max() - margin)
773                    ]
774                    obj_z_slices = inner if len(inner) else obj_z_slices
775                errors_per_slice = np.array([
776                    np.sum(gt_3d[z] != (segmentation[z] > 0)) for z in obj_z_slices
777                ])
778                z_worst = int(obj_z_slices[np.argmax(errors_per_slice)])
779
780                gt_slice = gt_3d[z_worst].astype("int64")
781                pred_slice = (segmentation[z_worst] > 0).astype("int64")
782                next_coords, next_labels = _get_batched_iterative_prompts(
783                    sampled_binary_gt=torch.from_numpy(gt_slice)[None, None].to(torch.float32),
784                    masks=torch.from_numpy(pred_slice)[None, None].to(torch.float32),
785                    batch_size=batch_size,
786                    prompt_generator=prompt_generator,
787                )
788                next_coords = next_coords.detach().cpu().numpy()  # [1, 2, 2]: (obj, pos+neg, xy)
789                next_labels = next_labels.detach().cpu().numpy()  # [1, 2]
790                _corr_points = next_coords[0]  # [[x_pos, y_pos], [x_neg, y_neg]]
791                _corr_labels = next_labels[0]  # [1, 0]
792                _corr_frame = z_worst
793
794        pred_per_object.append(pred_per_iteration)
795
796        # Reset the state after tracking
797        predictor.reset_state(inference_state)
798
799    return pred_per_object
def run_amg( image_paths: List[Union[str, os.PathLike]], image_key: Optional[str], experiment_folder: Union[os.PathLike, str], model_type: str, checkpoint_path: Union[os.PathLike, str], device: Union[str, torch.device, NoneType] = None, min_object_size: int = 0, ensure_8bit: bool = True):
 54def run_amg(
 55    image_paths: List[Union[os.PathLike, str]],
 56    image_key: Optional[str],
 57    experiment_folder: Union[os.PathLike, str],
 58    model_type: str,
 59    checkpoint_path: Union[os.PathLike, str],
 60    device: Optional[Union[torch.device, str]] = None,
 61    min_object_size: int = 0,
 62    ensure_8bit: bool = True,
 63):
 64    """Run automatic mask generation (AMG) of SAM2 on 2d images and save the segmentations.
 65
 66    The function saves one tif file per image in '<experiment_folder>/amg/inference'. It skips images
 67    that are already segmented.
 68
 69    Args:
 70        image_paths: The paths of the images.
 71        image_key: The key of the image data in container files, e.g. hdf5 or zarr. None for image files, e.g. tif.
 72        experiment_folder: The folder where the segmentations are saved.
 73        model_type: The SAM2 model, e.g. 'hvit_t_cells'.
 74        checkpoint_path: Optional path of the model weights. By default the weights of `model_type` are used.
 75        device: The torch device. By default the best available device is used.
 76        min_object_size: The minimum size of objects in pixels. Smaller objects are removed.
 77        ensure_8bit: Whether to normalize the images to 8 bit, as in training. Otherwise only grayscale
 78            images are converted to RGB.
 79
 80    Returns:
 81        The folder of the segmentations.
 82    """
 83    # where the predictions are saved
 84    prediction_dir = os.path.join(experiment_folder, "amg", "inference")
 85    os.makedirs(prediction_dir, exist_ok=True)
 86
 87    for image_path in tqdm(image_paths, desc="Run inference for automatic mask generation"):
 88        image_name = Path(os.path.basename(image_path)).with_suffix(".tif")
 89
 90        # We skip the images that are already segmented.
 91        prediction_path = os.path.join(prediction_dir, image_name)
 92        if os.path.exists(prediction_path):
 93            continue
 94
 95        if image_key is None:
 96            image = imageio.imread(image_path)
 97        else:
 98            image = open_file(image_path)[image_key][:]
 99
100        if ensure_8bit:
101            image = to_image(image)
102        elif image.ndim == 2:  # Convert single channel images to RGB images.
103            image = np.stack([image] * 3, axis=-1)
104
105        model = get_sam2_model(model_type=model_type, device=device, checkpoint_path=checkpoint_path)
106
107        mask_generator = SAM2AutomaticMaskGenerator(
108            model=model,
109            pred_iou_thresh=0.6,  # default: 0.8
110            stability_score_thresh=0.6,  # default: 0.95
111        )
112        configure_image_predictor(mask_generator.predictor)
113
114        outputs = mask_generator.generate(image.astype("uint8"))  # NOTE: Done as this is what SAM2 expects as inputs.
115
116        if len(outputs) == 0:  # i.e. no segmentations were found.
117            segmentation = np.zeros(image.shape[:2], dtype="uint32")
118        else:
119            segmentation = mask_data_to_segmentation(
120                masks=outputs, with_background=True, min_object_size=min_object_size
121            )
122
123        imageio.imwrite(prediction_path, segmentation, compression=5)
124
125    return prediction_dir

Run automatic mask generation (AMG) of SAM2 on 2d images and save the segmentations.

The function saves one tif file per image in '/amg/inference'. It skips images that are already segmented.

Arguments:
  • image_paths: The paths of the images.
  • image_key: The key of the image data in container files, e.g. hdf5 or zarr. None for image files, e.g. tif.
  • experiment_folder: The folder where the segmentations are saved.
  • model_type: The SAM2 model, e.g. 'hvit_t_cells'.
  • checkpoint_path: Optional path of the model weights. By default the weights of model_type are used.
  • device: The torch device. By default the best available device is used.
  • min_object_size: The minimum size of objects in pixels. Smaller objects are removed.
  • ensure_8bit: Whether to normalize the images to 8 bit, as in training. Otherwise only grayscale images are converted to RGB.
Returns:

The folder of the segmentations.

def get_prediction_dir_2d( prediction_dir: Union[os.PathLike, str], start_with_box_prompt: bool, use_masks: bool) -> str:
268def get_prediction_dir_2d(
269    prediction_dir: Union[os.PathLike, str], start_with_box_prompt: bool, use_masks: bool
270) -> str:
271    """Return the folder that `run_interactive_segmentation_2d` writes its 'iterationNN' folders to.
272
273    Args:
274        prediction_dir: The root folder of the predictions.
275        start_with_box_prompt: Whether the iterative prompting starts with a box prompt.
276        use_masks: Whether the iterative prompting uses the mask logits of the previous iteration.
277
278    Returns:
279        The folder of the predictions.
280    """
281    box_or_pt = "start_with_box" if start_with_box_prompt else "start_with_point"
282    return os.path.join(prediction_dir, box_or_pt, "with_masks" if use_masks else "without_masks")

Return the folder that run_interactive_segmentation_2d writes its 'iterationNN' folders to.

Arguments:
  • prediction_dir: The root folder of the predictions.
  • start_with_box_prompt: Whether the iterative prompting starts with a box prompt.
  • use_masks: Whether the iterative prompting uses the mask logits of the previous iteration.
Returns:

The folder of the predictions.

def run_interactive_segmentation_2d( image_paths: List[Union[str, os.PathLike]], gt_paths: List[Union[str, os.PathLike]], image_key: Optional[str], gt_key: Optional[str], prediction_dir: Union[os.PathLike, str], model_type: str, checkpoint_path: Union[os.PathLike, str], start_with_box_prompt: bool = False, device: Union[str, torch.device, NoneType] = None, n_iterations: int = 8, dilation: int = 5, batch_size: int = 32, use_masks: bool = True, ensure_8bit: bool = True, mask_threshold: float = 0.0, seed: int = 0, click_protocol: str = 'random'):
285def run_interactive_segmentation_2d(
286    image_paths: List[Union[os.PathLike, str]],
287    gt_paths: List[Union[os.PathLike, str]],
288    image_key: Optional[str],
289    gt_key: Optional[str],
290    prediction_dir: Union[os.PathLike, str],
291    model_type: str,
292    checkpoint_path: Union[os.PathLike, str],
293    start_with_box_prompt: bool = False,
294    device: Optional[Union[torch.device, str]] = None,
295    n_iterations: int = 8,
296    dilation: int = 5,
297    batch_size: int = 32,
298    use_masks: bool = True,
299    ensure_8bit: bool = True,
300    mask_threshold: float = 0.0,
301    seed: int = 0,
302    click_protocol: str = "random",
303):
304    """Functionality for interactive segmentation in 2d images using iterative prompting.
305
306    `use_masks` defaults to True because SAM2 is trained with the previous mask logits alongside every
307    correction click, see 'SAM2Train._iter_correct_pt_sampling'. Without them the predictions degrade
308    with each iteration. `seed` seeds the prompt sampling of every image.
309
310    `click_protocol` chooses the correction clicks: 'random' samples them at random positions in the
311    error regions and picks the best of 3 masks for a first point prompt. 'center' places them at the
312    centers of the largest error regions and predicts a single mask for a first point prompt.
313
314    Args:
315        image_paths: The paths of the images.
316        gt_paths: The paths of the ground-truth instance segmentations, in the same order as `image_paths`.
317        image_key: The key of the image data in container files, e.g. hdf5 or zarr. None for image files, e.g. tif.
318        gt_key: The key of the ground-truth data in container files. None for image files.
319        prediction_dir: The root folder of the predictions, see `get_prediction_dir_2d`.
320        model_type: The SAM2 model, e.g. 'hvit_t_cells'.
321        checkpoint_path: Optional path of the model weights. By default the weights of `model_type` are used.
322        start_with_box_prompt: Whether the iterative prompting starts with a box prompt. Otherwise it starts
323            with a point prompt.
324        device: The torch device. By default the best available device is used.
325        n_iterations: The number of iterations for iterative prompting.
326        dilation: The dilation factor for the radius around the ground-truth object around which
327            points will not be sampled.
328        batch_size: The number of objects that are segmented together.
329        use_masks: Whether to use the mask logits of the previous iteration as a prompt.
330        ensure_8bit: Whether to normalize the images to 8 bit, as in training. Otherwise only grayscale
331            images are converted to RGB.
332        mask_threshold: The threshold for the mask logits.
333        seed: The seed of the prompt sampling of every image.
334        click_protocol: The correction clicks, 'random' or 'center', see above.
335
336    Returns:
337        The folder of the predictions. It holds one subfolder per iteration: 'iteration00', 'iteration01' and so on.
338    """
339    if len(image_paths) != len(gt_paths):
340        raise ValueError(f"Expect same number of images and gt images, got {len(image_paths)}, {len(gt_paths)}")
341
342    # create all prediction folders for all intermediate iterations'
343    prediction_dir = get_prediction_dir_2d(prediction_dir, start_with_box_prompt, use_masks)
344    if use_masks:
345        print("The iterative prompting will make use of logits masks from previous iterations.")
346
347    for i in range(n_iterations):
348        os.makedirs(os.path.join(prediction_dir, f"iteration{i:02}"), exist_ok=True)
349
350    model = get_sam2_model(model_type=model_type, device=device, checkpoint_path=checkpoint_path)
351    predictor = get_sam2_image_predictor(model)
352
353    for image_path, gt_path in tqdm(
354        zip(image_paths, gt_paths), total=len(image_paths), desc="Run inference with iterative prompting",
355    ):
356        assert os.path.exists(image_path), image_path
357        assert os.path.exists(gt_path), gt_path
358
359        image_name = Path(os.path.basename(image_path)).with_suffix(".tif")
360
361        # We skip the images that have already been segmented
362        prediction_paths = [os.path.join(prediction_dir, f"iteration{i:02}", image_name) for i in range(n_iterations)]
363        if all(os.path.exists(prediction_path) for prediction_path in prediction_paths):
364            continue
365
366        if image_key is None:
367            image = imageio.imread(image_path)
368        else:
369            image = open_file(image_path)[image_key][:]
370
371        if ensure_8bit:
372            image = to_image(image)
373        elif image.ndim == 2:
374            image = np.stack([image] * 3, axis=-1)
375
376        if gt_key is None:
377            gt = imageio.imread(gt_path)
378        else:
379            gt = open_file(gt_path)[gt_key][:]
380
381        # Run connected components on labels
382        gt = connected_components(gt).astype("uint32")
383
384        # Skip the image if it has no labels. An image that one object covers has no background, but it
385        # still has a label to prompt.
386        if gt.max() == 0:
387            continue
388
389        _run_interactive_segmentation_2d_per_image(
390            image=image,
391            gt=gt,
392            prediction_paths=prediction_paths,
393            predictor=predictor,
394            start_with_box_prompt=start_with_box_prompt,
395            device=device,
396            dilation=dilation,
397            n_iterations=n_iterations,
398            use_masks=use_masks,
399            batch_size=batch_size,
400            mask_threshold=mask_threshold,
401            seed=seed,
402            click_protocol=click_protocol,
403        )
404
405    return prediction_dir

Functionality for interactive segmentation in 2d images using iterative prompting.

use_masks defaults to True because SAM2 is trained with the previous mask logits alongside every correction click, see 'SAM2Train._iter_correct_pt_sampling'. Without them the predictions degrade with each iteration. seed seeds the prompt sampling of every image.

click_protocol chooses the correction clicks: 'random' samples them at random positions in the error regions and picks the best of 3 masks for a first point prompt. 'center' places them at the centers of the largest error regions and predicts a single mask for a first point prompt.

Arguments:
  • image_paths: The paths of the images.
  • gt_paths: The paths of the ground-truth instance segmentations, in the same order as image_paths.
  • image_key: The key of the image data in container files, e.g. hdf5 or zarr. None for image files, e.g. tif.
  • gt_key: The key of the ground-truth data in container files. None for image files.
  • prediction_dir: The root folder of the predictions, see get_prediction_dir_2d.
  • model_type: The SAM2 model, e.g. 'hvit_t_cells'.
  • checkpoint_path: Optional path of the model weights. By default the weights of model_type are used.
  • start_with_box_prompt: Whether the iterative prompting starts with a box prompt. Otherwise it starts with a point prompt.
  • device: The torch device. By default the best available device is used.
  • n_iterations: The number of iterations for iterative prompting.
  • dilation: The dilation factor for the radius around the ground-truth object around which points will not be sampled.
  • batch_size: The number of objects that are segmented together.
  • use_masks: Whether to use the mask logits of the previous iteration as a prompt.
  • ensure_8bit: Whether to normalize the images to 8 bit, as in training. Otherwise only grayscale images are converted to RGB.
  • mask_threshold: The threshold for the mask logits.
  • seed: The seed of the prompt sampling of every image.
  • click_protocol: The correction clicks, 'random' or 'center', see above.
Returns:

The folder of the predictions. It holds one subfolder per iteration: 'iteration00', 'iteration01' and so on.

def get_prediction_paths_3d( prediction_dir: Union[os.PathLike, str], prediction_fname: str, start_with_box_prompt: bool, n_iterations: int) -> Tuple[str, List[str]]:
429def get_prediction_paths_3d(
430    prediction_dir: Union[os.PathLike, str], prediction_fname: str, start_with_box_prompt: bool, n_iterations: int,
431) -> Tuple[str, List[str]]:
432    """Return the folder and the per-iteration files that `run_interactive_segmentation_3d` writes.
433
434    Args:
435        prediction_dir: The root folder of the predictions.
436        prediction_fname: The name of the segmentation file.
437        start_with_box_prompt: Whether the iterative prompting starts with a box prompt.
438        n_iterations: The number of iterations for iterative prompting.
439
440    Returns:
441        The folder of the predictions and the path of the segmentation for each iteration.
442    """
443    box_or_pt = "start_with_box" if start_with_box_prompt else "start_with_point"
444    prediction_dir = os.path.join(prediction_dir, "interactive_segmentation_3d", box_or_pt, "without_masks")
445    fname = Path(prediction_fname).with_suffix(".tif")
446    return prediction_dir, [os.path.join(prediction_dir, f"iteration{i}", fname) for i in range(n_iterations)]

Return the folder and the per-iteration files that run_interactive_segmentation_3d writes.

Arguments:
  • prediction_dir: The root folder of the predictions.
  • prediction_fname: The name of the segmentation file.
  • start_with_box_prompt: Whether the iterative prompting starts with a box prompt.
  • n_iterations: The number of iterations for iterative prompting.
Returns:

The folder of the predictions and the path of the segmentation for each iteration.

def run_interactive_segmentation_3d( raw: numpy.ndarray, labels: numpy.ndarray, model_type: str, checkpoint_path: Union[os.PathLike, str], start_with_box_prompt: bool, prediction_dir: Union[os.PathLike, str], prediction_fname: str = 'segmentation', dilation: int = 5, device: Union[str, torch.device, NoneType] = None, first_prompt_at_center: bool = True, min_size: int = 0, batch_size: int = 16, n_iterations: int = 8, run_connected_components: bool = True, seed: int = 0, correction_margin: float = 0.0, click_protocol: str = 'random') -> str:
449def run_interactive_segmentation_3d(
450    raw: np.ndarray,
451    labels: np.ndarray,
452    model_type: str,
453    checkpoint_path: Union[os.PathLike, str],
454    start_with_box_prompt: bool,
455    prediction_dir: Union[os.PathLike, str],
456    prediction_fname: str = "segmentation",
457    dilation: int = 5,
458    device: Optional[Union[torch.device, str]] = None,
459    first_prompt_at_center: bool = True,  # NOTE: With our current schema, we always put the first prompt in center.
460    min_size: int = 0,
461    batch_size: int = 16,
462    n_iterations: int = 8,
463    run_connected_components: bool = True,
464    seed: int = 0,
465    correction_margin: float = 0.0,
466    click_protocol: str = "random",
467) -> str:
468    """Run interactive segmentation on 3d inputs using Segment Anything 2.
469
470    Args:
471        raw: The raw input array.
472        labels: The corresponding ground-truth array with instance labels.
473        model_type: The choice of Segment Anything 2 model.
474        checkpoint_path: The filepath to the model checkpoints.
475        start_with_box_prompt: Whether the iterative prompting starts with 'box' as first prompt
476            (else 'points' will be used).
477        prediction_dir: The filepath where the predictions will be stored.
478        prediction_fname: The name for storing the segmentations.
479        dilation: The dilation factor for the radius around the ground-truth object around which
480            points will not be sampled.
481        device: The torch device.
482        first_prompt_at_center: Whether to place the first prompt at center.
483        min_size: The minimum pixel criterion to accept instance objects for interactive segmentation.
484        batch_size: The batch size to compute prompts.
485        n_iterations: The number of iterations for iterative prompting.
486        run_connected_components: Whether to ensure individual instances and filter out small objects.
487        seed: The seed of the prompt sampling of the volume.
488        correction_margin: The fraction of each object's z-extent at either end that is excluded when the slice
489            for the next correction click is chosen. 0 chooses among all slices of the object.
490        click_protocol: The correction clicks on the worst slice of an object: 'random' samples them at random
491            positions in the error regions, 'center' places them at the centers of the largest error regions.
492
493    Returns:
494        The folder where segmentations are stored.
495    """
496    prediction_dir, prediction_paths = get_prediction_paths_3d(
497        prediction_dir, prediction_fname, start_with_box_prompt, n_iterations
498    )
499    if all([os.path.exists(_path) for _path in prediction_paths]):
500        cached = imageio.imread(prediction_paths[0])
501        if cached.shape == labels.shape:
502            print(f"The results are stored at '{prediction_dir}'.")
503            return prediction_dir
504        warnings.warn(
505            f"Stale cache: '{prediction_paths[0]}' has shape {cached.shape} "
506            f"but labels have shape {labels.shape}. Deleting and recomputing."
507        )
508        for path in prediction_paths:
509            if os.path.exists(path):
510                os.remove(path)
511
512    # Get the device.
513    device = _get_device(device)
514
515    if run_connected_components:
516        # Ensuring sequential instance labels.
517        labels = connected_components(labels).astype(labels.dtype)
518        # NOTE: There are some objects covering very few pixels, eg. in lucchi, causing troubles in iterative prompting.
519        labels = size_filter(seg=labels, min_size=min_size)
520
521    # Preparing prompts for the first iteration
522    if start_with_box_prompt:
523        use_boxes, use_points = True, False
524        n_positive = 0
525    else:
526        use_boxes, use_points = False, True
527        n_positive = 1
528
529    # Get the SAM2 predictor.
530    predictor = get_sam2_model(
531        model_type=model_type, device=device, checkpoint_path=checkpoint_path, input_type="videos",
532    )
533    # Match training: frames that receive correction clicks become conditioning frames so
534    # their corrected predictions are preserved and used as memory for neighboring frames.
535    predictor.add_all_frames_to_correct_as_cond = True
536
537    # Initialize the inference state
538    volume_embeddings = _embedding_tensors_to_numpy(
539        precompute_image_embeddings(predictor=predictor, input_=raw, ndim=3)
540    )
541    inference_state = predictor.init_state(volume=raw, volume_embeddings=volume_embeddings)
542
543    # The prompt generators sample from the global numpy RNG. Seeding it per volume makes the clicks,
544    # and with them the results, reproducible.
545    np.random.seed(seed)
546
547    gt_ids = list(np.setdiff1d(np.unique(labels), [0]))  # Ignoring the background label
548    # An empty volume has nothing to prompt, so all iterations stay empty.
549    segmentation = [np.zeros(labels.shape, dtype="uint64") for _ in range(n_iterations)]
550    # The area of the object that holds each label, per iteration, to resolve overlaps.
551    areas = [np.full(int(max(gt_ids, default=0)) + 1, np.inf) for _ in range(n_iterations)]
552    for gt_id in tqdm(gt_ids, desc="Segmenting per object in the volume"):
553        _per_iter_segmentation = _run_interactive_segmentation_3d_per_object(
554            gt_ids=gt_id,
555            labels=labels,
556            predictor=predictor,
557            inference_state=inference_state,
558            first_prompt_at_center=first_prompt_at_center,
559            use_points=use_points,
560            use_boxes=use_boxes,
561            n_positive=n_positive,
562            dilation=dilation,
563            batch_size=batch_size,
564            n_iterations=n_iterations,
565            correction_margin=correction_margin,
566            click_protocol=click_protocol,
567        )
568
569        # Merge the incoming object. Where objects overlap, the smaller one is kept, as in the 2d
570        # evaluation (see 'mask_data_to_segmentation'). Adding the labels would turn an overlap into the
571        # sum of both ids, i.e. into a third object.
572        for _iter in range(n_iterations):
573            mask = _per_iter_segmentation[_iter] > 0
574            area = mask.sum()
575            existing = segmentation[_iter][mask]
576            segmentation[_iter][mask] = np.where(areas[_iter][existing] > area, gt_id, existing)
577            areas[_iter][gt_id] = area
578
579    # Each file is written under a temporary name and then renamed, so a job killed during the write
580    # leaves no truncated file that a rerun would accept as complete.
581    for i, prediction_path in enumerate(prediction_paths):
582        os.makedirs(Path(prediction_path).parent, exist_ok=True)
583        partial_path = Path(prediction_path).with_suffix(".partial.tif")
584        imageio.imwrite(partial_path, segmentation[i], compression="zlib")
585        os.replace(partial_path, prediction_path)
586
587    return prediction_dir

Run interactive segmentation on 3d inputs using Segment Anything 2.

Arguments:
  • raw: The raw input array.
  • labels: The corresponding ground-truth array with instance labels.
  • model_type: The choice of Segment Anything 2 model.
  • checkpoint_path: The filepath to the model checkpoints.
  • start_with_box_prompt: Whether the iterative prompting starts with 'box' as first prompt (else 'points' will be used).
  • prediction_dir: The filepath where the predictions will be stored.
  • prediction_fname: The name for storing the segmentations.
  • dilation: The dilation factor for the radius around the ground-truth object around which points will not be sampled.
  • device: The torch device.
  • first_prompt_at_center: Whether to place the first prompt at center.
  • min_size: The minimum pixel criterion to accept instance objects for interactive segmentation.
  • batch_size: The batch size to compute prompts.
  • n_iterations: The number of iterations for iterative prompting.
  • run_connected_components: Whether to ensure individual instances and filter out small objects.
  • seed: The seed of the prompt sampling of the volume.
  • correction_margin: The fraction of each object's z-extent at either end that is excluded when the slice for the next correction click is chosen. 0 chooses among all slices of the object.
  • click_protocol: The correction clicks on the worst slice of an object: 'random' samples them at random positions in the error regions, 'center' places them at the centers of the largest error regions.
Returns:

The folder where segmentations are stored.