|
| 1 | +#!/bin/env python3 |
| 2 | +import sys |
| 3 | +import os |
| 4 | + |
| 5 | +# Add membrain-seg to Python path |
| 6 | +MEMBRAIN_SEG_PATH = "/home/sage/membrain-seg/src" |
| 7 | +if MEMBRAIN_SEG_PATH not in sys.path: |
| 8 | + sys.path.insert(0, MEMBRAIN_SEG_PATH) |
| 9 | + |
| 10 | +import argparse |
| 11 | +import h5py |
| 12 | +import pandas as pd |
| 13 | +from tqdm import tqdm |
| 14 | +import numpy as np |
| 15 | +from scipy.ndimage import label |
| 16 | +from skimage.measure import regionprops |
| 17 | + |
| 18 | +try: |
| 19 | + from membrain_seg.segmentation.skeletonize import skeletonization |
| 20 | + from membrain_seg.benchmark.metrics import masked_surface_dice |
| 21 | +except ImportError: |
| 22 | + raise ImportError("membrain_seg not found in path. Download source code:" \ |
| 23 | + "https://github.com/teamtomo/membrain-seg/tree/main/src/membrain_seg") |
| 24 | + exit() |
| 25 | + |
| 26 | +def load_segmentation(file_path, key): |
| 27 | + with h5py.File(file_path, "r") as f: |
| 28 | + data = f[key][:] |
| 29 | + return data |
| 30 | + |
| 31 | +def evaluate_surface_dice(pred, gt, raw, check): |
| 32 | + gt_skeleton = skeletonization(gt == 1, batch_size=100000) |
| 33 | + pred_skeleton = skeletonization(pred, batch_size=100000) |
| 34 | + mask = gt != 2 |
| 35 | + |
| 36 | + if check: |
| 37 | + import napari |
| 38 | + v = napari.Viewer() |
| 39 | + v.add_image(raw) |
| 40 | + v.add_labels(gt, name="gt") |
| 41 | + v.add_labels(gt_skeleton.astype(np.uint16), name="gt_skeleton") |
| 42 | + v.add_labels(pred, name="pred") |
| 43 | + v.add_labels(pred_skeleton.astype(np.uint16), name="pred_skeleton") |
| 44 | + |
| 45 | + napari.run() |
| 46 | + |
| 47 | + surf_dice, confusion_dict = masked_surface_dice( |
| 48 | + pred_skeleton, gt_skeleton, pred, gt, mask |
| 49 | + ) |
| 50 | + return surf_dice, confusion_dict |
| 51 | + |
| 52 | + |
| 53 | +def process_file(pred_path, gt_path, seg_key, gt_key, check, |
| 54 | + min_bb_shape=(64, 384, 384), min_thinning_size=2500, |
| 55 | + global_eval=False): |
| 56 | + try: |
| 57 | + pred = load_segmentation(pred_path, seg_key) |
| 58 | + gt = load_segmentation(gt_path, gt_key) |
| 59 | + raw = load_segmentation(gt_path, "raw") |
| 60 | + |
| 61 | + if global_eval: |
| 62 | + gt_bin = (gt == 1).astype(np.uint8) |
| 63 | + pred_bin = pred.astype(np.uint8) |
| 64 | + |
| 65 | + dice, confusion = evaluate_surface_dice(pred_bin, gt_bin, raw, check) |
| 66 | + return [{ |
| 67 | + "tomo_name": os.path.basename(pred_path), |
| 68 | + "gt_component_id": -1, # -1 indicates global eval |
| 69 | + "surface_dice": dice, |
| 70 | + **confusion |
| 71 | + }] |
| 72 | + |
| 73 | + labeled_gt, _ = label(gt == 1) |
| 74 | + props = regionprops(labeled_gt) |
| 75 | + results = [] |
| 76 | + |
| 77 | + for prop in props: |
| 78 | + if prop.area < min_thinning_size: |
| 79 | + continue |
| 80 | + |
| 81 | + comp_id = prop.label |
| 82 | + bbox_start = prop.bbox[:3] |
| 83 | + bbox_end = prop.bbox[3:] |
| 84 | + bbox = tuple(slice(start, stop) for start, stop in zip(bbox_start, bbox_end)) |
| 85 | + |
| 86 | + pad_width = [ |
| 87 | + max(min_shape - (sl.stop - sl.start), 0) // 2 |
| 88 | + for sl, min_shape in zip(bbox, min_bb_shape) |
| 89 | + ] |
| 90 | + |
| 91 | + expanded_bbox = tuple( |
| 92 | + slice( |
| 93 | + max(sl.start - pw, 0), |
| 94 | + min(sl.stop + pw, dim) |
| 95 | + ) |
| 96 | + for sl, pw, dim in zip(bbox, pad_width, gt.shape) |
| 97 | + ) |
| 98 | + |
| 99 | + gt_crop = (labeled_gt[expanded_bbox] == comp_id).astype(np.uint8) |
| 100 | + pred_crop = pred[expanded_bbox].astype(np.uint8) |
| 101 | + raw_crop = raw[expanded_bbox] |
| 102 | + |
| 103 | + try: |
| 104 | + dice, confusion = evaluate_surface_dice(pred_crop, gt_crop, raw_crop, check) |
| 105 | + except Exception as e: |
| 106 | + print(f"Error computing Dice for GT component {comp_id} in {pred_path}: {e}") |
| 107 | + continue |
| 108 | + |
| 109 | + result = { |
| 110 | + "tomo_name": os.path.basename(pred_path), |
| 111 | + "gt_component_id": comp_id, |
| 112 | + "surface_dice": dice, |
| 113 | + **confusion |
| 114 | + } |
| 115 | + results.append(result) |
| 116 | + |
| 117 | + return results |
| 118 | + |
| 119 | + except Exception as e: |
| 120 | + print(f"Error processing {pred_path}: {e}") |
| 121 | + return [] |
| 122 | + |
| 123 | + |
| 124 | +def collect_results(input_folder, gt_folder, model_name, check=False, |
| 125 | + min_bb_shape=(32, 384, 384), min_thinning_size=2500, |
| 126 | + global_eval=False): |
| 127 | + results = [] |
| 128 | + seg_key = f"/segmentations/{model_name}" |
| 129 | + gt_key = "/labels/actin" |
| 130 | + input_folder_name = os.path.basename(os.path.normpath(input_folder)) |
| 131 | + |
| 132 | + for fname in tqdm(os.listdir(input_folder), desc="Processing segmentations"): |
| 133 | + if not fname.endswith(".h5"): |
| 134 | + continue |
| 135 | + |
| 136 | + pred_path = os.path.join(input_folder, fname) |
| 137 | + print(pred_path) |
| 138 | + gt_path = os.path.join(gt_folder, fname) |
| 139 | + |
| 140 | + if not os.path.exists(gt_path): |
| 141 | + print(f"Warning: Ground truth file not found for {fname}") |
| 142 | + continue |
| 143 | + |
| 144 | + file_results = process_file( |
| 145 | + pred_path, gt_path, seg_key, gt_key, check, |
| 146 | + min_bb_shape=min_bb_shape, |
| 147 | + min_thinning_size=min_thinning_size, |
| 148 | + global_eval=global_eval |
| 149 | + ) |
| 150 | + |
| 151 | + for res in file_results: |
| 152 | + res["input_folder"] = input_folder_name |
| 153 | + results.append(res) |
| 154 | + |
| 155 | + return results |
| 156 | + |
| 157 | + |
| 158 | +def save_results(results, output_file): |
| 159 | + new_df = pd.DataFrame(results) |
| 160 | + |
| 161 | + if os.path.exists(output_file): |
| 162 | + existing_df = pd.read_excel(output_file) |
| 163 | + |
| 164 | + combined_df = existing_df[ |
| 165 | + ~existing_df.set_index(["tomo_name", "input_folder", "gt_component_id"]).index.isin( |
| 166 | + new_df.set_index(["tomo_name", "input_folder", "gt_component_id"]).index |
| 167 | + ) |
| 168 | + ] |
| 169 | + |
| 170 | + final_df = pd.concat([combined_df, new_df], ignore_index=True) |
| 171 | + else: |
| 172 | + final_df = new_df |
| 173 | + |
| 174 | + final_df.to_excel(output_file, index=False) |
| 175 | + print(f"Results saved to {output_file}") |
| 176 | + |
| 177 | + |
| 178 | +def main(): |
| 179 | + parser = argparse.ArgumentParser(description="Compute surface dice per GT component or globally for actin segmentations.") |
| 180 | + parser.add_argument("--input_folder", "-i", required=True, help="Folder with predicted segmentations (.h5)") |
| 181 | + parser.add_argument("--gt_folder", "-gt", required=True, help="Folder with ground truth segmentations (.h5)") |
| 182 | + parser.add_argument("--model_name", "-m", required=True, help="Model name string used in prediction key") |
| 183 | + parser.add_argument("--check", action="store_true", help="Visualize intermediate outputs in Napari") |
| 184 | + parser.add_argument("--global_eval", action="store_true", help="If set, compute global surface dice instead of per-component") |
| 185 | + |
| 186 | + args = parser.parse_args() |
| 187 | + |
| 188 | + min_bb_shape = (32, 464, 464) |
| 189 | + min_thinning_size = 2500 |
| 190 | + |
| 191 | + suffix = "global" if args.global_eval else "per_gt_component" |
| 192 | + |
| 193 | + output_file = f"./evaluation_results/{args.model_name}_surface_dice_{suffix}.xlsx" |
| 194 | + output_dir = os.path.dirname(output_file) |
| 195 | + os.makedirs(output_dir, exist_ok=True) |
| 196 | + |
| 197 | + results = collect_results( |
| 198 | + args.input_folder, |
| 199 | + args.gt_folder, |
| 200 | + args.model_name, |
| 201 | + args.check, |
| 202 | + min_bb_shape=min_bb_shape, |
| 203 | + min_thinning_size=min_thinning_size, |
| 204 | + global_eval=args.global_eval |
| 205 | + ) |
| 206 | + |
| 207 | + save_results(results, output_file) |
| 208 | + |
| 209 | + |
| 210 | +if __name__ == "__main__": |
| 211 | + main() |
0 commit comments