micro_sam.v1.evaluation.inference

Inference with Segment Anything models and different prompt strategies.

  1"""Inference with Segment Anything models and different prompt strategies.
  2"""
  3
  4import os
  5import pickle
  6from copy import deepcopy
  7from typing import Any, Dict, List, Optional, Union, Tuple
  8
  9import numpy as np
 10from tqdm import tqdm
 11import imageio.v3 as imageio
 12from segment_anything import SamPredictor
 13
 14import torch
 15
 16from bioimage_cpp.segmentation import label as connected_components, relabel_sequential
 17
 18from ... import util as util
 19from . import instance_segmentation
 20from ..inference import batched_inference
 21from ..util import get_sam_model, precompute_image_embeddings
 22from ...prompt_generators import CenterIterativePromptGenerator, PointAndBoxPromptGenerator, IterativePromptGenerator
 23from ..instance_segmentation import (
 24    get_predictor_and_decoder,
 25    AutomaticMaskGenerator, InstanceSegmentationWithDecoder,
 26    TiledAutomaticMaskGenerator, TiledInstanceSegmentationWithDecoder,
 27    AutomaticPromptGenerator,
 28)
 29
 30
 31def _load_prompts(
 32    cached_point_prompts, save_point_prompts, cached_box_prompts, save_box_prompts, image_name
 33):
 34
 35    def load_prompt_type(cached_prompts, save_prompts):
 36        # Check if we have saved prompts.
 37        if cached_prompts is None or save_prompts:  # we don't have cached prompts
 38            return cached_prompts, None
 39
 40        # we have cached prompts, but they have not been loaded yet
 41        if isinstance(cached_prompts, str):
 42            with open(cached_prompts, "rb") as f:
 43                cached_prompts = pickle.load(f)
 44
 45        prompts = cached_prompts[image_name]
 46        return cached_prompts, prompts
 47
 48    cached_point_prompts, point_prompts = load_prompt_type(cached_point_prompts, save_point_prompts)
 49    cached_box_prompts, box_prompts = load_prompt_type(cached_box_prompts, save_box_prompts)
 50
 51    # we don't have anything cached
 52    if point_prompts is None and box_prompts is None:
 53        return None, cached_point_prompts, cached_box_prompts
 54
 55    if point_prompts is None:
 56        input_point, input_label = [], []
 57    else:
 58        input_point, input_label = point_prompts
 59
 60    if box_prompts is None:
 61        input_box = []
 62    else:
 63        input_box = box_prompts
 64
 65    prompts = (input_point, input_label, input_box)
 66    return prompts, cached_point_prompts, cached_box_prompts
 67
 68
 69def _get_batched_prompts(gt, gt_ids, use_points, use_boxes, n_positives, n_negatives, dilation):
 70
 71    # Initialize the prompt generator.
 72    prompt_generator = PointAndBoxPromptGenerator(
 73        n_positive_points=n_positives, n_negative_points=n_negatives,
 74        dilation_strength=dilation, get_point_prompts=use_points,
 75        get_box_prompts=use_boxes
 76    )
 77
 78    # Generate the prompts.
 79    center_coordinates, bbox_coordinates = util.get_centers_and_bounding_boxes(gt)
 80    center_coordinates = [center_coordinates[gt_id] for gt_id in gt_ids]
 81    bbox_coordinates = [bbox_coordinates[gt_id] for gt_id in gt_ids]
 82    masks = util.segmentation_to_one_hot(gt.astype("int64"), gt_ids)
 83
 84    points, point_labels, boxes, _ = prompt_generator(
 85        masks, bbox_coordinates, center_coordinates
 86    )
 87
 88    def to_numpy(x):
 89        if x is None:
 90            return x
 91        return x.numpy()
 92
 93    return to_numpy(points), to_numpy(point_labels), to_numpy(boxes)
 94
 95
 96def _run_inference_with_prompts_for_image(
 97    predictor,
 98    image,
 99    gt,
100    use_points,
101    use_boxes,
102    n_positives,
103    n_negatives,
104    dilation,
105    batch_size,
106    cached_prompts,
107    embedding_path,
108):
109    gt_ids = np.unique(gt)[1:]
110    if cached_prompts is None:
111        points, point_labels, boxes = _get_batched_prompts(
112            gt, gt_ids, use_points, use_boxes, n_positives, n_negatives, dilation
113        )
114    else:
115        points, point_labels, boxes = cached_prompts
116
117    # Make a copy of the point prompts to return them at the end.
118    prompts = deepcopy((points, point_labels, boxes))
119
120    # Use multi-masking only if we have a single positive point without box
121    multimasking = False
122    if not use_boxes and (n_positives == 1 and n_negatives == 0):
123        multimasking = True
124
125    instance_labels = batched_inference(
126        predictor, image, batch_size,
127        boxes=boxes, points=points, point_labels=point_labels,
128        multimasking=multimasking, embedding_path=embedding_path,
129        return_instance_segmentation=True,
130    )
131
132    return instance_labels, prompts
133
134
135def precompute_all_embeddings(
136    predictor: SamPredictor, image_paths: List[Union[str, os.PathLike]], embedding_dir: Union[str, os.PathLike],
137) -> None:
138    """Precompute all image embeddings.
139
140    To enable running different inference tasks in parallel afterwards.
141
142    Args:
143        predictor: The Segment Anything predictor.
144        image_paths: The image file paths.
145        embedding_dir: The directory where the embeddings will be saved.
146    """
147    for image_path in tqdm(image_paths, desc="Precompute embeddings"):
148        image_name = os.path.basename(image_path)
149        im = imageio.imread(image_path)
150        embedding_path = os.path.join(embedding_dir, f"{os.path.splitext(image_name)[0]}.zarr")
151        precompute_image_embeddings(predictor, im, embedding_path, ndim=2)
152
153
154def _precompute_prompts(gt_path, use_points, use_boxes, n_positives, n_negatives, dilation):
155    name = os.path.basename(gt_path)
156
157    gt = imageio.imread(gt_path).astype("uint32")
158    gt = relabel_sequential(gt)[0]
159    gt_ids = np.unique(gt)[1:]
160
161    input_point, input_label, input_box = _get_batched_prompts(
162        gt, gt_ids, use_points, use_boxes, n_positives, n_negatives, dilation
163    )
164
165    if use_boxes and not use_points:
166        return name, input_box
167    return name, (input_point, input_label)
168
169
170def precompute_all_prompts(
171    gt_paths: List[Union[str, os.PathLike]],
172    prompt_save_dir: Union[str, os.PathLike],
173    prompt_settings: List[Dict[str, Any]],
174) -> None:
175    """Precompute all point prompts.
176
177    To enable running different inference tasks in parallel afterwards.
178
179    Args:
180        gt_paths: The file paths to the ground-truth segmentations.
181        prompt_save_dir: The directory where the prompt files will be saved.
182        prompt_settings: The settings for which the prompts will be computed.
183    """
184    os.makedirs(prompt_save_dir, exist_ok=True)
185
186    for settings in tqdm(prompt_settings, desc="Precompute prompts"):
187
188        use_points, use_boxes = settings["use_points"], settings["use_boxes"]
189        n_positives, n_negatives = settings["n_positives"], settings["n_negatives"]
190        dilation = settings.get("dilation", 5)
191
192        # check if the prompts were already computed
193        if use_boxes and not use_points:
194            prompt_save_path = os.path.join(prompt_save_dir, "boxes.pkl")
195        else:
196            prompt_save_path = os.path.join(prompt_save_dir, f"points-p{n_positives}-n{n_negatives}.pkl")
197        if os.path.exists(prompt_save_path):
198            continue
199
200        results = []
201        for gt_path in tqdm(gt_paths, desc=f"Precompute prompts for p{n_positives}-n{n_negatives}"):
202            prompts = _precompute_prompts(
203                gt_path,
204                use_points=use_points,
205                use_boxes=use_boxes,
206                n_positives=n_positives,
207                n_negatives=n_negatives,
208                dilation=dilation,
209            )
210            results.append(prompts)
211
212        saved_prompts = {res[0]: res[1] for res in results}
213        with open(prompt_save_path, "wb") as f:
214            pickle.dump(saved_prompts, f)
215
216
217def _get_prompt_caching(prompt_save_dir, use_points, use_boxes, n_positives, n_negatives):
218
219    def get_prompt_type_caching(use_type, save_name):
220        if not use_type:
221            return None, False, None
222
223        prompt_save_path = os.path.join(prompt_save_dir, save_name)
224        if os.path.exists(prompt_save_path):
225            print("Using precomputed prompts from", prompt_save_path)
226            # We delay loading the prompts, so we only have to load them once they're needed the first time.
227            # This avoids loading the prompts (which are in a big pickle file) if all predictions are done already.
228            cached_prompts = prompt_save_path
229            save_prompts = False
230        else:
231            print("Saving prompts in", prompt_save_path)
232            cached_prompts = {}
233            save_prompts = True
234        return cached_prompts, save_prompts, prompt_save_path
235
236    # Check if prompt serialization is enabled.
237    # If it is then load the prompts if they are already cached and otherwise store them.
238    if prompt_save_dir is None:
239        print("Prompts are not cached.")
240        cached_point_prompts, cached_box_prompts = None, None
241        save_point_prompts, save_box_prompts = False, False
242        point_prompt_save_path, box_prompt_save_path = None, None
243    else:
244        cached_point_prompts, save_point_prompts, point_prompt_save_path = get_prompt_type_caching(
245            use_points, f"points-p{n_positives}-n{n_negatives}.pkl"
246        )
247        cached_box_prompts, save_box_prompts, box_prompt_save_path = get_prompt_type_caching(
248            use_boxes, "boxes.pkl"
249        )
250
251    return (
252        cached_point_prompts, save_point_prompts, point_prompt_save_path,
253        cached_box_prompts, save_box_prompts, box_prompt_save_path
254    )
255
256
257def run_inference_with_prompts(
258    predictor: SamPredictor,
259    image_paths: List[Union[str, os.PathLike]],
260    gt_paths: List[Union[str, os.PathLike]],
261    embedding_dir: Union[str, os.PathLike],
262    prediction_dir: Union[str, os.PathLike],
263    use_points: bool,
264    use_boxes: bool,
265    n_positives: int,
266    n_negatives: int,
267    dilation: int = 5,
268    prompt_save_dir: Optional[Union[str, os.PathLike]] = None,
269    batch_size: int = 512,
270) -> None:
271    """Run segment anything inference for multiple images using prompts derived from groundtruth.
272
273    Args:
274        predictor: The Segment Anything predictor.
275        image_paths: The image file paths.
276        gt_paths: The ground-truth segmentation file paths.
277        embedding_dir: The directory where the image embddings will be saved or are already saved.
278        use_points: Whether to use point prompts.
279        use_boxes: Whether to use box prompts
280        n_positives: The number of positive point prompts that will be sampled.
281        n_negativess: The number of negative point prompts that will be sampled.
282        dilation: The dilation factor for the radius around the ground-truth object
283            around which points will not be sampled.
284        prompt_save_dir: The directory where point prompts will be saved or are already saved.
285            This enables running multiple experiments in a reproducible manner.
286        batch_size: The batch size used for batched prediction.
287    """
288    if not (use_points or use_boxes):
289        raise ValueError("You need to use at least one of point or box prompts.")
290
291    if len(image_paths) != len(gt_paths):
292        raise ValueError(f"Expect same number of images and gt images, got {len(image_paths)}, {len(gt_paths)}")
293
294    (
295        cached_point_prompts, save_point_prompts, point_prompt_save_path,
296        cached_box_prompts, save_box_prompts, box_prompt_save_path
297    ) = _get_prompt_caching(
298         prompt_save_dir, use_points, use_boxes, n_positives, n_negatives
299     )
300
301    os.makedirs(prediction_dir, exist_ok=True)
302    for image_path, gt_path in tqdm(
303        zip(image_paths, gt_paths), total=len(image_paths), desc="Run inference with prompts"
304    ):
305        image_name = os.path.basename(image_path)
306        label_name = os.path.basename(gt_path)
307
308        # We skip the images that already have been segmented.
309        prediction_path = os.path.join(prediction_dir, image_name)
310        if os.path.exists(prediction_path):
311            continue
312
313        assert os.path.exists(image_path), image_path
314        assert os.path.exists(gt_path), gt_path
315
316        im = imageio.imread(image_path)
317        gt = imageio.imread(gt_path).astype("uint32")
318        gt = relabel_sequential(gt)[0]
319
320        embedding_path = os.path.join(embedding_dir, f"{os.path.splitext(image_name)[0]}.zarr")
321        this_prompts, cached_point_prompts, cached_box_prompts = _load_prompts(
322            cached_point_prompts, save_point_prompts,
323            cached_box_prompts, save_box_prompts,
324            label_name
325        )
326        instances, this_prompts = _run_inference_with_prompts_for_image(
327            predictor, im, gt, n_positives=n_positives, n_negatives=n_negatives,
328            dilation=dilation, use_points=use_points, use_boxes=use_boxes,
329            batch_size=batch_size, cached_prompts=this_prompts,
330            embedding_path=embedding_path,
331        )
332
333        if save_point_prompts:
334            cached_point_prompts[label_name] = this_prompts[:2]
335        if save_box_prompts:
336            cached_box_prompts[label_name] = this_prompts[-1]
337
338        # It's important to compress here, otherwise the predictions would take up a lot of space.
339        imageio.imwrite(prediction_path, instances, compression=5)
340
341    # Save the prompts if we run experiments with prompt caching and have computed them
342    # for the first time.
343    if save_point_prompts:
344        with open(point_prompt_save_path, "wb") as f:
345            pickle.dump(cached_point_prompts, f)
346    if save_box_prompts:
347        with open(box_prompt_save_path, "wb") as f:
348            pickle.dump(cached_box_prompts, f)
349
350
351def _save_segmentation(masks, prediction_path):
352    # masks to segmentation
353    masks = masks.cpu().numpy().squeeze(1).astype("bool")
354    masks = [{"segmentation": mask, "area": mask.sum()} for mask in masks]
355    # One mask per object already, so connected components would only merge touching objects.
356    segmentation = util.mask_data_to_segmentation(masks, label_masks=False)
357    imageio.imwrite(prediction_path, segmentation, compression=5)
358
359
360def _get_batched_iterative_prompts(sampled_binary_gt, masks, batch_size, prompt_generator):
361    n_samples = sampled_binary_gt.shape[0]
362    n_batches = int(np.ceil(float(n_samples) / batch_size))
363    next_coords, next_labels = [], []
364    for batch_idx in range(n_batches):
365        batch_start = batch_idx * batch_size
366        batch_stop = min((batch_idx + 1) * batch_size, n_samples)
367
368        batch_coords, batch_labels, _, _ = prompt_generator(
369            sampled_binary_gt[batch_start: batch_stop], masks[batch_start: batch_stop]
370        )
371        next_coords.append(batch_coords)
372        next_labels.append(batch_labels)
373
374    next_coords = torch.concatenate(next_coords)
375    next_labels = torch.concatenate(next_labels)
376
377    return next_coords, next_labels
378
379
380@torch.no_grad()
381def _run_inference_with_iterative_prompting_for_image(
382    predictor,
383    image,
384    gt,
385    start_with_box_prompt,
386    dilation,
387    batch_size,
388    embedding_path,
389    n_iterations,
390    prediction_paths,
391    use_masks=False,
392    click_protocol="random",
393) -> None:
394    if click_protocol not in ("random", "center"):
395        raise ValueError(f"Invalid click protocol '{click_protocol}', choose 'random' or 'center'.")
396    verbose_embeddings = False
397
398    prompt_generator = CenterIterativePromptGenerator() if click_protocol == "center" else IterativePromptGenerator()
399
400    gt_ids = np.setdiff1d(np.unique(gt), [0])
401
402    # Use multi-masking only if we have a single positive point without box
403    if start_with_box_prompt:
404        use_boxes, use_points = True, False
405        n_positives = 0
406        multimasking = False
407    else:
408        use_boxes, use_points = False, True
409        n_positives = 1
410        multimasking = click_protocol == "random"
411
412    points, point_labels, boxes = _get_batched_prompts(
413        gt, gt_ids,
414        use_points=use_points,
415        use_boxes=use_boxes,
416        n_positives=n_positives,
417        n_negatives=0,
418        dilation=dilation
419    )
420
421    sampled_binary_gt = util.segmentation_to_one_hot(gt.astype("int64"), gt_ids)
422
423    for iteration in range(n_iterations):
424        if iteration == 0:  # logits mask can not be used for the first iteration.
425            logits_masks = None
426        else:
427            if not use_masks:  # logits mask should not be used when not desired.
428                logits_masks = None
429
430        batched_outputs = batched_inference(
431            predictor=predictor,
432            image=image,
433            batch_size=batch_size,
434            boxes=boxes,
435            points=points,
436            point_labels=point_labels,
437            multimasking=multimasking,
438            embedding_path=embedding_path,
439            return_instance_segmentation=False,
440            logits_masks=logits_masks,
441            verbose_embeddings=verbose_embeddings,
442        )
443
444        # switching off multimasking after first iter, as next iters (with multiple prompts) don't expect multimasking
445        multimasking = False
446
447        # The masks are stacked on the CPU: the prompt generators move them there anyway, and many objects in a
448        # large image do not fit on the GPU.
449        masks = torch.stack([m["segmentation"][None].cpu() for m in batched_outputs]).to(torch.float32)
450
451        next_coords, next_labels = _get_batched_iterative_prompts(
452            sampled_binary_gt, masks, batch_size, prompt_generator
453        )
454        next_coords, next_labels = next_coords.detach().cpu().numpy(), next_labels.detach().cpu().numpy()
455
456        if points is not None:
457            points = np.concatenate([points, next_coords], axis=1)
458        else:
459            points = next_coords
460
461        if point_labels is not None:
462            point_labels = np.concatenate([point_labels, next_labels], axis=1)
463        else:
464            point_labels = next_labels
465
466        if use_masks:
467            logits_masks = torch.stack([m["logits"] for m in batched_outputs])
468
469        _save_segmentation(masks, prediction_paths[iteration])
470
471
472def run_inference_with_iterative_prompting(
473    predictor: SamPredictor,
474    image_paths: List[Union[str, os.PathLike]],
475    gt_paths: List[Union[str, os.PathLike]],
476    embedding_dir: Union[str, os.PathLike],
477    prediction_dir: Union[str, os.PathLike],
478    start_with_box_prompt: bool = True,
479    dilation: int = 5,
480    batch_size: int = 32,
481    n_iterations: int = 8,
482    use_masks: bool = False,
483    click_protocol: str = "random",
484) -> None:
485    """Run Segment Anything inference for multiple images using prompts iteratively
486    derived from model outputs and ground-truth.
487
488    Args:
489        predictor: The Segment Anything predictor.
490        image_paths: The image file paths.
491        gt_paths: The ground-truth segmentation file paths.
492        embedding_dir: The directory where the image embeddings will be saved or are already saved.
493        prediction_dir: The directory where the predictions from Segment Anything will be saved per iteration.
494        start_with_box_prompt: Whether to use the first prompt as bounding box or a single point
495        dilation: The dilation factor for the radius around the ground-truth object
496            around which points will not be sampled.
497        batch_size: The batch size used for batched predictions.
498        n_iterations: The number of iterations for iterative prompting.
499        use_masks: Whether to make use of logits from previous prompt-based segmentation.
500        click_protocol: The correction clicks. 'random' samples them at random positions in the error regions
501            and picks the best of 3 masks for a first point prompt. 'center' places them at the centers of the
502            largest error regions and predicts a single mask for a first point prompt.
503    """
504    if len(image_paths) != len(gt_paths):
505        raise ValueError(f"Expect same number of images and gt images, got {len(image_paths)}, {len(gt_paths)}")
506
507    # create all prediction folders for all intermediate iterations
508    for i in range(n_iterations):
509        os.makedirs(os.path.join(prediction_dir, f"iteration{i:02}"), exist_ok=True)
510
511    if use_masks:
512        print("The iterative prompting will make use of logits masks from previous iterations.")
513
514    for image_path, gt_path in tqdm(
515        zip(image_paths, gt_paths), total=len(image_paths),
516        desc="Run inference with iterative prompting for all images",
517    ):
518        image_name = os.path.basename(image_path)
519
520        # We skip the images that already have been segmented
521        prediction_paths = [os.path.join(prediction_dir, f"iteration{i:02}", image_name) for i in range(n_iterations)]
522        if all(os.path.exists(prediction_path) for prediction_path in prediction_paths):
523            continue
524
525        assert os.path.exists(image_path), image_path
526        assert os.path.exists(gt_path), gt_path
527
528        image = imageio.imread(image_path)
529        gt = imageio.imread(gt_path).astype("uint32")
530        # The objects that get prompted are the connected components of the labels, as in the micro-sam2
531        # evaluation, so that both prompt the same objects.
532        gt = connected_components(gt).astype("uint32")
533
534        if embedding_dir is None:
535            embedding_path = None
536        else:
537            embedding_path = os.path.join(embedding_dir, f"{os.path.splitext(image_name)[0]}.zarr")
538
539        _run_inference_with_iterative_prompting_for_image(
540            predictor, image, gt, start_with_box_prompt=start_with_box_prompt,
541            dilation=dilation, batch_size=batch_size, embedding_path=embedding_path,
542            n_iterations=n_iterations, prediction_paths=prediction_paths, use_masks=use_masks,
543            click_protocol=click_protocol,
544        )
545
546
547#
548# AMG FUNCTION
549#
550
551
552def run_amg(
553    checkpoint: Union[str, os.PathLike],
554    model_type: str,
555    experiment_folder: Union[str, os.PathLike],
556    val_image_paths: List[Union[str, os.PathLike]],
557    val_gt_paths: List[Union[str, os.PathLike]],
558    test_image_paths: List[Union[str, os.PathLike]],
559    iou_thresh_values: Optional[List[float]] = None,
560    stability_score_values: Optional[List[float]] = None,
561    peft_kwargs: Optional[Dict] = None,
562    cache_embeddings: bool = False,
563    tiling_window_params: Optional[Dict[str, Tuple[int, int]]] = None,
564) -> str:
565    """Run Segment Anything inference for multiple images using automatic mask generation (AMG).
566
567    Args:
568        checkpoint: The filepath to model checkpoints.
569        model_type: The segment anything model choice.
570        experimet_folder: The directory where the relevant files are saved.
571        val_image_paths: The list of filepaths of input images for grid-search.
572        val_gt_paths: The list of filepaths of corresponding labels for grid-search.
573        test_image_paths: The list of filepaths of input images for automatic instance segmentation.
574        iou_thresh_values: Optional choice of values for grid search of `iou_thresh` parameter.
575        stability_score_values: Optional choice of values for grid search of `stability_score` parameter.
576        peft_kwargs: Keyword arguments for th PEFT wrapper class.
577        cache_embeddings: Whether to cache embeddings in experiment folder.
578        tiling_window_params: The parameters to decide whether to use tiling window operation for AIS.
579
580    Returns:
581        Filepath where the predictions have been saved.
582    """
583
584    if cache_embeddings:
585        embedding_folder = os.path.join(experiment_folder, "embeddings")  # where the precomputed embeddings are saved
586        os.makedirs(embedding_folder, exist_ok=True)
587    else:
588        embedding_folder = None
589
590    predictor = get_sam_model(model_type=model_type, checkpoint_path=checkpoint, peft_kwargs=peft_kwargs)
591
592    # Get the AMG class.
593    if tiling_window_params:
594        if not isinstance(tiling_window_params, dict):
595            raise RuntimeError("The tiling window parameters are expected to be provided as a dictionary of params.")
596
597        if "tile_shape" not in tiling_window_params:
598            raise RuntimeError("'tile_shape' parameter is missing from the provided parameters.")
599
600        if "halo" not in tiling_window_params:
601            raise RuntimeError("'halo' parameter is missing from the provided parameters.")
602
603        amg_class = TiledAutomaticMaskGenerator
604    else:
605        amg_class = AutomaticMaskGenerator
606
607    amg = amg_class(predictor)
608    amg_prefix = "amg"
609
610    # where the predictions are saved
611    prediction_folder = os.path.join(experiment_folder, amg_prefix, "inference")
612    os.makedirs(prediction_folder, exist_ok=True)
613
614    # where the grid-search results are saved
615    gs_result_folder = os.path.join(experiment_folder, amg_prefix, "grid_search")
616    os.makedirs(gs_result_folder, exist_ok=True)
617
618    grid_search_values = instance_segmentation.default_grid_search_values_amg(
619        iou_thresh_values=iou_thresh_values,
620        stability_score_values=stability_score_values,
621    )
622
623    instance_segmentation.run_instance_segmentation_grid_search_and_inference(
624        segmenter=amg,
625        grid_search_values=grid_search_values,
626        val_image_paths=val_image_paths,
627        val_gt_paths=val_gt_paths,
628        test_image_paths=test_image_paths,
629        embedding_dir=embedding_folder,
630        prediction_dir=prediction_folder,
631        result_dir=gs_result_folder,
632        experiment_folder=experiment_folder,
633        tiling_window_params=tiling_window_params,
634    )
635    return prediction_folder
636
637
638def run_apg(
639    checkpoint: Optional[Union[str, os.PathLike]],
640    model_type: str,
641    experiment_folder: Union[str, os.PathLike],
642    val_image_paths: List[Union[str, os.PathLike]],
643    val_gt_paths: List[Union[str, os.PathLike]],
644    test_image_paths: List[Union[str, os.PathLike]],
645    peft_kwargs: Optional[Dict] = None,
646    cache_embeddings: bool = False,
647    tiling_window_params: Optional[Dict[str, Tuple[int, int]]] = None,
648) -> str:
649    """Run Segment Anything inference for multiple images using automatic prompt generation (APG).
650
651    Args:
652        ...
653
654    Returns:
655        Filepath where the predictions have been saved.
656    """
657    if cache_embeddings:
658        embedding_folder = os.path.join(experiment_folder, "embeddings")  # where the precomputed embeddings are saved
659        os.makedirs(embedding_folder, exist_ok=True)
660    else:
661        embedding_folder = None
662
663    predictor, decoder = get_predictor_and_decoder(
664        model_type=model_type, checkpoint_path=checkpoint, peft_kwargs=peft_kwargs,
665    )
666
667    # Get the APG class.
668    if tiling_window_params:
669        raise NotImplementedError
670    else:
671        apg_class = AutomaticPromptGenerator
672
673    segmenter = apg_class(predictor, decoder)
674    seg_prefix = "apg"
675
676    # where the predictions are saved
677    prediction_folder = os.path.join(experiment_folder, seg_prefix, "inference")
678    os.makedirs(prediction_folder, exist_ok=True)
679
680    # where the grid-search results are saved
681    gs_result_folder = os.path.join(experiment_folder, seg_prefix, "grid_search")
682    os.makedirs(gs_result_folder, exist_ok=True)
683
684    grid_search_values = instance_segmentation.default_grid_search_values_apg()
685
686    instance_segmentation.run_instance_segmentation_grid_search_and_inference(
687        segmenter=segmenter,
688        grid_search_values=grid_search_values,
689        val_image_paths=val_image_paths,
690        val_gt_paths=val_gt_paths,
691        test_image_paths=test_image_paths,
692        embedding_dir=embedding_folder,
693        prediction_dir=prediction_folder,
694        result_dir=gs_result_folder,
695        experiment_folder=experiment_folder,
696        tiling_window_params=tiling_window_params,
697    )
698    return prediction_folder
699
700
701#
702# INSTANCE SEGMENTATION FUNCTION
703#
704
705
706def run_instance_segmentation_with_decoder(
707    checkpoint: Union[str, os.PathLike],
708    model_type: str,
709    experiment_folder: Union[str, os.PathLike],
710    val_image_paths: List[Union[str, os.PathLike]],
711    val_gt_paths: List[Union[str, os.PathLike]],
712    test_image_paths: List[Union[str, os.PathLike]],
713    peft_kwargs: Optional[Dict] = None,
714    cache_embeddings: bool = False,
715    tiling_window_params: Optional[Dict[str, Tuple[int, int]]] = None,
716) -> str:
717    """Run Segment Anything inference for multiple images using additional automatic instance segmentation (AIS).
718
719    Args:
720        checkpoint: The filepath to model checkpoints.
721        model_type: The segment anything model choice.
722        experimet_folder: The directory where the relevant files are saved.
723        val_image_paths: The list of filepaths of input images for grid-search.
724        val_gt_paths: The list of filepaths of corresponding labels for grid-search.
725        test_image_paths: The list of filepaths of input images for automatic instance segmentation.
726        peft_kwargs: Keyword arguments for th PEFT wrapper class.
727        cache_embeddings: Whether to cache embeddings in experiment folder.
728        tiling_window_params: The parameters to decide whether to use tiling window operation for AIS.
729
730    Returns:
731        Filepath where the predictions have been saved.
732    """
733
734    if cache_embeddings:
735        embedding_folder = os.path.join(experiment_folder, "embeddings")  # where the precomputed embeddings are saved
736        os.makedirs(embedding_folder, exist_ok=True)
737    else:
738        embedding_folder = None
739
740    predictor, decoder = get_predictor_and_decoder(
741        model_type=model_type, checkpoint_path=checkpoint, peft_kwargs=peft_kwargs,
742    )
743
744    # Get the AIS class.
745    if tiling_window_params:
746        if not isinstance(tiling_window_params, dict):
747            raise RuntimeError("The tiling window parameters are expected to be provided as a dictionary of params.")
748
749        if "tile_shape" not in tiling_window_params:
750            raise RuntimeError("'tile_shape' parameter is missing from the provided parameters.")
751
752        if "halo" not in tiling_window_params:
753            raise RuntimeError("'halo' parameter is missing from the provided parameters.")
754
755        ais_class = TiledInstanceSegmentationWithDecoder
756    else:
757        ais_class = InstanceSegmentationWithDecoder
758
759    segmenter = ais_class(predictor, decoder)
760    seg_prefix = "instance_segmentation_with_decoder"
761
762    # where the predictions are saved
763    prediction_folder = os.path.join(experiment_folder, seg_prefix, "inference")
764    os.makedirs(prediction_folder, exist_ok=True)
765
766    # where the grid-search results are saved
767    gs_result_folder = os.path.join(experiment_folder, seg_prefix, "grid_search")
768    os.makedirs(gs_result_folder, exist_ok=True)
769
770    grid_search_values = instance_segmentation.default_grid_search_values_instance_segmentation_with_decoder()
771
772    instance_segmentation.run_instance_segmentation_grid_search_and_inference(
773        segmenter=segmenter,
774        grid_search_values=grid_search_values,
775        val_image_paths=val_image_paths,
776        val_gt_paths=val_gt_paths,
777        test_image_paths=test_image_paths,
778        embedding_dir=embedding_folder,
779        prediction_dir=prediction_folder,
780        result_dir=gs_result_folder,
781        experiment_folder=experiment_folder,
782        tiling_window_params=tiling_window_params,
783    )
784    return prediction_folder
def precompute_all_embeddings( predictor: segment_anything.predictor.SamPredictor, image_paths: List[Union[str, os.PathLike]], embedding_dir: Union[str, os.PathLike]) -> None:
136def precompute_all_embeddings(
137    predictor: SamPredictor, image_paths: List[Union[str, os.PathLike]], embedding_dir: Union[str, os.PathLike],
138) -> None:
139    """Precompute all image embeddings.
140
141    To enable running different inference tasks in parallel afterwards.
142
143    Args:
144        predictor: The Segment Anything predictor.
145        image_paths: The image file paths.
146        embedding_dir: The directory where the embeddings will be saved.
147    """
148    for image_path in tqdm(image_paths, desc="Precompute embeddings"):
149        image_name = os.path.basename(image_path)
150        im = imageio.imread(image_path)
151        embedding_path = os.path.join(embedding_dir, f"{os.path.splitext(image_name)[0]}.zarr")
152        precompute_image_embeddings(predictor, im, embedding_path, ndim=2)

