""" eval_utils.py — shared utilities for ChestX-ray8 grounding evaluation. Coordinate conventions ────────────────────── GT : BBox_List_2017.csv stores (x, y, w, h) absolute pixels on a 1024×1024 image. Loaded → converted to (x1, y1, x2, y2) absolute pixels for IoU. Pred : Lingshu / Qwen2.5-VL natively outputs [x1, y1, x2, y2] in range [0, 1000]. We ask for this format in the prompt (unambiguous, no heuristic needed). parse_xyxy_1000() → scale by (image_size / 1000) → absolute pixels. If a future model outputs a different format, use the explicit helpers parse_xywh_abs() or parse_norm_xywh() instead. Fallback : parse_bbox_from_text() tries xyxy-1000 first, then heuristic fallbacks, and returns (x1,y1,x2,y2) absolute pixels or None on failure. Missing prediction : IoU = 0.0 (未检出 treated as worst case). """ import re import json import numpy as np import pandas as pd from pathlib import Path from typing import Optional # ───────────────────────────────────────────────────────────────────────────── # 1. BBox conversion helpers # ───────────────────────────────────────────────────────────────────────────── def xywh_to_xyxy(x, y, w, h): """(x_topleft, y_topleft, width, height) → (x1, y1, x2, y2) absolute.""" return float(x), float(y), float(x) + float(w), float(y) + float(h) def xyxy_to_xywh(x1, y1, x2, y2): return x1, y1, x2 - x1, y2 - y1 def scale_xyxy(box, src_size: int, dst_size: int): """Rescale an (x1,y1,x2,y2) box from src_size to dst_size coordinate space.""" ratio = dst_size / src_size return tuple(v * ratio for v in box) # ───────────────────────────────────────────────────────────────────────────── # 2. IoU / IoBB # ───────────────────────────────────────────────────────────────────────────── def compute_iou(box_a, box_b) -> float: """Standard IoU between two (x1,y1,x2,y2) boxes.""" if box_a is None or box_b is None: return 0.0 ix1 = max(box_a[0], box_b[0]) iy1 = max(box_a[1], box_b[1]) ix2 = min(box_a[2], box_b[2]) iy2 = min(box_a[3], box_b[3]) inter = max(0.0, ix2 - ix1) * max(0.0, iy2 - iy1) area_a = (box_a[2] - box_a[0]) * (box_a[3] - box_a[1]) area_b = (box_b[2] - box_b[0]) * (box_b[3] - box_b[1]) union = area_a + area_b - inter return inter / union if union > 0 else 0.0 def compute_iobb(pred_box, gt_box) -> float: """Intersection over predicted-Box area — used in original ChestX-ray8 paper.""" if pred_box is None or gt_box is None: return 0.0 ix1 = max(pred_box[0], gt_box[0]) iy1 = max(pred_box[1], gt_box[1]) ix2 = min(pred_box[2], gt_box[2]) iy2 = min(pred_box[3], gt_box[3]) inter = max(0.0, ix2 - ix1) * max(0.0, iy2 - iy1) area_pred = (pred_box[2] - pred_box[0]) * (pred_box[3] - pred_box[1]) return inter / area_pred if area_pred > 0 else 0.0 # ───────────────────────────────────────────────────────────────────────────── # 3. Dataset loading # ───────────────────────────────────────────────────────────────────────────── def load_bbox_csv(bbox_csv: str) -> pd.DataFrame: """ Load BBox_List_2017.csv. Real column names in the file (after pandas CSV parse): 'Image Index', 'Finding Label', 'Bbox [x', 'y', 'w', 'h]' (The bracket is split across columns by the comma separator.) Returns a clean DataFrame with columns: image_index, finding_label, x, y, w, h (all float for x/y/w/h) Note: 984 rows, 880 unique images, 8 disease classes. """ df = pd.read_csv(bbox_csv) df.columns = [c.strip() for c in df.columns] rename = {} for c in df.columns: lc = c.lower() if "image" in lc and "index" in lc: rename[c] = "image_index" elif "finding" in lc and "label" in lc: rename[c] = "finding_label" # CSV splits "Bbox [x" / "y" / "w" / "h]" — match each fragment elif re.search(r"bbox.*\[?x\]?$|^bbox \[x$", lc): rename[c] = "x" elif re.search(r"^y$", lc): rename[c] = "y" elif re.search(r"^w$", lc): rename[c] = "w" elif re.search(r"^h\]?$", lc): rename[c] = "h" df = df.rename(columns=rename) for col in ["x", "y", "w", "h"]: df[col] = df[col].astype(float) # drop stray unnamed columns df = df[[c for c in df.columns if not c.startswith("Unnamed")]] return df # ───────────────────────────────────────────────────────────────────────────── # 4. Output parsing # ───────────────────────────────────────────────────────────────────────────── _RE_FOUR_NUMS = re.compile( r"[\[\(]?\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)\s*[\]\)]?" ) def _clip_xyxy(x1, y1, x2, y2, image_size: int): x1 = max(0.0, min(float(x1), image_size)) y1 = max(0.0, min(float(y1), image_size)) x2 = max(0.0, min(float(x2), image_size)) y2 = max(0.0, min(float(y2), image_size)) return (x1, y1, x2, y2) if x2 > x1 and y2 > y1 else None def parse_xyxy_1000(text: str, image_size: int = 1024) -> Optional[tuple]: """ PRIMARY PARSER — for Qwen2.5-VL / Lingshu. Model is prompted to output [x1, y1, x2, y2] with values in [0, 1000] where (0,0) is top-left and (1000,1000) is bottom-right. Converts to absolute pixels: multiply by (image_size / 1000). Use this when the prompt explicitly requests the 0-1000 format. """ if not text: return None m = _RE_FOUR_NUMS.search(text) if not m: return None a, b, c, d = [float(v) for v in m.groups()] scale = image_size / 1000.0 return _clip_xyxy(a * scale, b * scale, c * scale, d * scale, image_size) def parse_xywh_abs(text: str, image_size: int = 1024) -> Optional[tuple]: """ Parser for models that output [x, y, w, h] in absolute pixels. (x,y) = top-left corner; w,h = width, height. """ if not text: return None m = _RE_FOUR_NUMS.search(text) if not m: return None x, y, w, h = [float(v) for v in m.groups()] return _clip_xyxy(x, y, x + w, y + h, image_size) def parse_norm_xywh(text: str, image_size: int = 1024) -> Optional[tuple]: """ Parser for models that output [x, y, w, h] normalised to [0, 1]. """ if not text: return None m = _RE_FOUR_NUMS.search(text) if not m: return None x, y, w, h = [float(v) for v in m.groups()] s = image_size return _clip_xyxy(x * s, y * s, (x + w) * s, (y + h) * s, image_size) def parse_bbox_from_text(text: str, image_size: int = 1024, coord_format: str = "xyxy_1000") -> Optional[tuple]: """ High-level dispatcher. coord_format options: "xyxy_1000" (default) — Qwen2.5-VL / Lingshu native "xywh_abs" — absolute pixel xywh "norm_xywh" — normalised 0-1 xywh "xyxy_abs" — absolute pixel xyxy All return (x1, y1, x2, y2) in absolute pixels, or None. NOTE on missing predictions (未检出): If the model produces no parseable box, this returns None. The caller should treat None as IoU = 0.0. """ if coord_format == "xyxy_1000": return parse_xyxy_1000(text, image_size) elif coord_format == "xywh_abs": return parse_xywh_abs(text, image_size) elif coord_format == "norm_xywh": return parse_norm_xywh(text, image_size) elif coord_format == "xyxy_abs": if not text: return None m = _RE_FOUR_NUMS.search(text) if not m: return None a, b, c, d = [float(v) for v in m.groups()] return _clip_xyxy(a, b, c, d, image_size) else: raise ValueError(f"Unknown coord_format: {coord_format!r}") # ───────────────────────────────────────────────────────────────────────────── # 5. Evaluation aggregation # ───────────────────────────────────────────────────────────────────────────── def evaluate_predictions(records: list, iou_thresholds=(0.1, 0.25, 0.5)) -> dict: """ records: list of dicts with keys: image_index : str finding_label : str gt_xyxy : (x1,y1,x2,y2) absolute pixels pred_xyxy : (x1,y1,x2,y2) absolute pixels, or None → IoU = 0 Returns metrics dict. """ from collections import defaultdict thresholds = list(iou_thresholds) per_class = defaultdict(lambda: {"ious": [], **{t: [] for t in thresholds}}) all_ious = [] parse_fail = 0 for r in records: pred = r.get("pred_xyxy") if pred is None: parse_fail += 1 iou = 0.0 else: iou = compute_iou(r["gt_xyxy"], pred) label = r["finding_label"] all_ious.append(iou) per_class[label]["ious"].append(iou) for t in thresholds: per_class[label][t].append(float(iou >= t)) overall = {} for t in thresholds: hits = [float(iou >= t) for iou in all_ious] overall[f"hit@{t}"] = float(np.mean(hits)) if hits else 0.0 per_class_summary = {} for label, d in per_class.items(): per_class_summary[label] = { "mean_iou": float(np.mean(d["ious"])) if d["ious"] else 0.0, **{f"hit@{t}": float(np.mean(d[t])) if d[t] else 0.0 for t in thresholds}, } return { "n_instances": len(records), "parse_fail": parse_fail, "parse_fail_rate": parse_fail / max(len(records), 1), "mean_iou": float(np.mean(all_ious)) if all_ious else 0.0, "overall": overall, "per_class": per_class_summary, } # ───────────────────────────────────────────────────────────────────────────── # 6. I/O helpers # ───────────────────────────────────────────────────────────────────────────── def print_results(metrics: dict, model_name: str = "Model"): print(f"\n{'='*62}") print(f" {model_name}") print(f" ChestX-ray8 Grounding (984 instances, 880 images, 8 classes)") print(f"{'='*62}") print(f" Total instances : {metrics['n_instances']}") print(f" Parse failures : {metrics['parse_fail']} " f"({metrics['parse_fail_rate']:.1%})") print(f" Mean IoU : {metrics['mean_iou']:.4f}") print() print(" Overall:") for k, v in metrics["overall"].items(): print(f" {k:12s} : {v:.4f}") print() print(f" {'Class':<22} {'Hit@0.1':>8} {'Hit@0.25':>9} {'Hit@0.5':>8} {'mIoU':>8}") print(f" {'-'*22} {'-'*8} {'-'*9} {'-'*8} {'-'*8}") for label, d in sorted(metrics["per_class"].items()): print(f" {label:<22} " f"{d.get('hit@0.1',0):.4f} " f"{d.get('hit@0.25',0):.4f} " f"{d.get('hit@0.5',0):.4f} " f"{d.get('mean_iou',0):.4f}") print(f"{'='*62}\n") def save_results(metrics: dict, records: list, out_dir: str, prefix: str): out_path = Path(out_dir) out_path.mkdir(parents=True, exist_ok=True) with open(out_path / f"{prefix}_metrics.json", "w") as f: json.dump(metrics, f, indent=2) rows = [] for r in records: pred = r.get("pred_xyxy") rows.append({ "image_index": r["image_index"], "finding_label": r["finding_label"], "gt_x1": r["gt_xyxy"][0], "gt_y1": r["gt_xyxy"][1], "gt_x2": r["gt_xyxy"][2], "gt_y2": r["gt_xyxy"][3], "pred_x1": pred[0] if pred else None, "pred_y1": pred[1] if pred else None, "pred_x2": pred[2] if pred else None, "pred_y2": pred[3] if pred else None, "iou": r.get("iou", 0.0), "raw_output": r.get("raw_output", ""), }) pd.DataFrame(rows).to_csv(out_path / f"{prefix}_instances.csv", index=False) print(f"[saved] {out_path}/{prefix}_metrics.json + _instances.csv")