micro_sam.v1.evaluation.evaluation

Evaluation functionality for segmentation predictions from micro_sam.v1.evaluation.automatic_mask_generation and micro_sam.v1.evaluation.inference.

  1"""Evaluation functionality for segmentation predictions from `micro_sam.v1.evaluation.automatic_mask_generation`
  2and `micro_sam.v1.evaluation.inference`.
  3"""
  4
  5import os
  6from glob import glob
  7from pathlib import Path
  8from typing import List, Optional, Union
  9
 10import numpy as np
 11import pandas as pd
 12from tqdm import tqdm
 13import imageio.v3 as imageio
 14from natsort import natsorted
 15
 16from elf.evaluation import mean_segmentation_accuracy, matching
 17
 18from bioimage_cpp.segmentation import label
 19
 20from ...util import load_image_data
 21
 22
 23def _run_evaluation(gt_paths, prediction_paths, verbose=True, thresholds=None):
 24    assert len(gt_paths) == len(prediction_paths)
 25
 26    msas, sa50s, sa75s, precisions, recalls, f1s = [], [], [], [], [], []
 27    for gt_path, pred_path in tqdm(
 28        zip(gt_paths, prediction_paths), desc="Evaluate predictions", total=len(gt_paths), disable=not verbose
 29    ):
 30
 31        if isinstance(gt_path, np.ndarray):
 32            gt = gt_path
 33        else:
 34            assert os.path.exists(gt_path), gt_path
 35            gt = imageio.imread(gt_path)
 36            gt = label(gt)
 37
 38        if isinstance(pred_path, np.ndarray):
 39            pred = pred_path
 40        else:
 41            assert os.path.exists(pred_path), pred_path
 42            pred = imageio.imread(pred_path)
 43
 44        assert gt.shape == pred.shape, f"Expected {gt.shape}, got {pred.shape}"
 45        msa, scores = mean_segmentation_accuracy(pred, gt, thresholds=thresholds, return_accuracies=True)
 46        stats = matching(pred, gt)
 47        msas.append(msa)
 48        if thresholds is None:
 49            sa50, sa75 = scores[0], scores[5]
 50            sa50s.append(sa50), sa75s.append(sa75)
 51        precisions.append(stats["precision"])
 52        recalls.append(stats["recall"])
 53        f1s.append(stats["f1"])
 54
 55    if thresholds is None:
 56        return (msas, sa50s, sa75s), (precisions, recalls, f1s)
 57    else:
 58        return msas, (precisions, recalls, f1s)
 59
 60
 61def run_evaluation(
 62    gt_paths: List[Union[np.ndarray, os.PathLike, str]],
 63    prediction_paths: List[Union[np.ndarray, os.PathLike, str]],
 64    save_path: Optional[Union[os.PathLike, str]] = None,
 65    verbose: bool = True,
 66    thresholds: Optional[List[float]] = None,
 67) -> pd.DataFrame:
 68    """Run evaluation for instance segmentation predictions.
 69
 70    Args:
 71        gt_paths: The list of paths to ground-truth images.
 72        prediction_paths: The list of paths with the instance segmentations to evaluate.
 73        save_path: Optional path for saving the results.
 74        verbose: Whether to print the progress.
 75        thresholds: The choice of overlap thresholds.
 76
 77    Returns:
 78        A DataFrame that contains the evaluation results.
 79    """
 80    assert len(gt_paths) == len(prediction_paths)
 81    # if a save_path is given and it already exists then just load it instead of running the eval
 82    if save_path is not None and os.path.exists(save_path):
 83        return pd.read_csv(save_path)
 84
 85    scores = _run_evaluation(
 86        gt_paths=gt_paths, prediction_paths=prediction_paths, verbose=verbose, thresholds=thresholds
 87    )
 88
 89    sas, other_scores = scores  # Separate all score into two categories.
 90    precisions, recalls, f1s = other_scores
 91
 92    if thresholds is None:
 93        msas, sa50s, sa75s = sas
 94    else:
 95        msas = sas
 96
 97    results = {"mSA": [np.mean(msas)]}
 98    if thresholds is None:
 99        results["SA50"] = [np.mean(sa50s)]