Precompute all image embeddings.

To enable running different inference tasks in parallel afterwards.

Arguments:
  • predictor: The Segment Anything predictor.
  • image_paths: The image file paths.
  • embedding_dir: The directory where the embeddings will be saved.
def precompute_all_prompts( gt_paths: List[Union[str, os.PathLike]], prompt_save_dir: Union[str, os.PathLike], prompt_settings: List[Dict[str, Any]]) -> None:
171def precompute_all_prompts(
172    gt_paths: List[Union[str, os.PathLike]],
173    prompt_save_dir: Union[str, os.PathLike],
174    prompt_settings: List[Dict[str, Any]],
175) -> None:
176    """Precompute all point prompts.
177
178    To enable running different inference tasks in parallel afterwards.
179
180    Args:
181        gt_paths: The file paths to the ground-truth segmentations.
182        prompt_save_dir: The directory where the prompt files will be saved.
183        prompt_settings: The settings for which the prompts will be computed.
184    """
185    os.makedirs(prompt_save_dir, exist_ok=True)
186
187    for settings in tqdm(prompt_settings, desc="Precompute prompts"):
188
189        use_points, use_boxes = settings["use_points"], settings["use_boxes"]
190        n_positives, n_negatives = settings["n_positives"], settings["n_negatives"]
191        dilation = settings.get("dilation", 5)
192
193        # check if the prompts were already computed
194        if use_boxes and not use_points:
195            prompt_save_path = os.path.join(prompt_save_dir, "boxes.pkl")
196        else:
197            prompt_save_path = os.path.join(prompt_save_dir, f"points-p{n_positives}-n{n_negatives}.pkl")
198        if os.path.exists(prompt_save_path):
199            continue
200
201        results = []
202        for gt_path in tqdm(gt_paths, desc=f"Precompute prompts for p{n_positives}-n{n_negatives}"):
203            prompts = _precompute_prompts(
204                gt_path,
205                use_points=use_points,
206                use_boxes=use_boxes,
207                n_positives=n_positives,
208                n_negatives=n_negatives,
209                dilation=dilation,
210            )
211            results.append(prompts)
212
213        saved_prompts = {res[0]: res[1] for res in results}
214        with open(prompt_save_path, "wb") as f:
215            pickle.dump(saved_prompts, f)

