micro_sam.v1.evaluation.multi_dimensional_segmentation

  1import os
  2from math import floor
  3from itertools import product
  4from typing import Union, Tuple, Optional, List, Dict, Literal
  5
  6import numpy as np
  7import pandas as pd
  8from tqdm import tqdm
  9import imageio.v3 as imageio
 10
 11import torch
 12
 13from bioimage_cpp.distance import distance_transform
 14
 15from elf.evaluation import mean_segmentation_accuracy, dice_score
 16
 17from ... import util
 18from ..inference import batched_inference
 19from ...prompt_generators import PointAndBoxPromptGenerator
 20from ..util import get_sam_model, precompute_image_embeddings
 21from ..multi_dimensional_segmentation import segment_mask_in_volume
 22from ..evaluation.instance_segmentation import _get_range_of_search_values, evaluate_instance_segmentation_grid_search
 23from ..prompt_based_segmentation import (
 24    segment_from_box, segment_from_box_and_points, segment_from_mask, segment_from_points
 25)
 26
 27
 28def default_grid_search_values_multi_dimensional_segmentation(
 29    iou_threshold_values: Optional[List[float]] = None,
 30    projection_method_values: Optional[Union[str, dict]] = None,
 31    box_extension_values: Optional[Union[float, int]] = None
 32) -> Dict[str, List]:
 33    """Default grid-search parameters for multi-dimensional prompt-based instance segmentation.
 34
 35    Args:
 36        iou_threshold_values: The values for `iou_threshold` used in the grid-search.
 37            By default values in the range from 0.5 to 0.9 with a stepsize of 0.1 will be used.
 38        projection_method_values: The values for `projection` method used in the grid-search.
 39            By default the values `mask`, `points`, `box`, `points_and_mask` and `single_point` are used.
 40        box_extension_values: The values for `box_extension` used in the grid-search.
 41            By default values in the range from 0 to 0.25 with a stepsize of 0.025 will be used.
 42
 43    Returns:
 44        The values for grid search.
 45    """
 46    if iou_threshold_values is None:
 47        iou_threshold_values = _get_range_of_search_values([0.5, 0.9], step=0.1)
 48
 49    if projection_method_values is None:
 50        projection_method_values = [
 51            "mask", "points", "box", "points_and_mask", "single_point"
 52        ]
 53
 54    if box_extension_values is None:
 55        box_extension_values = _get_range_of_search_values([0, 0.25], step=0.025)
 56
 57    return {
 58        "iou_threshold": iou_threshold_values,
 59        "projection": projection_method_values,
 60        "box_extension": box_extension_values
 61    }
 62
 63
 64@torch.no_grad()
 65def segment_slices_from_ground_truth(
 66    volume: np.ndarray,
 67    ground_truth: np.ndarray,
 68    model_type: str,
 69    checkpoint_path: Optional[Union[str, os.PathLike]] = None,
 70    embedding_path: Optional[Union[str, os.PathLike]] = None,
 71    save_path: Optional[Union[str, os.PathLike]] = None,
 72    iou_threshold: float = 0.8,
 73    projection: Union[str, dict] = "mask",
 74    box_extension: Union[float, int] = 0.025,
 75    device: Union[str, torch.device] = None,
 76    interactive_seg_mode: str = "box",
 77    verbose: bool = False,
 78    return_segmentation: bool = False,
 79    min_size: int = 0,
 80    evaluation_metric: Literal["sa", "dice"] = "sa",
 81) -> Union[Dict, Tuple[Dict, np.ndarray]]:
 82    """Segment all objects in a volume by prompt-based segmentation in one slice per object.
 83
 84    This function first segments each object in the respective specified slice using interactive
 85    (prompt-based) segmentation functionality. Then it segments the particular object in the
 86    remaining slices in the volume.
 87
 88    Args:
 89        volume: The input volume.
 90        ground_truth: The label volume with instance segmentations.
 91        model_type: Choice of segment anything model.
 92        checkpoint_path: Path to the model checkpoint.
 93        embedding_path: Path to cache the computed embeddings.
 94        save_path: Path to store the segmentations.
 95        iou_threshold: The criterion to decide whether to link the objects in the consecutive slice's segmentation.
 96        projection: The projection (prompting) method to generate prompts for consecutive slices.
 97        box_extension: Extension factor for increasing the box size after projection.
 98        device: The selected device for computation.
 99        interactive_seg_mode: Method for guiding prompt-based instance segmentation.
100        verbose: Whether to get the trace for projected segmentations.
101        return_segmentation: Whether to return the segmented volume.
102        min_size: The minimal size for evaluating an object in the ground-truth.
103            The size is measured within the central slice.
104        evaluation_metric: The choice of supported metric to evaluate predictions.
105
106    Returns:
107        A dictionary of results with all desired metrics.
108        Optional segmentation result (controlled by `return_segmentation` argument).
109    """
110    assert volume.ndim == 3
111
112    predictor = get_sam_model(model_type=model_type, checkpoint_path=checkpoint_path, device=device)
113
114    # Compute the image embeddings
115    embeddings = precompute_image_embeddings(
116        predictor=predictor, input_=volume, save_path=embedding_path, ndim=3, verbose=verbose,
117    )
118
119    # Compute instance ids (without the background)
120    label_ids = np.setdiff1d(np.unique(ground_truth), [0])
121    assert len(label_ids) > 0, "There are no objects to perform volumetric segmentation."
122
123    # Create an empty volume to store incoming segmentations
124    final_segmentation = np.zeros_like(ground_truth)
125
126    _segmentation_completed = False
127    if save_path is not None and os.path.exists(save_path):
128        _segmentation_completed = True  # We avoid rerunning the segmentation if it is completed.
129
130    skipped_label_ids = []
131    for label_id in tqdm(label_ids, desc="Segmenting per object in the volume", disable=not verbose):
132        # Binary label volume per instance (also referred to as object)
133        this_seg = (ground_truth == label_id).astype("int")
134
135        # Let's search the slices where we have the current object
136        slice_range = np.where(this_seg)[0]
137
138        # Choose the middle slice of the current object for prompt-based segmentation
139        slice_range = (slice_range.min(), slice_range.max())
140        slice_choice = floor(np.mean(slice_range))
141        this_slice_seg = this_seg[slice_choice]
142        if min_size > 0 and this_slice_seg.sum() < min_size:
143            skipped_label_ids.append(label_id)
144            continue
145
146        if _segmentation_completed:
147            continue
148
149        if verbose:
150            print(f"The object with id {label_id} lies in slice range: {slice_range}")
151
152        # Prompts for segmentation for the current slice
153        if interactive_seg_mode == "points":
154            _get_points, _get_box = True, False
155        elif interactive_seg_mode == "box":
156            _get_points, _get_box = False, True
157        else:
158            raise ValueError(
159                f"The provided interactive prompting '{interactive_seg_mode}' for the first slice isn't supported. "
160                "Please choose from 'box' / 'points'."
161            )
162
163        prompt_generator = PointAndBoxPromptGenerator(
164            n_positive_points=1 if _get_points else 0,
165            n_negative_points=1 if _get_points else 0,
166            dilation_strength=10,
167            get_point_prompts=_get_points,
168            get_box_prompts=_get_box
169        )
170        _, box_coords = util.get_centers_and_bounding_boxes(this_slice_seg)
171        point_prompts, point_labels, box_prompts, _ = prompt_generator(
172            segmentation=torch.from_numpy(this_slice_seg)[None, None].to(torch.float32),
173            bbox_coordinates=[box_coords[1]],
174        )
175
176        # Prompt-based segmentation on middle slice of the current object
177        output_slice = batched_inference(
178            predictor=predictor,
179            image=volume[slice_choice],
180            batch_size=1,
181            boxes=box_prompts.numpy() if isinstance(box_prompts, torch.Tensor) else box_prompts,
182            points=point_prompts.numpy() if isinstance(point_prompts, torch.Tensor) else point_prompts,
183            point_labels=point_labels.numpy() if isinstance(point_labels, torch.Tensor) else point_labels,
184            verbose_embeddings=verbose,
185        )
186        output_seg = np.zeros_like(ground_truth)
187        output_seg[slice_choice][output_slice == 1] = 1
188
189        # Segment the object in the entire volume with the specified segmented slice
190        this_seg, _ = segment_mask_in_volume(
191            segmentation=output_seg,
192            predictor=predictor,
193            image_embeddings=embeddings,
194            segmented_slices=np.array(slice_choice),
195            stop_lower=False, stop_upper=False,
196            iou_threshold=iou_threshold,
197            projection=projection,
198            box_extension=box_extension,
199            verbose=verbose,
200        )
201
202        # Store the entire segmented object
203        final_segmentation[this_seg == 1] = label_id
204
205    # Save the volumetric segmentation
206    if save_path is not None:
207        if _segmentation_completed:
208            final_segmentation = imageio.imread(save_path)
209        else:
210            imageio.imwrite(save_path, final_segmentation, compression="zlib")
211
212    # Evaluate the volumetric segmentation
213    if skipped_label_ids:
214        curr_gt = ground_truth.copy()
215        curr_gt[np.isin(curr_gt, skipped_label_ids)] = 0
216    else:
217        curr_gt = ground_truth
218
219    if evaluation_metric == "sa":
220        msa, sa = mean_segmentation_accuracy(
221            segmentation=final_segmentation, groundtruth=curr_gt, return_accuracies=True
222        )
223        results = {"mSA": msa, "SA50": sa[0], "SA75": sa[5]}
224
225    elif evaluation_metric == "dice":
226        # Calculate overall dice score (by binarizing all labels).
227        dice = dice_score(segmentation=final_segmentation, groundtruth=curr_gt)
228        results = {"Dice": dice}
229
230    elif evaluation_metric == "dice_per_class":
231        # Calculate dice per class.
232        dice = [
233            dice_score(segmentation=(final_segmentation == i), groundtruth=(curr_gt == i))
234            for i in np.setdiff1d(np.unique(curr_gt), [0])
235        ]
236        dice = np.mean(dice)
237        results = {"Dice": dice}
238
239    else:
240        raise ValueError(
241            f"'{evaluation_metric}' is not a supported evaluation metrics. "
242            "Please choose 'sa' / 'dice' / 'dice_per_class'."
243        )
244
245    if return_segmentation:
246        return results, final_segmentation
247    else:
248        return results
249
250
251def _get_best_parameters_from_grid_search_combinations(
252    result_dir, best_params_path, grid_search_values, evaluation_metric,
253):
254    if os.path.exists(best_params_path):
255        print("The best parameters are already saved at:", best_params_path)
256        return
257
258    criterion = "mSA" if evaluation_metric == "sa" else "Dice"
259    best_kwargs, best_metric = evaluate_instance_segmentation_grid_search(
260        result_dir=result_dir, grid_search_parameters=list(grid_search_values.keys()), criterion=criterion,
261    )
262
263    # let's save the best parameters
264    best_kwargs[criterion] = best_metric
265    best_param_df = pd.DataFrame.from_dict([best_kwargs])
266    best_param_df.to_csv(best_params_path)
267
268    best_param_str = ", ".join(f"{k} = {v}" for k, v in best_kwargs.items())
269    print("Best grid-search result:", best_metric, "with parmeters:\n", best_param_str)
270
271
272def run_multi_dimensional_segmentation_grid_search(
273    volume: np.ndarray,
274    ground_truth: np.ndarray,
275    model_type: str,
276    checkpoint_path: Union[str, os.PathLike],
277    embedding_path: Optional[Union[str, os.PathLike]],
278    result_dir: Union[str, os.PathLike],
279    interactive_seg_mode: str = "box",
280    verbose: bool = False,
281    grid_search_values: Optional[Dict[str, List]] = None,
282    min_size: int = 0,
283    evaluation_metric: Literal["sa", "dice"] = "sa",
284    store_segmentation: bool = False,
285) -> str:
286    """Run grid search for prompt-based multi-dimensional instance segmentation.
287
288    The parameters and their respective value ranges for the grid search are specified via the
289    `grid_search_values` argument. For example, to run a grid search over the parameters `iou_threshold`,
290    `projection` and `box_extension`, you can pass the following:
291    ```python
292    grid_search_values = {
293        "iou_threshold": [0.5, 0.6, 0.7, 0.8, 0.9],
294        "projection": ["mask", "box", "points"],
295        "box_extension": [0, 0.1, 0.2, 0.3, 0.4, 0,5],
296    }
297    ```
298    All combinations of the parameters will be checked.
299    If passed None, the function `default_grid_search_values_multi_dimensional_segmentation` is used
300    to get the default grid search parameters for the instance segmentation method.
301
302    Args:
303        volume: The input volume.
304        ground_truth: The label volume with instance segmentations.
305        model_type: Choice of segment anything model.
306        checkpoint_path: Path to the model checkpoint.
307        embedding_path: Path to cache the computed embeddings.
308        result_dir: Path to save the grid search results.
309        interactive_seg_mode: Method for guiding prompt-based instance segmentation.
310        verbose: Whether to get the trace for projected segmentations.
311        grid_search_values: The grid search values for parameters of the `segment_slices_from_ground_truth` function.
312        min_size: The minimal size for evaluating an object in the ground-truth.
313            The size is measured within the central slice.
314        evaluation_metric: The choice of metric for evaluating predictions.
315        store_segmentation: Whether to store the segmentations per grid-search locally.
316
317    Returns:
318        Filepath where the best parameters are saved.
319    """
320    if grid_search_values is None:
321        grid_search_values = default_grid_search_values_multi_dimensional_segmentation()
322
323    assert len(grid_search_values.keys()) == 3, "There must be three grid-search parameters. See above for details."
324
325    os.makedirs(result_dir, exist_ok=True)
326    result_path = os.path.join(result_dir, "all_grid_search_results.csv")
327    best_params_path = os.path.join(result_dir, "grid_search_params_multi_dimensional_segmentation.csv")
328    if os.path.exists(result_path):
329        _get_best_parameters_from_grid_search_combinations(
330            result_dir, best_params_path, grid_search_values, evaluation_metric
331        )
332        return best_params_path
333
334    # Compute all combinations of grid search values.
335    gs_combinations = product(*grid_search_values.values())
336
337    # Map each combination back to a valid kwarg input.
338    gs_combinations = [
339        {k: v for k, v in zip(grid_search_values.keys(), vals)} for vals in gs_combinations
340    ]
341
342    prediction_dir = os.path.join(result_dir, "predictions")
343    os.makedirs(prediction_dir, exist_ok=True)
344
345    net_list = []
346    for i, gs_kwargs in tqdm(
347        enumerate(gs_combinations),
348        total=len(gs_combinations),
349        desc="Run grid-search for multi-dimensional segmentation",
350    ):
351        results, segmentation = segment_slices_from_ground_truth(
352            volume=volume,
353            ground_truth=ground_truth,
354            model_type=model_type,
355            checkpoint_path=checkpoint_path,
356            embedding_path=embedding_path,
357            interactive_seg_mode=interactive_seg_mode,
358            verbose=verbose,
359            return_segmentation=True,
360            min_size=min_size,
361            evaluation_metric=evaluation_metric,
362            **gs_kwargs
363        )
364
365        # Store the segmentations for each grid search combination, if desired by the user.
366        if store_segmentation:
367            imageio.imwrite(
368                os.path.join(prediction_dir, f"grid_search_result_{i:05}.tif"), segmentation, compression="zlib"
369            )
370
371        result_dict = {**results, **gs_kwargs}
372        tmp_df = pd.DataFrame([result_dict])
373        net_list.append(tmp_df)
374
375    res_df = pd.concat(net_list, ignore_index=True)
376    res_df.to_csv(result_path)
377
378    _get_best_parameters_from_grid_search_combinations(
379        result_dir, best_params_path, grid_search_values, evaluation_metric
380    )
381    print("The best grid-search parameters have been computed and stored at:", best_params_path)
382    return best_params_path
383
384
385PROMPT_CHOICES = ("box", "points", "box_and_points")
386START_SLICE_CHOICES = ("begin", "center", "end", "random")
387
388
389def _deepest_point(mask):
390    """Return the pixel of a 2d mask that is farthest from its boundary, as (y, x)."""
391    distances = distance_transform(np.pad(mask, 1))[1:-1, 1:-1]
392    return np.array(np.unravel_index(np.argmax(distances), mask.shape))
393
394
395def _new_anchor():
396    """Return the empty prompts of a slice. The prompts accumulate over the iterations."""
397    return {"box": None, "points": [], "labels": [], "mask": None}
398
399
400def _add_prompts(anchor, gt, pred, kind):
401    """Add one interaction on a slice to the prompts of the slice.
402
403    The box is the ground-truth box. The points are a positive click in the largest missed region
404    and a negative click in the largest false region.
405    """
406    ys, xs = np.where(gt)
407    box = np.array([ys.min(), xs.min(), ys.max() + 1, xs.max() + 1])
408    use_box, use_points = kind in ("box", "box_and_points"), kind in ("points", "box_and_points")
409    if use_box and np.array_equal(anchor["box"], box):
410        use_box, use_points = False, True  # The same box again adds nothing, so click instead.
411
412    if use_box:
413        anchor["box"] = box
414    if use_points:
415        # Always click positive: the annotator reads a single negative click as a stop.
416        missed, false = gt & ~pred, pred & ~gt
417        anchor["points"].append(_deepest_point(missed if missed.any() else gt))
418        anchor["labels"].append(1)
419        if false.any():
420            anchor["points"].append(_deepest_point(false))
421            anchor["labels"].append(0)
422    anchor["mask"] = None
423
424
425def _segment_anchor(predictor, image_embeddings, z, anchor, previous):
426    """Segment one prompted slice from its prompts, and from the previous mask if you pass one."""
427    box = anchor["box"]
428    points = np.array(anchor["points"]) if anchor["points"] else None
429    labels = np.array(anchor["labels"]) if anchor["labels"] else None
430    kwargs = {"image_embeddings": image_embeddings, "i": z}
431
432    if previous is not None and previous.any():
433        # Unlike the other functions, 'segment_from_mask' takes the points in (x, y) order.
434        mask = segment_from_mask(
435            predictor, previous, use_box=False, box=box, labels=labels,
436            points=None if points is None else points[:, ::-1], **kwargs,
437        )
438    elif box is not None and points is not None:
439        mask = segment_from_box_and_points(predictor, box, points, labels, **kwargs)
440    elif box is not None:
441        mask = segment_from_box(predictor, box, **kwargs)
442    else:
443        mask = segment_from_points(predictor, points, labels, **kwargs)
444    return mask.squeeze().astype(bool)
445
446
447def evaluate_interactive_volume_segmentation(
448    predictor,
449    volume: np.ndarray,
450    ground_truth: np.ndarray,
451    image_embeddings: Optional[util.ImageEmbeddings] = None,
452    start_prompt: str = "box",
453    start_slice: str = "center",
454    n_iterations: int = 8,
455    correction: str = "box_and_points",
456    use_previous_mask: bool = False,
457    projection: Union[str, dict] = "mask",
458    iou_threshold: float = 0.8,
459    box_extension: float = 0.025,
460    seed: Optional[int] = None,
461    verbose: bool = False,
462) -> List[np.ndarray]:
463    """Segment every object of a volume with iterative prompts, as a user of the 3d annotator does.
464
465    The function prompts each object on one slice and projects the result through the volume.
466    Each later iteration corrects the slice with the largest error. Then the function segments the object
467    again from all prompts so far. A leak beyond the object gets a stop slice instead of a prompt.
468
469    Args:
470        predictor: The segment anything predictor.
471        volume: The input volume, with the shape (Z, Y, X).
472        ground_truth: The instance labels of the volume. The function derives the prompts from them.
473        image_embeddings: The precomputed embeddings of the volume. The function computes them if you do not pass them.
474        start_prompt: The first prompt of an object: 'box', 'points' (a positive click) or 'box_and_points'.
475        start_slice: The slice of the object that gets the first prompt: 'begin', 'center', 'end' or 'random'.
476        n_iterations: The number of iterations, which includes the first prompt.
477        correction: The prompt on the worst slice: 'box', 'points' (a positive and a negative click) or
478            'box_and_points'. If the slice already has the ground-truth box, 'box' adds clicks instead.
479        use_previous_mask: Whether to pass the previous prediction of a prompted slice as a mask prompt.
480        projection: The projection from slice to slice, see `segment_mask_in_volume`.
481        iou_threshold: The IoU between neighbouring slices below which the projection stops.
482        box_extension: The extension of the projected box, see `segment_mask_in_volume`.
483        seed: The seed for the 'random' start slice.
484        verbose: Whether to show the progress.
485
486    Returns:
487        The instance segmentation after each iteration.
488    """
489    if start_prompt not in PROMPT_CHOICES or correction not in PROMPT_CHOICES:
490        raise ValueError(f"The prompts '{start_prompt}' and '{correction}' must be one of {PROMPT_CHOICES}.")
491    if start_slice not in START_SLICE_CHOICES:
492        raise ValueError(f"The start slice '{start_slice}' must be one of {START_SLICE_CHOICES}.")
493
494    if image_embeddings is None:
495        image_embeddings = precompute_image_embeddings(predictor, volume, ndim=3, verbose=verbose)
496    rng = np.random.default_rng(seed)
497    z_index = np.arange(volume.shape[0])
498
499    segmentations = [np.zeros(ground_truth.shape, dtype="uint32") for _ in range(n_iterations)]
500    for label_id in tqdm(np.setdiff1d(np.unique(ground_truth), [0]), desc="Segment objects", disable=not verbose):
501        gt = ground_truth == label_id
502        z_values = np.where(gt.any(axis=(1, 2)))[0]
503        if start_slice == "random":
504            z = int(rng.choice(z_values))
505        else:
506            z = int(z_values[{"begin": 0, "center": len(z_values) // 2, "end": -1}[start_slice]])
507
508        anchors, stops, pred = {}, {"lower": None, "upper": None}, None
509        _add_prompts(anchors.setdefault(z, _new_anchor()), gt[z], np.zeros_like(gt[z]), start_prompt)
510
511        for segmentation in segmentations:
512            if pred is not None:
513                # A stop works only beyond the outermost prompts, so skip the empty slices between them.
514                errors = (gt != pred).sum(axis=(1, 2))
515                errors[~gt.any(axis=(1, 2)) & (z_index > min(anchors)) & (z_index < max(anchors))] = 0
516                z = int(np.argmax(errors))
517                if errors[z] == 0:
518                    segmentation[pred] = label_id
519                    continue
520
521                if gt[z].any():
522                    _add_prompts(anchors.setdefault(z, _new_anchor()), gt[z], pred[z], correction)
523                else:
524                    stops["lower" if z < min(anchors) else "upper"] = z
525                # A new prompt beyond a stop removes the stop.
526                if stops["lower"] is not None and stops["lower"] > min(anchors):
527                    stops["lower"] = None
528                if stops["upper"] is not None and stops["upper"] < max(anchors):
529                    stops["upper"] = None
530
531            # Prompts that did not change give the same mask, so only the changed slices run SAM again.
532            seg = np.zeros(gt.shape, dtype="uint32")
533            for z, anchor in anchors.items():
534                if anchor["mask"] is None or (use_previous_mask and pred is not None):
535                    previous = pred[z] if use_previous_mask and pred is not None else None
536                    anchor["mask"] = _segment_anchor(predictor, image_embeddings, z, anchor, previous)
537                seg[z] = anchor["mask"]
538
539            slices = np.array(sorted(set(anchors) | {s for s in stops.values() if s is not None}))
540            seg, _ = segment_mask_in_volume(
541                seg, predictor, image_embeddings, slices,
542                stop_lower=stops["lower"] is not None, stop_upper=stops["upper"] is not None,
543                iou_threshold=iou_threshold, projection=projection, box_extension=box_extension,
544            )
545            pred = seg == 1
546            segmentation[pred] = label_id
547
548    return segmentations
def default_grid_search_values_multi_dimensional_segmentation( iou_threshold_values: Optional[List[float]] = None, projection_method_values: Union[str, dict, NoneType] = None, box_extension_values: Union[float, int, NoneType] = None) -> Dict[str, List]:
29def default_grid_search_values_multi_dimensional_segmentation(
30    iou_threshold_values: Optional[List[float]] = None,
31    projection_method_values: Optional[Union[str, dict]] = None,
32    box_extension_values: Optional[Union[float, int]] = None
33) -> Dict[str, List]:
34    """Default grid-search parameters for multi-dimensional prompt-based instance segmentation.
35
36    Args:
37        iou_threshold_values: The values for `iou_threshold` used in the grid-search.
38            By default values in the range from 0.5 to 0.9 with a stepsize of 0.1 will be used.
39        projection_method_values: The values for `projection` method used in the grid-search.
40            By default the values `mask`, `points`, `box`, `points_and_mask` and `single_point` are used.
41        box_extension_values: The values for `box_extension` used in the grid-search.
42            By default values in the range from 0 to 0.25 with a stepsize of 0.025 will be used.
43
44    Returns:
45        The values for grid search.
46    """
47    if iou_threshold_values is None:
48        iou_threshold_values = _get_range_of_search_values([0.5, 0.9], step=0.1)
49
50    if projection_method_values is None:
51        projection_method_values = [
52            "mask", "points", "box", "points_and_mask", "single_point"
53        ]
54
55    if box_extension_values is None:
56        box_extension_values = _get_range_of_search_values([0, 0.25], step=0.025)
57
58    return {
59        "iou_threshold": iou_threshold_values,
60        "projection": projection_method_values,
61        "box_extension": box_extension_values
62    }

Default grid-search parameters for multi-dimensional prompt-based instance segmentation.

Arguments:
  • iou_threshold_values: The values for iou_threshold used in the grid-search. By default values in the range from 0.5 to 0.9 with a stepsize of 0.1 will be used.
  • projection_method_values: The values for projection method used in the grid-search. By default the values mask, points, box, points_and_mask and single_point are used.
  • box_extension_values: The values for box_extension used in the grid-search. By default values in the range from 0 to 0.25 with a stepsize of 0.025 will be used.
Returns:

The values for grid search.

@torch.no_grad()
def segment_slices_from_ground_truth( volume: numpy.ndarray, ground_truth: numpy.ndarray, model_type: str, checkpoint_path: Union[str, os.PathLike, NoneType] = None, embedding_path: Union[str, os.PathLike, NoneType] = None, save_path: Union[str, os.PathLike, NoneType] = None, iou_threshold: float = 0.8, projection: Union[str, dict] = 'mask', box_extension: Union[float, int] = 0.025, device: Union[str, torch.device] = None, interactive_seg_mode: str = 'box', verbose: bool = False, return_segmentation: bool = False, min_size: int = 0, evaluation_metric: Literal['sa', 'dice'] = 'sa') -> Union[Dict, Tuple[Dict, numpy.ndarray]]:
 65@torch.no_grad()
 66def segment_slices_from_ground_truth(
 67    volume: np.ndarray,
 68    ground_truth: np.ndarray,
 69    model_type: str,
 70    checkpoint_path: Optional[Union[str, os.PathLike]] = None,
 71    embedding_path: Optional[Union[str, os.PathLike]] = None,
 72    save_path: Optional[Union[str, os.PathLike]] = None,
 73    iou_threshold: float = 0.8,
 74    projection: Union[str, dict] = "mask",
 75    box_extension: Union[float, int] = 0.025,
 76    device: Union[str, torch.device] = None,
 77    interactive_seg_mode: str = "box",
 78    verbose: bool = False,
 79    return_segmentation: bool = False,
 80    min_size: int = 0,
 81    evaluation_metric: Literal["sa", "dice"] = "sa",
 82) -> Union[Dict, Tuple[Dict, np.ndarray]]:
 83    """Segment all objects in a volume by prompt-based segmentation in one slice per object.
 84
 85    This function first segments each object in the respective specified slice using interactive
 86    (prompt-based) segmentation functionality. Then it segments the particular object in the
 87    remaining slices in the volume.
 88
 89    Args:
 90        volume: The input volume.
 91        ground_truth: The label volume with instance segmentations.
 92        model_type: Choice of segment anything model.
 93        checkpoint_path: Path to the model checkpoint.
 94        embedding_path: Path to cache the computed embeddings.
 95        save_path: Path to store the segmentations.
 96        iou_threshold: The criterion to decide whether to link the objects in the consecutive slice's segmentation.
 97        projection: The projection (prompting) method to generate prompts for consecutive slices.
 98        box_extension: Extension factor for increasing the box size after projection.
 99        device: The selected device for computation.
100        interactive_seg_mode: Method for guiding prompt-based instance segmentation.
101        verbose: Whether to get the trace for projected segmentations.
102        return_segmentation: Whether to return the segmented volume.
103        min_size: The minimal size for evaluating an object in the ground-truth.
104            The size is measured within the central slice.
105        evaluation_metric: The choice of supported metric to evaluate predictions.
106
107    Returns:
108        A dictionary of results with all desired metrics.
109        Optional segmentation result (controlled by `return_segmentation` argument).
110    """
111    assert volume.ndim == 3
112
113    predictor = get_sam_model(model_type=model_type, checkpoint_path=checkpoint_path, device=device)
114
115    # Compute the image embeddings
116    embeddings = precompute_image_embeddings(
117        predictor=predictor, input_=volume, save_path=embedding_path, ndim=3, verbose=verbose,
118    )
119
120    # Compute instance ids (without the background)
121    label_ids = np.setdiff1d(np.unique(ground_truth), [0])
122    assert len(label_ids) > 0, "There are no objects to perform volumetric segmentation."
123
124    # Create an empty volume to store incoming segmentations
125    final_segmentation = np.zeros_like(ground_truth)
126
127    _segmentation_completed = False
128    if save_path is not None and os.path.exists(save_path):
129        _segmentation_completed = True  # We avoid rerunning the segmentation if it is completed.
130
131    skipped_label_ids = []
132    for label_id in tqdm(label_ids, desc="Segmenting per object in the volume", disable=not verbose):
133        # Binary label volume per instance (also referred to as object)
134        this_seg = (ground_truth == label_id).astype("int")
135
136        # Let's search the slices where we have the current object
137        slice_range = np.where(this_seg)[0]
138
139        # Choose the middle slice of the current object for prompt-based segmentation
140        slice_range = (slice_range.min(), slice_range.max())
141        slice_choice = floor(np.mean(slice_range))
142        this_slice_seg = this_seg[slice_choice]
143        if min_size > 0 and this_slice_seg.sum() < min_size:
144            skipped_label_ids.append(label_id)
145            continue
146
147        if _segmentation_completed:
148            continue
149
150        if verbose:
151            print(f"The object with id {label_id} lies in slice range: {slice_range}")
152
153        # Prompts for segmentation for the current slice
154        if interactive_seg_mode == "points":
155            _get_points, _get_box = True, False
156        elif interactive_seg_mode == "box":
157            _get_points, _get_box = False, True
158        else:
159            raise ValueError(
160                f"The provided interactive prompting '{interactive_seg_mode}' for the first slice isn't supported. "
161                "Please choose from 'box' / 'points'."
162            )
163
164        prompt_generator = PointAndBoxPromptGenerator(
165            n_positive_points=1 if _get_points else 0,
166            n_negative_points=1 if _get_points else 0,
167            dilation_strength=10,
168            get_point_prompts=_get_points,
169            get_box_prompts=_get_box
170        )
171        _, box_coords = util.get_centers_and_bounding_boxes(this_slice_seg)
172        point_prompts, point_labels, box_prompts, _ = prompt_generator(
173            segmentation=torch.from_numpy(this_slice_seg)[None, None].to(torch.float32),
174            bbox_coordinates=[box_coords[1]],
175        )
176
177        # Prompt-based segmentation on middle slice of the current object
178        output_slice = batched_inference(
179            predictor=predictor,
180            image=volume[slice_choice],
181            batch_size=1,
182            boxes=box_prompts.numpy() if isinstance(box_prompts, torch.Tensor) else box_prompts,
183            points=point_prompts.numpy() if isinstance(point_prompts, torch.Tensor) else point_prompts,
184            point_labels=point_labels.numpy() if isinstance(point_labels, torch.Tensor) else point_labels,
185            verbose_embeddings=verbose,
186        )
187        output_seg = np.zeros_like(ground_truth)
188        output_seg[slice_choice][output_slice == 1] = 1
189
190        # Segment the object in the entire volume with the specified segmented slice
191        this_seg, _ = segment_mask_in_volume(
192            segmentation=output_seg,
193            predictor=predictor,
194            image_embeddings=embeddings,
195            segmented_slices=np.array(slice_choice),
196            stop_lower=False, stop_upper=False,
197            iou_threshold=iou_threshold,
198            projection=projection,
199            box_extension=box_extension,
200            verbose=verbose,
201        )
202
203        # Store the entire segmented object
204        final_segmentation[this_seg == 1] = label_id
205
206    # Save the volumetric segmentation
207    if save_path is not None:
208        if _segmentation_completed:
209            final_segmentation = imageio.imread(save_path)
210        else:
211            imageio.imwrite(save_path, final_segmentation, compression="zlib")
212
213    # Evaluate the volumetric segmentation
214    if skipped_label_ids:
215        curr_gt = ground_truth.copy()
216        curr_gt[np.isin(curr_gt, skipped_label_ids)] = 0
217    else:
218        curr_gt = ground_truth
219
220    if evaluation_metric == "sa":
221        msa, sa = mean_segmentation_accuracy(
222            segmentation=final_segmentation, groundtruth=curr_gt, return_accuracies=True
223        )
224        results = {"mSA": msa, "SA50": sa[0], "SA75": sa[5]}
225
226    elif evaluation_metric == "dice":
227        # Calculate overall dice score (by binarizing all labels).
228        dice = dice_score(segmentation=final_segmentation, groundtruth=curr_gt)
229        results = {"Dice": dice}
230
231    elif evaluation_metric == "dice_per_class":
232        # Calculate dice per class.
233        dice = [
234            dice_score(segmentation=(final_segmentation == i), groundtruth=(curr_gt == i))
235            for i in np.setdiff1d(np.unique(curr_gt), [0])
236        ]
237        dice = np.mean(dice)
238        results = {"Dice": dice}
239
240    else:
241        raise ValueError(
242            f"'{evaluation_metric}' is not a supported evaluation metrics. "
243            "Please choose 'sa' / 'dice' / 'dice_per_class'."
244        )
245
246    if return_segmentation:
247        return results, final_segmentation
248    else:
249        return results

Segment all objects in a volume by prompt-based segmentation in one slice per object.

This function first segments each object in the respective specified slice using interactive (prompt-based) segmentation functionality. Then it segments the particular object in the remaining slices in the volume.

Arguments:
  • volume: The input volume.
  • ground_truth: The label volume with instance segmentations.
  • model_type: Choice of segment anything model.
  • checkpoint_path: Path to the model checkpoint.
  • embedding_path: Path to cache the computed embeddings.
  • save_path: Path to store the segmentations.
  • iou_threshold: The criterion to decide whether to link the objects in the consecutive slice's segmentation.
  • projection: The projection (prompting) method to generate prompts for consecutive slices.
  • box_extension: Extension factor for increasing the box size after projection.
  • device: The selected device for computation.
  • interactive_seg_mode: Method for guiding prompt-based instance segmentation.
  • verbose: Whether to get the trace for projected segmentations.
  • return_segmentation: Whether to return the segmented volume.
  • min_size: The minimal size for evaluating an object in the ground-truth. The size is measured within the central slice.
  • evaluation_metric: The choice of supported metric to evaluate predictions.
Returns:

A dictionary of results with all desired metrics. Optional segmentation result (controlled by return_segmentation argument).

PROMPT_CHOICES = ('box', 'points', 'box_and_points')
START_SLICE_CHOICES = ('begin', 'center', 'end', 'random')
def evaluate_interactive_volume_segmentation( predictor, volume: numpy.ndarray, ground_truth: numpy.ndarray, image_embeddings: Optional[Dict[str, Any]] = None, start_prompt: str = 'box', start_slice: str = 'center', n_iterations: int = 8, correction: str = 'box_and_points', use_previous_mask: bool = False, projection: Union[str, dict] = 'mask', iou_threshold: float = 0.8, box_extension: float = 0.025, seed: Optional[int] = None, verbose: bool = False) -> List[numpy.ndarray]:
448def evaluate_interactive_volume_segmentation(
449    predictor,
450    volume: np.ndarray,
451    ground_truth: np.ndarray,
452    image_embeddings: Optional[util.ImageEmbeddings] = None,
453    start_prompt: str = "box",
454    start_slice: str = "center",
455    n_iterations: int = 8,
456    correction: str = "box_and_points",
457    use_previous_mask: bool = False,
458    projection: Union[str, dict] = "mask",
459    iou_threshold: float = 0.8,
460    box_extension: float = 0.025,
461    seed: Optional[int] = None,
462    verbose: bool = False,
463) -> List[np.ndarray]:
464    """Segment every object of a volume with iterative prompts, as a user of the 3d annotator does.
465
466    The function prompts each object on one slice and projects the result through the volume.
467    Each later iteration corrects the slice with the largest error. Then the function segments the object
468    again from all prompts so far. A leak beyond the object gets a stop slice instead of a prompt.
469
470    Args:
471        predictor: The segment anything predictor.
472        volume: The input volume, with the shape (Z, Y, X).
473        ground_truth: The instance labels of the volume. The function derives the prompts from them.
474        image_embeddings: The precomputed embeddings of the volume. The function computes them if you do not pass them.
475        start_prompt: The first prompt of an object: 'box', 'points' (a positive click) or 'box_and_points'.
476        start_slice: The slice of the object that gets the first prompt: 'begin', 'center', 'end' or 'random'.
477        n_iterations: The number of iterations, which includes the first prompt.
478        correction: The prompt on the worst slice: 'box', 'points' (a positive and a negative click) or
479            'box_and_points'. If the slice already has the ground-truth box, 'box' adds clicks instead.
480        use_previous_mask: Whether to pass the previous prediction of a prompted slice as a mask prompt.
481        projection: The projection from slice to slice, see `segment_mask_in_volume`.
482        iou_threshold: The IoU between neighbouring slices below which the projection stops.
483        box_extension: The extension of the projected box, see `segment_mask_in_volume`.
484        seed: The seed for the 'random' start slice.
485        verbose: Whether to show the progress.
486
487    Returns:
488        The instance segmentation after each iteration.
489    """
490    if start_prompt not in PROMPT_CHOICES or correction not in PROMPT_CHOICES:
491        raise ValueError(f"The prompts '{start_prompt}' and '{correction}' must be one of {PROMPT_CHOICES}.")
492    if start_slice not in START_SLICE_CHOICES:
493        raise ValueError(f"The start slice '{start_slice}' must be one of {START_SLICE_CHOICES}.")
494
495    if image_embeddings is None:
496        image_embeddings = precompute_image_embeddings(predictor, volume, ndim=3, verbose=verbose)
497    rng = np.random.default_rng(seed)
498    z_index = np.arange(volume.shape[0])
499
500    segmentations = [np.zeros(ground_truth.shape, dtype="uint32") for _ in range(n_iterations)]
501    for label_id in tqdm(np.setdiff1d(np.unique(ground_truth), [0]), desc="Segment objects", disable=not verbose):
502        gt = ground_truth == label_id
503        z_values = np.where(gt.any(axis=(1, 2)))[0]
504        if start_slice == "random":
505            z = int(rng.choice(z_values))
506        else:
507            z = int(z_values[{"begin": 0, "center": len(z_values) // 2, "end": -1}[start_slice]])
508
509        anchors, stops, pred = {}, {"lower": None, "upper": None}, None
510        _add_prompts(anchors.setdefault(z, _new_anchor()), gt[z], np.zeros_like(gt[z]), start_prompt)
511
512        for segmentation in segmentations:
513            if pred is not None:
514                # A stop works only beyond the outermost prompts, so skip the empty slices between them.
515                errors = (gt != pred).sum(axis=(1, 2))
516                errors[~gt.any(axis=(1, 2)) & (z_index > min(anchors)) & (z_index < max(anchors))] = 0
517                z = int(np.argmax(errors))
518                if errors[z] == 0:
519                    segmentation[pred] = label_id
520                    continue
521
522                if gt[z].any():
523                    _add_prompts(anchors.setdefault(z, _new_anchor()), gt[z], pred[z], correction)
524                else:
525                    stops["lower" if z < min(anchors) else "upper"] = z
526                # A new prompt beyond a stop removes the stop.
527                if stops["lower"] is not None and stops["lower"] > min(anchors):
528                    stops["lower"] = None
529                if stops["upper"] is not None and stops["upper"] < max(anchors):
530                    stops["upper"] = None
531
532            # Prompts that did not change give the same mask, so only the changed slices run SAM again.
533            seg = np.zeros(gt.shape, dtype="uint32")
534            for z, anchor in anchors.items():
535                if anchor["mask"] is None or (use_previous_mask and pred is not None):
536                    previous = pred[z] if use_previous_mask and pred is not None else None
537                    anchor["mask"] = _segment_anchor(predictor, image_embeddings, z, anchor, previous)
538                seg[z] = anchor["mask"]
539
540            slices = np.array(sorted(set(anchors) | {s for s in stops.values() if s is not None}))
541            seg, _ = segment_mask_in_volume(
542                seg, predictor, image_embeddings, slices,
543                stop_lower=stops["lower"] is not None, stop_upper=stops["upper"] is not None,
544                iou_threshold=iou_threshold, projection=projection, box_extension=box_extension,
545            )
546            pred = seg == 1
547            segmentation[pred] = label_id
548
549    return segmentations

Segment every object of a volume with iterative prompts, as a user of the 3d annotator does.

The function prompts each object on one slice and projects the result through the volume. Each later iteration corrects the slice with the largest error. Then the function segments the object again from all prompts so far. A leak beyond the object gets a stop slice instead of a prompt.

Arguments:
  • predictor: The segment anything predictor.
  • volume: The input volume, with the shape (Z, Y, X).
  • ground_truth: The instance labels of the volume. The function derives the prompts from them.
  • image_embeddings: The precomputed embeddings of the volume. The function computes them if you do not pass them.
  • start_prompt: The first prompt of an object: 'box', 'points' (a positive click) or 'box_and_points'.
  • start_slice: The slice of the object that gets the first prompt: 'begin', 'center', 'end' or 'random'.
  • n_iterations: The number of iterations, which includes the first prompt.
  • correction: The prompt on the worst slice: 'box', 'points' (a positive and a negative click) or 'box_and_points'. If the slice already has the ground-truth box, 'box' adds clicks instead.
  • use_previous_mask: Whether to pass the previous prediction of a prompted slice as a mask prompt.
  • projection: The projection from slice to slice, see segment_mask_in_volume.
  • iou_threshold: The IoU between neighbouring slices below which the projection stops.
  • box_extension: The extension of the projected box, see segment_mask_in_volume.
  • seed: The seed for the 'random' start slice.
  • verbose: Whether to show the progress.
Returns:

The instance segmentation after each iteration.