| 
 | 1 | +import argparse  | 
 | 2 | +import json  | 
 | 3 | +import multiprocessing as mp  | 
 | 4 | +import os  | 
 | 5 | +from concurrent import futures  | 
 | 6 | +from typing import List  | 
 | 7 | + | 
 | 8 | +import numpy as np  | 
 | 9 | +import tifffile  | 
 | 10 | +from tqdm import tqdm  | 
 | 11 | + | 
 | 12 | +GT_DIR = "/mnt/vast-nhr/projects/nim00007/data/moser/cochlea-lightsheet/training_data/nucleus/2025-07_NIS3D/test"  | 
 | 13 | +PRED_DIR = "/mnt/vast-nhr/projects/nim00007/data/moser/cochlea-lightsheet/predictions/val_nucleus/distance_unet_NIS3D"  | 
 | 14 | + | 
 | 15 | + | 
 | 16 | +def find_overlapping_masks(  | 
 | 17 | +    arr_base: np.ndarray,  | 
 | 18 | +    arr_ref: np.ndarray,  | 
 | 19 | +    label_id_base: int,  | 
 | 20 | +    min_overlap: float = 0.5,  | 
 | 21 | +) -> List[int]:  | 
 | 22 | +    """Find masks of segmentation, which have an overlap with undefined mask greater than 0.5.  | 
 | 23 | +    """  | 
 | 24 | +    labels_undefined_mask = []  | 
 | 25 | +    arr_base_undefined = arr_base == label_id_base  | 
 | 26 | + | 
 | 27 | +    # iterate through segmentation ids in reference mask  | 
 | 28 | +    ref_ids = list(np.unique(arr_ref)[1:])  | 
 | 29 | +    for ref_id in ref_ids:  | 
 | 30 | +        arr_ref_instance = arr_ref == ref_id  | 
 | 31 | + | 
 | 32 | +        intersection = np.logical_and(arr_ref_instance, arr_base_undefined)  | 
 | 33 | +        overlap_ratio = np.sum(intersection) / np.sum(arr_ref_instance)  | 
 | 34 | +        if overlap_ratio >= min_overlap:  | 
 | 35 | +            labels_undefined_mask.append(ref_id)  | 
 | 36 | + | 
 | 37 | +    return labels_undefined_mask  | 
 | 38 | + | 
 | 39 | + | 
 | 40 | +def find_matching_masks(arr_gt, arr_ref, out_path, labels_undefined_mask=[]):  | 
 | 41 | +    """For each instance in the reference array, the corresponding mask of the ground truth array,  | 
 | 42 | +    which has the biggest overlap, is identified.  | 
 | 43 | +
  | 
 | 44 | +    Args:  | 
 | 45 | +        arr_gt:  | 
 | 46 | +        arr_ref:  | 
 | 47 | +        out_path: Output path for saving dictionary.  | 
 | 48 | +        labels_undefined_mask: Labels of the reference array to exclude.  | 
 | 49 | +    """  | 
 | 50 | +    seg_ids_ref = [int(i) for i in np.unique(arr_ref)[1:]]  | 
 | 51 | +    print(f"total number of segmentation masks: {len(seg_ids_ref)}")  | 
 | 52 | +    seg_ids_ref = [s for s in seg_ids_ref if s not in labels_undefined_mask]  | 
 | 53 | +    print(f"number of segmentation masks after filtering undefined masks: {len(seg_ids_ref)}")  | 
 | 54 | + | 
 | 55 | +    def compute_overlap(ref_id):  | 
 | 56 | +        """Identify ID of segmentation mask with biggest overlap.  | 
 | 57 | +        Return matched IDs and overlap.  | 
 | 58 | +        """  | 
 | 59 | +        arr_ref_instance = arr_ref == ref_id  | 
 | 60 | + | 
 | 61 | +        seg_ids_gt = np.unique(arr_gt[arr_ref_instance])[1:]  | 
 | 62 | + | 
 | 63 | +        max_overlap = 0  | 
 | 64 | +        gt_id_match = None  | 
 | 65 | + | 
 | 66 | +        for gt_id in seg_ids_gt:  | 
 | 67 | +            arr_gt_instance = arr_gt == gt_id  | 
 | 68 | + | 
 | 69 | +            intersection = np.logical_and(arr_ref_instance, arr_gt_instance)  | 
 | 70 | +            overlap_ratio = np.sum(intersection) / np.sum(arr_ref_instance)  | 
 | 71 | +            if overlap_ratio > max_overlap:  | 
 | 72 | +                gt_id_match = int(gt_id.tolist())  | 
 | 73 | +                max_overlap = np.max([max_overlap, overlap_ratio])  | 
 | 74 | + | 
 | 75 | +        if gt_id_match is not None:  | 
 | 76 | +            return {  | 
 | 77 | +                "ref_id": ref_id,  | 
 | 78 | +                "gt_id": gt_id_match,  | 
 | 79 | +                "overlap": float(max_overlap.tolist())  | 
 | 80 | +            }  | 
 | 81 | +        else:  | 
 | 82 | +            return None  | 
 | 83 | + | 
 | 84 | +    n_threads = min(16, mp.cpu_count())  | 
 | 85 | +    print(f"Parallelizing with {n_threads} Threads.")  | 
 | 86 | +    with futures.ThreadPoolExecutor(n_threads) as pool:  | 
 | 87 | +        results = list(tqdm(pool.map(compute_overlap, seg_ids_ref), total=len(seg_ids_ref)))  | 
 | 88 | + | 
 | 89 | +    matching_masks = {r['ref_id']: r for r in results if r is not None}  | 
 | 90 | + | 
 | 91 | +    with open(out_path, "w") as f:  | 
 | 92 | +        json.dump(matching_masks, f, indent='\t', separators=(',', ': '))  | 
 | 93 | + | 
 | 94 | + | 
 | 95 | +def filter_true_positives(output_folder, prefixes, force_overwrite):  | 
 | 96 | +    """ Filter true positives from segmentation.  | 
 | 97 | +    Segmentation instances and ground truth labels are filtered symmetrically.  | 
 | 98 | +    The maximal overlap of each is computed and taken as a true positive if symmetric.  | 
 | 99 | +    The instance ID, the reference ID, and the overlap are saved in dictionaries.  | 
 | 100 | +
  | 
 | 101 | +    Args:  | 
 | 102 | +        output_folder: Output folder for dictionaries.  | 
 | 103 | +        prefixes: List of prefixes for evaluation. One or multiple of ["Drosophila", "MusMusculus", "Zebrafish"].  | 
 | 104 | +        force_overwrite: Flag for forced overwrite of existing output files.  | 
 | 105 | +    """  | 
 | 106 | +    if "PRED_DIR" in globals():  | 
 | 107 | +        pred_dir = PRED_DIR  | 
 | 108 | +    if "GT_DIR" in globals():  | 
 | 109 | +        gt_dir = GT_DIR  | 
 | 110 | + | 
 | 111 | +    if prefixes is None:  | 
 | 112 | +        prefixes = ["Drosophila", "MusMusculus", "Zebrafish"]  | 
 | 113 | + | 
 | 114 | +    for prefix in prefixes:  | 
 | 115 | +        conf_file = os.path.join(gt_dir, f"{prefix}_1_iitest_confidence.tif")  | 
 | 116 | +        annot_file = os.path.join(gt_dir, f"{prefix}_1_iitest_annotations.tif")  | 
 | 117 | +        conf_arr = tifffile.imread(conf_file)  | 
 | 118 | +        gt_arr = tifffile.imread(annot_file)  | 
 | 119 | + | 
 | 120 | +        seg_file = os.path.join(pred_dir, f"{prefix}_1_iitest_seg.tif")  | 
 | 121 | +        seg_arr = tifffile.imread(seg_file)  | 
 | 122 | + | 
 | 123 | +        # find largest overlap of ground truth mask with each segmentation instance  | 
 | 124 | +        out_path = os.path.join(output_folder, f"{prefix}_matching_ref_gt.json")  | 
 | 125 | +        if os.path.isfile(out_path) and not force_overwrite:  | 
 | 126 | +            print(f"Skipping the creation of {out_path}. File already exists.")  | 
 | 127 | +        else:  | 
 | 128 | +            # exclude detections with more than 50% of pixels in undefined category  | 
 | 129 | +            if 1 in np.unique(conf_arr)[1:]:  | 
 | 130 | +                labels_undefined_mask = find_overlapping_masks(conf_arr, seg_arr, label_id_base=1)  | 
 | 131 | +            else:  | 
 | 132 | +                labels_undefined_mask = []  | 
 | 133 | +                print("Array does not contain undefined mask")  | 
 | 134 | + | 
 | 135 | +            find_matching_masks(gt_arr, seg_arr, out_path, labels_undefined_mask=labels_undefined_mask)  | 
 | 136 | + | 
 | 137 | +        # find largest overlap of segmentation instance with each ground truth mask  | 
 | 138 | +        out_path = os.path.join(output_folder, f"{prefix}_matching_gt_ref.json")  | 
 | 139 | +        if os.path.isfile(out_path) and not force_overwrite:  | 
 | 140 | +            print(f"Skipping the creation of {out_path}. File already exists.")  | 
 | 141 | +        else:  | 
 | 142 | +            find_matching_masks(seg_arr, gt_arr, out_path)  | 
 | 143 | + | 
 | 144 | + | 
 | 145 | +def main():  | 
 | 146 | +    parser = argparse.ArgumentParser()  | 
 | 147 | +    parser.add_argument("--output_folder", "-o", required=True)  | 
 | 148 | +    parser.add_argument("--prefix", "-p", nargs="+", type=str, default=None)  | 
 | 149 | +    parser.add_argument("--force", action="store_true", help="Forcefully overwrite output.")  | 
 | 150 | +    args = parser.parse_args()  | 
 | 151 | + | 
 | 152 | +    filter_true_positives(  | 
 | 153 | +        args.output_folder,  | 
 | 154 | +        args.prefix,  | 
 | 155 | +        args.force,  | 
 | 156 | +    )  | 
 | 157 | + | 
 | 158 | + | 
 | 159 | +if __name__ == "__main__":  | 
 | 160 | +    main()  | 
0 commit comments