Precompute all point prompts.

To enable running different inference tasks in parallel afterwards.

Arguments:
  • gt_paths: The file paths to the ground-truth segmentations.
  • prompt_save_dir: The directory where the prompt files will be saved.
  • prompt_settings: The settings for which the prompts will be computed.
def run_inference_with_prompts( predictor: segment_anything.predictor.SamPredictor, image_paths: List[Union[str, os.PathLike]], gt_paths: List[Union[str, os.PathLike]], embedding_dir: Union[str, os.PathLike], prediction_dir: Union[str, os.PathLike], use_points: bool, use_boxes: bool, n_positives: int, n_negatives: int, dilation: int = 5, prompt_save_dir: Union[str, os.PathLike, NoneType] = None, batch_size: int = 512) -> None:
258def run_inference_with_prompts(
259    predictor: SamPredictor,
260    image_paths: List[Union[str, os.PathLike]],
261    gt_paths: List[Union[str, os.PathLike]],
262    embedding_dir: Union[str, os.PathLike],
263    prediction_dir: Union[str, os.PathLike],
264    use_points: bool,
265    use_boxes: bool,
266    n_positives: int,
267    n_negatives: int,
268    dilation: int = 5,
269    prompt_save_dir: Optional[Union[str, os.PathLike]] = None,
270    batch_size: int = 512,
271) -> None:
272    """Run segment anything inference for multiple images using prompts derived from groundtruth.
273
274    Args:
275        predictor: The Segment Anything predictor.
276        image_paths: The image file paths.
277        gt_paths: The ground-truth segmentation file paths.
278        embedding_dir: The directory where the image embddings will be saved or are already saved.
279        use_points: Whether to use point prompts.
280        use_boxes: Whether to use box prompts
281        n_positives: The number of positive point prompts that will be sampled.
282        n_negativess: The number of negative point prompts that will be sampled.
283        dilation: The dilation factor for the radius around the ground-truth object
284            around which points will not be sampled.
285        prompt_save_dir: The directory where point prompts will be saved or are already saved.
286            This enables running multiple experiments in a reproducible manner.
287        batch_size: The batch size used for batched prediction.
288    """
289    if not (use_points or use_boxes):
290        raise ValueError("You need to use at least one of point or box prompts.")
291
292    if len(image_paths) != len(gt_paths):
293        raise ValueError(f"Expect same number of images and gt images, got {len(image_paths)}, {len(gt_paths)}")
294
295    (
296        cached_point_prompts, save_point_prompts, point_prompt_save_path,
297        cached_box_prompts, save_box_prompts, box_prompt_save_path
298    ) = _get_prompt_caching(
299         prompt_save_dir, use_points, use_boxes, n_positives, n_negatives
300     )
301
302    os.makedirs(prediction_dir, exist_ok=True)
303    for image_path, gt_path in tqdm(
304        zip(image_paths, gt_paths), total=len(image_paths), desc="Run inference with prompts"
305    ):
306        image_name = os.path.basename(image_path)
307        label_name = os.path.basename(gt_path)
308
309        # We skip the images that already have been segmented.
310        prediction_path = os.path.join(prediction_dir, image_name)
311        if os.path.exists(prediction_path):
312            continue
313
314        assert os.path.exists(image_path), image_path
315        assert os.path.exists(gt_path), gt_path
316
317        im = imageio.imread(image_path)
318        gt = imageio.imread(gt_path).astype("uint32")
319        gt = relabel_sequential(gt)[0]
320
321        embedding_path = os.path.join(embedding_dir, f"{os.path.splitext(image_name)[0]}.zarr")
322        this_prompts, cached_point_prompts, cached_box_prompts = _load_prompts(
323            cached_point_prompts, save_point_prompts,
324            cached_box_prompts, save_box_prompts,
325            label_name
326        )
327        instances, this_prompts = _run_inference_with_prompts_for_image(
328            predictor, im, gt, n_positives=n_positives, n_negatives=n_negatives,
329            dilation=dilation, use_points=use_points, use_boxes=use_boxes,
330            batch_size=batch_size, cached_prompts=this_prompts,
331            embedding_path=embedding_path,
332        )
333
334        if save_point_prompts:
335            cached_point_prompts[label_name] = this_prompts[:2]
336        if save_box_prompts:
337            cached_box_prompts[label_name] = this_prompts[-1]
338
339        # It's important to compress here, otherwise the predictions would take up a lot of space.
340        imageio.imwrite(prediction_path, instances, compression=5)
341
342    # Save the prompts if we run experiments with prompt caching and have computed them
343    # for the first time.
344    if save_point_prompts:
345        with open(point_prompt_save_path, "wb") as f:
346            pickle.dump(cached_point_prompts, f)
347    if save_box_prompts:
348        with open(box_prompt_save_path, "wb") as f:
349            pickle.dump(cached_box_prompts, f)