100        results["SA75"] = [np.mean(sa75s)]
101    results["Precision"] = [np.mean(precisions)]
102    results["Recall"] = [np.mean(recalls)]
103    results["F1 Score"] = [np.mean(f1s)]
104
105    results = pd.DataFrame.from_dict(results)
106
107    if save_path is not None:
108        os.makedirs(Path(save_path).parent, exist_ok=True)
109        results.to_csv(save_path, index=False)
110
111    return results
112
113
114def run_evaluation_for_iterative_prompting(
115    gt_paths: List[Union[os.PathLike, str]],
116    prediction_root: Union[os.PathLike, str],
117    experiment_folder: Union[os.PathLike, str],
118    start_with_box_prompt: bool = False,
119    overwrite_results: bool = False,
120    use_masks: bool = False,
121) -> pd.DataFrame:
122    """Run evaluation for iterative prompt-based segmentation predictions.
123
124    Args:
125        gt_paths: The list of paths to ground-truth images.
126        prediction_root: The folder with the iterative prompt-based instance segmentations to evaluate.
127        experiment_folder: The folder where all the experiment results are stored.
128        start_with_box_prompt: Whether to evaluate on experiments with iterative prompting starting with box.
129        overwrite_results: Whether to overwrite the results to update them with the new evaluation run.
130        use_masks: Whether to use masks for iterative prompting.
131
132    Returns:
133        A DataFrame that contains the evaluation results.
134    """
135    assert os.path.exists(prediction_root), prediction_root
136
137    # Save the results in the experiment folder
138    result_folder = os.path.join(
139        experiment_folder, "results", "iterative_prompting_" + ("with" if use_masks else "without") + "_mask"
140    )
141    os.makedirs(result_folder, exist_ok=True)
142
143    csv_path = os.path.join(
144        result_folder,
145        "iterative_prompts_start_box.csv" if start_with_box_prompt else "iterative_prompts_start_point.csv"
146    )
147
148    # Overwrite the previously saved results
149    if overwrite_results and os.path.exists(csv_path):
150        os.remove(csv_path)
151
152    # If the results have been computed already, it's not needed to re-run it again.
153    if os.path.exists(csv_path):
154        print(f"Results with iterative prompting for interactive segmentation are already stored at '{csv_path}'.")
155        return
156
157    list_of_results = []
158    prediction_folders = sorted(glob(os.path.join(prediction_root, "iteration*")))
159    for pred_folder in prediction_folders:
160        print("Evaluating", os.path.split(pred_folder)[-1])
161        pred_paths = sorted(glob(os.path.join(pred_folder, "*")))
162        result = run_evaluation(gt_paths=gt_paths, prediction_paths=pred_paths, save_path=None)
163        list_of_results.append(result)
164
165    res_df = pd.concat(list_of_results, ignore_index=True)
166    res_df.to_csv(csv_path)
167
168    return res_df
169
170
171def main(argv=None):
172    """@private"""
173    import argparse
174
175    parser = argparse.ArgumentParser(description="Evaluating segmentations from Segment Anything model on custom data.")
176
177    # labels and predictions for quantitative evaluation.
178    parser.add_argument(
179        "--labels", required=True, type=str, nargs="+",
180        help="Filepath(s) to ground-truth labels or the directory where the label data is stored."
181    )
182    parser.add_argument(
183        "--predictions", required=True, type=str, nargs="+",
184        help="Filepath to predicted labels or the directory where the predicted label data is stored."
185    )
186    parser.add_argument(
187        "--label_key", type=str, default=None,
188        help="The key for accessing predicted label data, either a pattern / wildcard or with 'elf.io.open_file'. "
189    )
190    parser.add_argument(
191        "--prediction_key", type=str, default=None,
192        help="The key for accessing ground-truth label data, either a pattern / wildcard or with 'elf.io.open_file'. "
193    )
194    parser.add_argument(
195        "-o", "--output_path", type=str, default=None,
196        help="The filepath to store the evaluation results. The current support stores results in a 'csv' file."
197    )
198    parser.add_argument(
199        "--threshold", default=None, type=float, nargs="+",
200        help="The choice of overlap threshold(s) for calculating the segmentation accuracy. By default, "
201        "np.arange(0.5, 1., 0.05) is used to provide the mean segmentation accurcy score over all values.",
202    )
203    parser.add_argument("-v", "--verbose", action="store_true", help="Whether to allow verbosity of evaluation.")
204
205    # TODO: We can extend this in future for other metrics, eg. dice score, etc.
206    # NOTE: This argument is not exposed to the user atm.
207    # parser.add_argument(
208    #     "--metric", type=str, default="segmentation_accuracy", choices=("segmentation_accuracy"),
209    #     help="The choice of metric for evaluation. By default, it computes segmentation accuracy "
210    #     "for instance segmentation."
211    # )
212
213    args = parser.parse_args(argv)
214
215    # Check whether the inputs are as expected.
216    def _get_inputs_from_paths(paths, key):
217        fpaths = []
218        for path in paths:
219            if os.path.isfile(path):  # it is just one filepath and we check whether we can access it via 'elf'.
220                fpaths.append(path if key is None else load_image_data(path=path, key=key))
221            else:  # otherwise, path is a directory, fetch all inputs provided with a pattern.
222                assert key is not None, \
223                    f"You must provide a wildcard / pattern as the filepath '{os.path.abspath(path)}' is a directory."
224                fpaths.extend(natsorted(glob(os.path.join(path, key))))
225
226        return fpaths
227
228    labels = _get_inputs_from_paths(args.labels, args.label_key)
229    predictions = _get_inputs_from_paths(args.predictions, args.prediction_key)
230    assert labels and len(labels) == len(predictions)
231
232    # Check whether output path is a csv or not, if passed.
233    output_path = args.output_path
234    if output_path is not None:
235        if not os.path.isfile(output_path):  # If it is a directory, store this in "<OUTPUT_PATH>/results.csv"
236            os.makedirs(output_path, exist_ok=True)
237            output_path = os.path.join(output_path, "results.csv")
238
239        if not output_path.endswith(".csv"):  # If it is a filepath missing extension / with a different extension.
240            output_path = str(Path(output_path).with_suffix(".csv"))  # Limit supports to csv files for now.
241
242    # Run evaluation on labels and predictions.
243    results = run_evaluation(
244        gt_paths=labels,
245        prediction_paths=predictions,
246        save_path=output_path,
247        verbose=args.verbose,
248        thresholds=args.threshold,
249    )
250
251    print("The evaluation results for the predictions are:")
252    print(results)
253
254    if args.verbose and output_path is not None:
255        print(f"The evaluation results have been stored at '{os.path.abspath(output_path)}'.")
def run_evaluation( gt_paths: List[Union[numpy.ndarray, os.PathLike, str]], prediction_paths: List[Union[numpy.ndarray, os.PathLike, str]], save_path: Union[str, os.PathLike, NoneType] = None, verbose: bool = True, thresholds: Optional[List[float]] = None) -> pandas.DataFrame:
 62def run_evaluation(
 63    gt_paths: List[Union[np.ndarray, os.PathLike, str]],
 64    prediction_paths: List[Union[np.ndarray, os.PathLike, str]],
 65    save_path: Optional[Union[os.PathLike, str]] = None,
 66    verbose: bool = True,
 67    thresholds: Optional[List[float]] = None,
 68) -> pd.DataFrame:
 69    """Run evaluation for instance segmentation predictions.
 70
 71    Args:
 72        gt_paths: The list of paths to ground-truth images.
 73        prediction_paths: The list of paths with the instance segmentations to evaluate.
 74        save_path: Optional path for saving the results.
 75        verbose: Whether to print the progress.
 76        thresholds: The choice of overlap thresholds.
 77
 78    Returns:
 79        A DataFrame that contains the evaluation results.
 80    """
 81    assert len(gt_paths) == len(prediction_paths)
 82    # if a save_path is given and it already exists then just load it instead of running the eval
 83    if save_path is not None and os.path.exists(save_path):
 84        return pd.read_csv(save_path)
 85
 86    scores = _run_evaluation(
 87        gt_paths=gt_paths, prediction_paths=prediction_paths, verbose=verbose, thresholds=thresholds
 88    )
 89
 90    sas, other_scores = scores  # Separate all score into two categories.
 91    precisions, recalls, f1s = other_scores
 92
 93    if thresholds is None:
 94        msas, sa50s, sa75s = sas
 95    else:
 96        msas = sas
 97
 98    results = {"mSA": [np.mean(msas)]}
 99    if thresholds is None:
