#!/usr/bin/env python3 """Score segmentation predictions on a real_ours split with the paper's metrics. Predictions are label-map PNGs in --pred-dir, one per image, named like the image (`row["image"]["path"]`, e.g. 0f4eab9c-frame_003200.png) and the same size as the image. Reported (in %): mIoU, mPrecision and mRecall over background plus the 10 classes with real-world examples, as in the paper's tables, the same means over the 10 classes only (fg_*), and per-class values. revolving_door has no real-world examples and is not scored. Examples: python tools/evaluate.py --pred-dir preds/ # dataset class ids python tools/evaluate.py --pred-dir preds/ --label-order checkpoint # raw output of a released mmseg checkpoint python tools/evaluate.py --pred-dir preds/ --gt-dir data/navable/ann_dir/test """ from __future__ import annotations import argparse import json import sys from pathlib import Path import numpy as np from PIL import Image sys.path.insert(0, str(Path(__file__).resolve().parent)) import navable as nv # noqa: E402 def ground_truth(args): """Yield (file name, label map) for every image of the split.""" if args.gt_dir: for f in sorted(args.gt_dir.glob("*.png")): yield f.name, nv.mask_array(Image.open(f)) return files = nv.parquet_files("real_ours", args.split, args.data_dir) for row in nv.iter_rows(files, columns=["image.path", "mask"]): yield Path(nv.row_name(row)).stem + ".png", nv.mask_array(row["mask"]) def print_table(r: dict) -> None: print(f"\n{'class':<20}{'IoU':>8}{'Prec':>8}{'Rec':>8}") for name in nv.CLASSES: c = r["per_class"][name] if c["gt_pixels"] or name in ("background",): print(f"{name:<20}{c['IoU']:8.2f}{c['precision']:8.2f}{c['recall']:8.2f}") print(f"\n{'paper (bg + 10)':<20}{r['mIoU']:8.2f}{r['mPrecision']:8.2f}{r['mRecall']:8.2f}") print(f"{'10 classes only':<20}{r['fg_mIoU']:8.2f}{r['fg_mPrecision']:8.2f}{r['fg_mRecall']:8.2f}") def main() -> int: p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) p.add_argument("--pred-dir", type=Path, required=True) p.add_argument("--split", choices=nv.CONFIGS["real_ours"], default="test") p.add_argument("--label-order", choices=["dataset", "checkpoint", "checkpoint-fg"], default="dataset", help="label ids in the predictions: dataset class ids, a released mmseg checkpoint's " "order (12 labels), or SAN's order without background (11 labels)") p.add_argument("--gt-dir", type=Path, help="ground-truth label PNGs (e.g. from tools/export.py) instead of the Hub") p.add_argument("--data-dir", type=Path, help="downloaded copy of the repo (see tools/download.py)") p.add_argument("--out", type=Path, help="write the full results as JSON") args = p.parse_args() metrics, missing, n = nv.SegmentationMetrics(), [], 0 for name, gt in ground_truth(args): f = args.pred_dir / name if not f.exists(): missing.append(name) continue pred = np.asarray(Image.open(f)) if args.label_order != "dataset": pred = nv.checkpoint_to_dataset_labels(pred, has_background=args.label_order == "checkpoint") metrics.update(pred, gt) n += 1 if missing: print(f"{len(missing)} images have no prediction in {args.pred_dir} (e.g. {missing[:3]})") return 1 r = metrics.results() print(f"real_ours/{args.split}: {n} images") print_table(r) if args.out: args.out.write_text(json.dumps({"split": args.split, "images": n, **r}, indent=1)) print(f"\nresults -> {args.out}") return 0 if __name__ == "__main__": sys.exit(main())