#!/usr/bin/env python3 """RipBench semantic-segmentation evaluator (framework-agnostic). HOW TO USE (no CLI args - edit CONFIG below, then: python evaluate_semantic.py in any env with numpy). Consumes the _confmat_.npz files that predict_semantic.py writes (per-image 4x4 GT-x-pred pixel confusion matrices), sums them per split, and appends one TSV row per model x split to eval/results/semantic_segmentation_eval.tsv. No threshold protocol - semantic predictions are argmax maps, so every metric is threshold-free: per-class IoU (rip_current first - the headline), mIoU, pixel accuracy, mean per-class accuracy (macc). Per-video breakdowns for the insights analysis aggregate the SAME npz files by video id. """ import glob import os _RIPBENCH_ROOT = os.environ.get("RIPBENCH_ROOT", os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", ".."))) # release root (env RIPBENCH_ROOT overrides) from datetime import datetime import numpy as np # --- CONFIG ------------------------------------------------------------------- PRED_DIR = _RIPBENCH_ROOT + "/models/semantic_segmentation/best_models/predictions" SPLITS = ("val", "test") OUT_TSV = os.path.join(os.path.dirname(os.path.abspath(__file__)), "results", "semantic_segmentation_eval.tsv") # ------------------------------------------------------------------------------ CLASSES = ("rip_current", "water", "land", "sky") # train ids 0..3 HEADER = ("timestamp\tmodel\ttask\tsplit\tn_images" "\tmIoU\tIoU_rip_current\tIoU_water\tIoU_land\tIoU_sky" "\tpixel_acc\tmacc\n") def metrics(conf): """conf: [4,4] float64, rows GT, cols pred.""" tp = np.diag(conf) fp = conf.sum(0) - tp fn = conf.sum(1) - tp denom = tp + fp + fn iou = np.where(denom > 0, tp / np.maximum(denom, 1), np.nan) acc = np.where(conf.sum(1) > 0, tp / np.maximum(conf.sum(1), 1), np.nan) return {"iou": iou, "miou": float(np.nanmean(iou)), "pixel_acc": float(tp.sum() / conf.sum()), "macc": float(np.nanmean(acc))} def main(): os.makedirs(os.path.dirname(OUT_TSV), exist_ok=True) write_header = not os.path.isfile(OUT_TSV) pairs = {} for f in sorted(glob.glob(os.path.join(PRED_DIR, "*_confmat_*.npz"))): base = os.path.basename(f) stem, split = base.rsplit("_confmat_", 1) pairs.setdefault(stem, {})[split.removesuffix(".npz")] = f print(f"{len(pairs)} model(s) in {PRED_DIR}") with open(OUT_TSV, "a") as out: if write_header: out.write(HEADER) for stem, files in pairs.items(): for split in SPLITS: if split not in files: print(f"SKIP {stem}: no {split} confmat") continue data = np.load(files[split], allow_pickle=False) conf = data["confmat"].sum(0).astype(np.float64) m = metrics(conf) row = [datetime.now().strftime("%Y-%m-%d %H:%M"), stem, "semantic_segmentation", split, len(data["stems"]), f"{m['miou']:.6f}"] + [f"{v:.6f}" for v in m["iou"]] + [ f"{m['pixel_acc']:.6f}", f"{m['macc']:.6f}"] out.write("\t".join(str(x) for x in row) + "\n") print(f"[{split}] {stem}: mIoU={m['miou']:.4f} " f"rip-IoU={m['iou'][0]:.4f} pixAcc={m['pixel_acc']:.4f}") print(f"rows appended to {OUT_TSV}") if __name__ == "__main__": main()