100        results["SA50"] = [np.mean(sa50s)]
101        results["SA75"] = [np.mean(sa75s)]
102    results["Precision"] = [np.mean(precisions)]
103    results["Recall"] = [np.mean(recalls)]
104    results["F1 Score"] = [np.mean(f1s)]
105
106    results = pd.DataFrame.from_dict(results)
107
108    if save_path is not None:
109        os.makedirs(Path(save_path).parent, exist_ok=True)
110        results.to_csv(save_path, index=False)
111
112    return results

Run evaluation for instance segmentation predictions.

Arguments:
  • gt_paths: The list of paths to ground-truth images.
  • prediction_paths: The list of paths with the instance segmentations to evaluate.
  • save_path: Optional path for saving the results.
  • verbose: Whether to print the progress.
  • thresholds: The choice of overlap thresholds.
Returns:

A DataFrame that contains the evaluation results.

def run_evaluation_for_iterative_prompting( gt_paths: List[Union[str, os.PathLike]], prediction_root: Union[os.PathLike, str], experiment_folder: Union[os.PathLike, str], start_with_box_prompt: bool = False, overwrite_results: bool = False, use_masks: bool = False) -> pandas.DataFrame:
115def run_evaluation_for_iterative_prompting(
116    gt_paths: List[Union[os.PathLike, str]],
117    prediction_root: Union[os.PathLike, str],
118    experiment_folder: Union[os.PathLike, str],
119    start_with_box_prompt: bool = False,
120    overwrite_results: bool = False,
121    use_masks: bool = False,
122) -> pd.DataFrame:
123    """Run evaluation for iterative prompt-based segmentation predictions.
124
125    Args:
126        gt_paths: The list of paths to ground-truth images.
127        prediction_root: The folder with the iterative prompt-based instance segmentations to evaluate.
128        experiment_folder: The folder where all the experiment results are stored.
129        start_with_box_prompt: Whether to evaluate on experiments with iterative prompting starting with box.
130        overwrite_results: Whether to overwrite the results to update them with the new evaluation run.
131        use_masks: Whether to use masks for iterative prompting.
132
133    Returns:
134        A DataFrame that contains the evaluation results.
135    """
136    assert os.path.exists(prediction_root), prediction_root
137
138    # Save the results in the experiment folder
139    result_folder = os.path.join(
140        experiment_folder, "results", "iterative_prompting_" + ("with" if use_masks else "without") + "_mask"
141    )
142    os.makedirs(result_folder, exist_ok=True)
143
144    csv_path = os.path.join(
145        result_folder,
146        "iterative_prompts_start_box.csv" if start_with_box_prompt else "iterative_prompts_start_point.csv"
147    )
148
149    # Overwrite the previously saved results
150    if overwrite_results and os.path.exists(csv_path):
151        os.remove(csv_path)
152
153    # If the results have been computed already, it's not needed to re-run it again.
154    if os.path.exists(csv_path):
155        print(f"Results with iterative prompting for interactive segmentation are already stored at '{csv_path}'.")
156        return
157
158    list_of_results = []
159    prediction_folders = sorted(glob(os.path.join(prediction_root, "iteration*")))
160    for pred_folder in prediction_folders:
161        print("Evaluating", os.path.split(pred_folder)[-1])
162        pred_paths = sorted(glob(os.path.join(pred_folder, "*")))
163        result = run_evaluation(gt_paths=gt_paths, prediction_paths=pred_paths, save_path=None)
164        list_of_results.append(result)
165
166    res_df = pd.concat(list_of_results, ignore_index=True)
167    res_df.to_csv(csv_path)
168
169    return res_df

Run evaluation for iterative prompt-based segmentation predictions.

Arguments:
  • gt_paths: The list of paths to ground-truth images.
  • prediction_root: The folder with the iterative prompt-based instance segmentations to evaluate.
  • experiment_folder: The folder where all the experiment results are stored.
  • start_with_box_prompt: Whether to evaluate on experiments with iterative prompting starting with box.
  • overwrite_results: Whether to overwrite the results to update them with the new evaluation run.
  • use_masks: Whether to use masks for iterative prompting.
Returns:

A DataFrame that contains the evaluation results.