Run segment anything inference for multiple images using prompts derived from groundtruth.

Arguments:
  • predictor: The Segment Anything predictor.
  • image_paths: The image file paths.
  • gt_paths: The ground-truth segmentation file paths.
  • embedding_dir: The directory where the image embddings will be saved or are already saved.
  • use_points: Whether to use point prompts.
  • use_boxes: Whether to use box prompts
  • n_positives: The number of positive point prompts that will be sampled.
  • n_negativess: The number of negative point prompts that will be sampled.
  • dilation: The dilation factor for the radius around the ground-truth object around which points will not be sampled.
  • prompt_save_dir: The directory where point prompts will be saved or are already saved. This enables running multiple experiments in a reproducible manner.
  • batch_size: The batch size used for batched prediction.
def run_inference_with_iterative_prompting( predictor: segment_anything.predictor.SamPredictor, image_paths: List[Union[str, os.PathLike]], gt_paths: List[Union[str, os.PathLike]], embedding_dir: Union[str, os.PathLike], prediction_dir: Union[str, os.PathLike], start_with_box_prompt: bool = True, dilation: int = 5, batch_size: int = 32, n_iterations: int = 8, use_masks: bool = False, click_protocol: str = 'random') -> None:
473def run_inference_with_iterative_prompting(
474    predictor: SamPredictor,
475    image_paths: List[Union[str, os.PathLike]],
476    gt_paths: List[Union[str, os.PathLike]],
477    embedding_dir: Union[str, os.PathLike],
478    prediction_dir: Union[str, os.PathLike],
479    start_with_box_prompt: bool = True,
480    dilation: int = 5,
481    batch_size: int = 32,
482    n_iterations: int = 8,
483    use_masks: bool = False,
484    click_protocol: str = "random",
485) -> None:
486    """Run Segment Anything inference for multiple images using prompts iteratively
487    derived from model outputs and ground-truth.
488
489    Args:
490        predictor: The Segment Anything predictor.
491        image_paths: The image file paths.
492        gt_paths: The ground-truth segmentation file paths.
493        embedding_dir: The directory where the image embeddings will be saved or are already saved.
494        prediction_dir: The directory where the predictions from Segment Anything will be saved per iteration.
495        start_with_box_prompt: Whether to use the first prompt as bounding box or a single point
496        dilation: The dilation factor for the radius around the ground-truth object
497            around which points will not be sampled.
498        batch_size: The batch size used for batched predictions.
499        n_iterations: The number of iterations for iterative prompting.
500        use_masks: Whether to make use of logits from previous prompt-based segmentation.
501        click_protocol: The correction clicks. 'random' samples them at random positions in the error regions
502            and picks the best of 3 masks for a first point prompt. 'center' places them at the centers of the
503            largest error regions and predicts a single mask for a first point prompt.
504    """
505    if len(image_paths) != len(gt_paths):
506        raise ValueError(f"Expect same number of images and gt images, got {len(image_paths)}, {len(gt_paths)}")
507
508    # create all prediction folders for all intermediate iterations
509    for i in range(n_iterations):
510        os.makedirs(os.path.join(prediction_dir, f"iteration{i:02}"), exist_ok=True)
511
512    if use_masks:
513        print("The iterative prompting will make use of logits masks from previous iterations.")
514
515    for image_path, gt_path in tqdm(
516        zip(image_paths, gt_paths), total=len(image_paths),
517        desc="Run inference with iterative prompting for all images",
518    ):
519        image_name = os.path.basename(image_path)
520
521        # We skip the images that already have been segmented
522        prediction_paths = [os.path.join(prediction_dir, f"iteration{i:02}", image_name) for i in range(n_iterations)]
523        if all(os.path.exists(prediction_path) for prediction_path in prediction_paths):
524            continue
525
526        assert os.path.exists(image_path), image_path
527        assert os.path.exists(gt_path), gt_path
528
529        image = imageio.imread(image_path)
530        gt = imageio.imread(gt_path).astype("uint32")
531        # The objects that get prompted are the connected components of the labels, as in the micro-sam2
532        # evaluation, so that both prompt the same objects.
533        gt = connected_components(gt).astype("uint32")
534
535        if embedding_dir is None:
536            embedding_path = None
537        else:
538            embedding_path = os.path.join(embedding_dir, f"{os.path.splitext(image_name)[0]}.zarr")
539
540        _run_inference_with_iterative_prompting_for_image(
541            predictor, image, gt, start_with_box_prompt=start_with_box_prompt,
542            dilation=dilation, batch_size=batch_size, embedding_path=embedding_path,
543            n_iterations=n_iterations, prediction_paths=prediction_paths, use_masks=use_masks,
544            click_protocol=click_protocol,
545        )

