#!/usr/bin/env python3 """Compare ImageJ Analyze Particles output with synthetic ground truth. Ground-truth set = particles NOT touching the image border and area >= 20 px (same rules as the macro: exclude on edges, size >= 20 px^2). IoU>=0.5 -> matched (TP). merged : a predicted object that covers >=30% of the area of >=2 distinct GT particles split : a GT particle that is covered (>=30% of the predicted object's area) by >=2 predicted objects """ import os, re, glob import numpy as np, pandas as pd, tifffile SCALE_UM = 0.5 IOU_T = 0.5 FRAC_T = 0.3 OUT = 'fiji_output' IMAGES = ['A_clear', 'B_noisy', 'C_touching'] METHODS = ['Default', 'Huang', 'Intermodes', 'IsoData', 'Li', 'MaxEntropy', 'Mean', 'MinError', 'Minimum', 'Moments', 'Otsu', 'Percentile', 'RenyiEntropy', 'Shanbhag', 'Triangle', 'Yen'] WARN = {('A_clear', 'MinError'): 'ImageJ log: "MinError(I): NaN, not converging"', ('B_noisy', 'MinError'): 'ImageJ log: "MinError(I): NaN, not converging"'} def contingency(gt, pr): ng, npr = gt.max() + 1, pr.max() + 1 m = np.zeros((ng, npr), np.int64) np.add.at(m, (gt.ravel(), pr.ravel()), 1) return m rows, per_particle = [], [] for img in IMAGES: gt = tifffile.imread(f'ground_truth/{img}_gt_labels.tif').astype(np.int64) gtp = pd.read_csv(f'ground_truth/{img}_gt_particles.csv') ev_ids = set(gtp[gtp.evaluable].gt_id) gt_ev = np.where(np.isin(gt, list(ev_ids)), gt, 0) gt_area_px = {i: int(a) for i, a in zip(gtp.gt_id, gtp.area_px)} gt_total_um2 = gtp[gtp.evaluable].area_um2.sum() for m in METHODS: tag = f'{img}__{m}' info = dict(l.strip().split('=', 1) for l in open(f'{OUT}/{tag}_run.txt') if '=' in l) pr = tifffile.imread(f'{OUT}/{tag}_countmask.tif').astype(np.int64) csvp = f'{OUT}/{tag}_results.csv' res = pd.read_csv(csvp) if os.path.exists(csvp) else pd.DataFrame(columns=['Area']) n_pred = int(info['count']) pred_um2 = float(res['Area'].sum()) if len(res) else 0.0 pred_px = {i: int((pr == i).sum()) for i in range(1, pr.max() + 1)} M = contingency(gt_ev, pr) # rows: gt id, cols: pred id tp = 0; ious = []; dices = []; matched_pred = set(); matched_gt = set() for g in ev_ids: for p in range(1, M.shape[1]): inter = M[g, p] if inter == 0: continue iou = inter / (gt_area_px[g] + pred_px[p] - inter) if iou >= IOU_T: tp += 1; ious.append(iou); dices.append(2 * inter / (gt_area_px[g] + pred_px[p])) matched_pred.add(p); matched_gt.add(g) fn = len(ev_ids) - tp fp = n_pred - tp merged = split = 0; merged_gt = set(); split_gt = set() for p in range(1, M.shape[1]): cov = [g for g in ev_ids if M[g, p] >= FRAC_T * gt_area_px[g] and M[g, p] > 0] if len(cov) >= 2: merged += 1; merged_gt.update(cov) for g in ev_ids: cov = [p for p in range(1, M.shape[1]) if M[g, p] >= FRAC_T * pred_px[p] and M[g, p] > 0] if len(cov) >= 2: split += 1; split_gt.add(g) gt_fg = gt_ev > 0; pr_fg = pr > 0 inter = (gt_fg & pr_fg).sum() pix_dice = 2 * inter / (gt_fg.sum() + pr_fg.sum()) n_gt = len(ev_ids) rows.append(dict(image=img, method=m, threshold_upper=int(float(info['threshold_upper'])), gt_count=n_gt, fiji_count=n_pred, count_error=n_pred - n_gt, count_rel_error_pct=100 * (n_pred - n_gt) / n_gt, gt_area_um2=gt_total_um2, fiji_area_um2=pred_um2, area_rel_error_pct=100 * (pred_um2 - gt_total_um2) / gt_total_um2, TP=tp, FP=fp, FN=fn, precision=tp / n_pred if n_pred else np.nan, recall=tp / n_gt, F1=2 * tp / (n_pred + n_gt), mean_IoU_matched=np.mean(ious) if ious else np.nan, mean_Dice_matched=np.mean(dices) if dices else np.nan, pixel_Dice=pix_dice, merged_objects=merged, GT_in_merges=len(merged_gt), split_GT=split, warning=WARN.get((img, m), ''))) for g in sorted(ev_ids): status = 'matched' if g in matched_gt else ('merged' if g in merged_gt else ('split' if g in split_gt else 'missed')) per_particle.append(dict(image=img, method=m, gt_id=g, gt_area_px=gt_area_px[g], status=status)) df = pd.DataFrame(rows) df.to_csv('results/summary_metrics.csv', index=False) pd.DataFrame(per_particle).to_csv('results/per_particle_status.csv', index=False) pd.set_option('display.width', 250); pd.set_option('display.max_columns', 30) print(df[['image', 'method', 'gt_count', 'fiji_count', 'count_error', 'area_rel_error_pct', 'TP', 'FP', 'FN', 'F1', 'mean_IoU_matched', 'merged_objects', 'split_GT']].round(3).to_string(index=False))