Run Segment Anything inference for multiple images using prompts iteratively derived from model outputs and ground-truth.

Arguments:
  • predictor: The Segment Anything predictor.
  • image_paths: The image file paths.
  • gt_paths: The ground-truth segmentation file paths.
  • embedding_dir: The directory where the image embeddings will be saved or are already saved.
  • prediction_dir: The directory where the predictions from Segment Anything will be saved per iteration.
  • start_with_box_prompt: Whether to use the first prompt as bounding box or a single point
  • dilation: The dilation factor for the radius around the ground-truth object around which points will not be sampled.
  • batch_size: The batch size used for batched predictions.
  • n_iterations: The number of iterations for iterative prompting.
  • use_masks: Whether to make use of logits from previous prompt-based segmentation.
  • click_protocol: 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.
def run_amg( checkpoint: Union[str, os.PathLike], model_type: str, experiment_folder: Union[str, os.PathLike], val_image_paths: List[Union[str, os.PathLike]], val_gt_paths: List[Union[str, os.PathLike]], test_image_paths: List[Union[str, os.PathLike]], iou_thresh_values: Optional[List[float]] = None, stability_score_values: Optional[List[float]] = None, peft_kwargs: Optional[Dict] = None, cache_embeddings: bool = False, tiling_window_params: Optional[Dict[str, Tuple[int, int]]] = None) -> str:
553def run_amg(
554    checkpoint: Union[str, os.PathLike],
555    model_type: str,
556    experiment_folder: Union[str, os.PathLike],
557    val_image_paths: List[Union[str, os.PathLike]],
558    val_gt_paths: List[Union[str, os.PathLike]],
559    test_image_paths: List[Union[str, os.PathLike]],
560    iou_thresh_values: Optional[List[float]] = None,
561    stability_score_values: Optional[List[float]] = None,
562    peft_kwargs: Optional[Dict] = None,
563    cache_embeddings: bool = False,
564    tiling_window_params: Optional[Dict[str, Tuple[int, int]]] = None,
565) -> str:
566    """Run Segment Anything inference for multiple images using automatic mask generation (AMG).
567
568    Args:
569        checkpoint: The filepath to model checkpoints.
570        model_type: The segment anything model choice.
571        experimet_folder: The directory where the relevant files are saved.
572        val_image_paths: The list of filepaths of input images for grid-search.
573        val_gt_paths: The list of filepaths of corresponding labels for grid-search.
574        test_image_paths: The list of filepaths of input images for automatic instance segmentation.
575        iou_thresh_values: Optional choice of values for grid search of `iou_thresh` parameter.
576        stability_score_values: Optional choice of values for grid search of `stability_score` parameter.
577        peft_kwargs: Keyword arguments for th PEFT wrapper class.
578        cache_embeddings: Whether to cache embeddings in experiment folder.
579        tiling_window_params: The parameters to decide whether to use tiling window operation for AIS.
580
581    Returns:
582        Filepath where the predictions have been saved.
583    """
584
585    if cache_embeddings:
586        embedding_folder = os.path.join(experiment_folder, "embeddings")  # where the precomputed embeddings are saved
587        os.makedirs(embedding_folder, exist_ok=True)
588    else:
589        embedding_folder = None
590
591    predictor = get_sam_model(model_type=model_type, checkpoint_path=checkpoint, peft_kwargs=peft_kwargs)
592
593    # Get the AMG class.
594    if tiling_window_params:
595        if not isinstance(tiling_window_params, dict):
596            raise RuntimeError("The tiling window parameters are expected to be provided as a dictionary of params.")
597
598        if "tile_shape" not in tiling_window_params:
599            raise RuntimeError("'tile_shape' parameter is missing from the provided parameters.")
600
601        if "halo" not in tiling_window_params:
602            raise RuntimeError("'halo' parameter is missing from the provided parameters.")
603
604        amg_class = TiledAutomaticMaskGenerator
605    else:
606        amg_class = AutomaticMaskGenerator
607
608    amg = amg_class(predictor)
609    amg_prefix = "amg"
610
611    # where the predictions are saved
612    prediction_folder = os.path.join(experiment_folder, amg_prefix, "inference")
613    os.makedirs(prediction_folder, exist_ok=True)
614
615    # where the grid-search results are saved
616    gs_result_folder = os.path.join(experiment_folder, amg_prefix, "grid_search")
617    os.makedirs(gs_result_folder, exist_ok=True)
618
619    grid_search_values = instance_segmentation.default_grid_search_values_amg(
620        iou_thresh_values=iou_thresh_values,
621        stability_score_values=stability_score_values,
622    )
623
624    instance_segmentation.run_instance_segmentation_grid_search_and_inference(
625        segmenter=amg,
626        grid_search_values=grid_search_values,
627        val_image_paths=val_image_paths,
628        val_gt_paths=val_gt_paths,
629        test_image_paths=test_image_paths,
630        embedding_dir=embedding_folder,
631        prediction_dir=prediction_folder,
632        result_dir=gs_result_folder,
633        experiment_folder=experiment_folder,
634        tiling_window_params=tiling_window_params,
635    )
636    return prediction_folder

Run Segment Anything inference for multiple images using automatic mask generation (AMG).

Arguments:
  • checkpoint: The filepath to model checkpoints.
  • model_type: The segment anything model choice.
  • experimet_folder: The directory where the relevant files are saved.
  • val_image_paths: The list of filepaths of input images for grid-search.
  • val_gt_paths: The list of filepaths of corresponding labels for grid-search.
  • test_image_paths: The list of filepaths of input images for automatic instance segmentation.
  • iou_thresh_values: Optional choice of values for grid search of iou_thresh parameter.
  • stability_score_values: Optional choice of values for grid search of stability_score parameter.
  • peft_kwargs: Keyword arguments for th PEFT wrapper class.
  • cache_embeddings: Whether to cache embeddings in experiment folder.
  • tiling_window_params: The parameters to decide whether to use tiling window operation for AIS.
Returns:

Filepath where the predictions have been saved.

def run_apg( checkpoint: Union[str, os.PathLike, NoneType], model_type: str, experiment_folder: Union[str, os.PathLike], val_image_paths: List[Union[str, os.PathLike]], val_gt_paths: List[Union[str, os.PathLike]], test_image_paths: List[Union[str, os.PathLike]], peft_kwargs: Optional[Dict] = None, cache_embeddings: bool = False, tiling_window_params: Optional[Dict[str, Tuple[int, int]]] = None) -> str:
639def run_apg(
640    checkpoint: Optional[Union[str, os.PathLike]],
641    model_type: str,
642    experiment_folder: Union[str, os.PathLike],
643    val_image_paths: List[Union[str, os.PathLike]],
644    val_gt_paths: List[Union[str, os.PathLike]],
645    test_image_paths: List[Union[str, os.PathLike]],
646    peft_kwargs: Optional[Dict] = None,
647    cache_embeddings: bool = False,
648    tiling_window_params: Optional[Dict[str, Tuple[int, int]]] = None,
649) -> str:
650    """Run Segment Anything inference for multiple images using automatic prompt generation (APG).
651
652    Args:
653        ...
654
655    Returns:
656        Filepath where the predictions have been saved.
657    """
658    if cache_embeddings:
659        embedding_folder = os.path.join(experiment_folder, "embeddings")  # where the precomputed embeddings are saved
660        os.makedirs(embedding_folder, exist_ok=True)
661    else:
662        embedding_folder = None
663
664    predictor, decoder = get_predictor_and_decoder(
665        model_type=model_type, checkpoint_path=checkpoint, peft_kwargs=peft_kwargs,
666    )
667
668    # Get the APG class.
669    if tiling_window_params:
670        raise NotImplementedError
671    else:
672        apg_class = AutomaticPromptGenerator
673
674    segmenter = apg_class(predictor, decoder)
675    seg_prefix = "apg"
676
677    # where the predictions are saved
678    prediction_folder = os.path.join(experiment_folder, seg_prefix, "inference")
679    os.makedirs(prediction_folder, exist_ok=True)
680
681    # where the grid-search results are saved
682    gs_result_folder = os.path.join(experiment_folder, seg_prefix, "grid_search")
683    os.makedirs(gs_result_folder, exist_ok=True)
684
685    grid_search_values = instance_segmentation.default_grid_search_values_apg()
686
687    instance_segmentation.run_instance_segmentation_grid_search_and_inference(
688        segmenter=segmenter,
689        grid_search_values=grid_search_values,
690        val_image_paths=val_image_paths,
691        val_gt_paths=val_gt_paths,
692        test_image_paths=test_image_paths,
693        embedding_dir=embedding_folder,
694        prediction_dir=prediction_folder,
695        result_dir=gs_result_folder,
696        experiment_folder=experiment_folder,
697        tiling_window_params=tiling_window_params,
698    )
699    return prediction_folder

Run Segment Anything inference for multiple images using automatic prompt generation (APG).

Arguments:
  • ...
Returns:

Filepath where the predictions have been saved.

def run_instance_segmentation_with_decoder( checkpoint: Union[str, os.PathLike], model_type: str, experiment_folder: Union[str, os.PathLike], val_image_paths: List[Union[str, os.PathLike]], val_gt_paths: List[Union[str, os.PathLike]], test_image_paths: List[Union[str, os.PathLike]], peft_kwargs: Optional[Dict] = None, cache_embeddings: bool = False, tiling_window_params: Optional[Dict[str, Tuple[int, int]]] = None) -> str:
707def run_instance_segmentation_with_decoder(
708    checkpoint: Union[str, os.PathLike],
709    model_type: str,
710    experiment_folder: Union[str, os.PathLike],
711    val_image_paths: List[Union[str, os.PathLike]],
712    val_gt_paths: List[Union[str, os.PathLike]],
713    test_image_paths: List[Union[str, os.PathLike]],
714    peft_kwargs: Optional[Dict] = None,
715    cache_embeddings: bool = False,
716    tiling_window_params: Optional[Dict[str, Tuple[int, int]]] = None,
717) -> str:
718    """Run Segment Anything inference for multiple images using additional automatic instance segmentation (AIS).
719
720    Args:
721        checkpoint: The filepath to model checkpoints.
722        model_type: The segment anything model choice.
723        experimet_folder: The directory where the relevant files are saved.
724        val_image_paths: The list of filepaths of input images for grid-search.
725        val_gt_paths: The list of filepaths of corresponding labels for grid-search.
726        test_image_paths: The list of filepaths of input images for automatic instance segmentation.
727        peft_kwargs: Keyword arguments for th PEFT wrapper class.
728        cache_embeddings: Whether to cache embeddings in experiment folder.
729        tiling_window_params: The parameters to decide whether to use tiling window operation for AIS.
730
731    Returns:
732        Filepath where the predictions have been saved.
733    """
734
735    if cache_embeddings:
736        embedding_folder = os.path.join(experiment_folder, "embeddings")  # where the precomputed embeddings are saved
737        os.makedirs(embedding_folder, exist_ok=True)
738    else:
739        embedding_folder = None
740
741    predictor, decoder = get_predictor_and_decoder(
742        model_type=model_type, checkpoint_path=checkpoint, peft_kwargs=peft_kwargs,
743    )
744
745    # Get the AIS class.
746    if tiling_window_params:
747        if not isinstance(tiling_window_params, dict):
748            raise RuntimeError("The tiling window parameters are expected to be provided as a dictionary of params.")
749
750        if "tile_shape" not in tiling_window_params:
751            raise RuntimeError("'tile_shape' parameter is missing from the provided parameters.")
752
753        if "halo" not in tiling_window_params:
754            raise RuntimeError("'halo' parameter is missing from the provided parameters.")
755
756        ais_class = TiledInstanceSegmentationWithDecoder
757    else:
758        ais_class = InstanceSegmentationWithDecoder
759
760    segmenter = ais_class(predictor, decoder)
761    seg_prefix = "instance_segmentation_with_decoder"
762
763    # where the predictions are saved
764    prediction_folder = os.path.join(experiment_folder, seg_prefix, "inference")
765    os.makedirs(prediction_folder, exist_ok=True)
766
767    # where the grid-search results are saved
768    gs_result_folder = os.path.join(experiment_folder, seg_prefix, "grid_search")
769    os.makedirs(gs_result_folder, exist_ok=True)
770
771    grid_search_values = instance_segmentation.default_grid_search_values_instance_segmentation_with_decoder()
772
773    instance_segmentation.run_instance_segmentation_grid_search_and_inference(
774        segmenter=segmenter,
775        grid_search_values=grid_search_values,
776        val_image_paths=val_image_paths,
777        val_gt_paths=val_gt_paths,
778        test_image_paths=test_image_paths,
779        embedding_dir=embedding_folder,
780        prediction_dir=prediction_folder,
781        result_dir=gs_result_folder,
782        experiment_folder=experiment_folder,
783        tiling_window_params=tiling_window_params,
784    )
785    return prediction_folder

Run Segment Anything inference for multiple images using additional automatic instance segmentation (AIS).

Arguments:
  • checkpoint: The filepath to model checkpoints.
  • model_type: The segment anything model choice.
  • experimet_folder: The directory where the relevant files are saved.
  • val_image_paths: The list of filepaths of input images for grid-search.
  • val_gt_paths: The list of filepaths of corresponding labels for grid-search.
  • test_image_paths: The list of filepaths of input images for automatic instance segmentation.
  • peft_kwargs: Keyword arguments for th PEFT wrapper class.
  • cache_embeddings: Whether to cache embeddings in experiment folder.
  • tiling_window_params: The parameters to decide whether to use tiling window operation for AIS.
Returns:

Filepath where the predictions have been saved.