| """ |
| V4: Evaluate all full-data conditions on the validation set. |
| Supports kvasir (binary), cvc (binary), refuge2 (3-class). |
| Saves predicted masks, overlay visualizations, and per-image metrics. |
| |
| Usage: |
| CUDA_VISIBLE_DEVICES=0 python scripts/v4_eval_fulldata.py --dataset kvasir |
| CUDA_VISIBLE_DEVICES=0 python scripts/v4_eval_fulldata.py --dataset cvc |
| CUDA_VISIBLE_DEVICES=0 python scripts/v4_eval_fulldata.py --dataset refuge2 |
| """ |
| import sys |
| sys.path.insert(0, "/data/sichengli/Code/PixelGen") |
|
|
| import argparse |
| import os |
| import json |
| import random |
| import numpy as np |
| import torch |
| from torch.utils.data import Dataset, DataLoader |
| from PIL import Image |
| import torchvision.transforms as transforms |
| import torchvision.transforms.functional as TF |
| import segmentation_models_pytorch as smp |
|
|
| from segmentation.metrics import compute_dice_iou_binary, compute_dice_iou_multiclass |
|
|
|
|
| |
| DATASET_CONFIGS = { |
| "kvasir": { |
| "data_root": "/data2/sichengli/Data/test/Segmentation/Kvasir-SEG/Kvasir-SEG", |
| "img_subdir": "images", "mask_subdir": "masks", |
| "file_ext": (".jpg", ".png", ".jpeg"), |
| "multi_split": False, "train_ratio": 0.9, |
| "task": "binary", "num_classes": 1, |
| }, |
| "cvc": { |
| "data_root": "/data2/sichengli/Data/test/Segmentation/CVC-ClinicDB", |
| "img_subdir": "PNG/Original", "mask_subdir": "PNG/Ground Truth", |
| "file_ext": (".png",), |
| "multi_split": False, "train_ratio": 0.9, |
| "task": "binary", "num_classes": 1, |
| }, |
| "refuge2": { |
| "data_root": "/data2/sichengli/Data/test/Segmentation/REFUGE2", |
| "splits": ["train", "val"], |
| "file_ext": (".jpg", ".png", ".jpeg"), |
| "mask_ext": (".bmp", ".png"), |
| "multi_split": True, "val_ratio": 0.1, |
| "task": "multiclass", "num_classes": 3, |
| "class_mapping": {0: 0, 128: 1, 255: 2}, |
| }, |
| } |
|
|
| WORK_DIR_BASE = "/data/sichengli/Code/PixelGen/synergy_v4_workdir" |
| RESOLUTION = 256 |
| SPLIT_SEED = 42 |
| EVAL_SEED = 42 |
|
|
| IMAGENET_MEAN = [0.485, 0.456, 0.406] |
| IMAGENET_STD = [0.229, 0.224, 0.225] |
|
|
| CONDITIONS = ["no_aug", "baseline", "cycle", "consist", "cycle_consist"] |
|
|
|
|
| |
| def process_mask(mask_pil, task, class_mapping=None): |
| mask_np = np.array(mask_pil) |
| if task == "binary": |
| mask_np = (mask_np > 127).astype(np.float32) |
| return torch.from_numpy(mask_np).unsqueeze(0) |
| else: |
| result = np.zeros_like(mask_np, dtype=np.int64) |
| for pixel_val, class_idx in class_mapping.items(): |
| result[mask_np == pixel_val] = class_idx |
| for pixel_val in np.unique(mask_np): |
| if pixel_val not in class_mapping: |
| closest = min(class_mapping.keys(), key=lambda x: abs(x - pixel_val)) |
| result[mask_np == pixel_val] = class_mapping[closest] |
| return torch.from_numpy(result).long() |
|
|
|
|
| |
| class ValDataset(Dataset): |
| """Validation set with filenames preserved.""" |
| def __init__(self, dataset_name): |
| cfg = DATASET_CONFIGS[dataset_name] |
| self.task = cfg["task"] |
| self.class_mapping = cfg.get("class_mapping") |
| self.normalize = transforms.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD) |
|
|
| if cfg["multi_split"]: |
| all_pairs = [] |
| for s in cfg["splits"]: |
| img_dir = os.path.join(cfg["data_root"], s, "images") |
| mask_dir = os.path.join(cfg["data_root"], s, "mask") |
| img_files = sorted([f for f in os.listdir(img_dir) if f.endswith(cfg["file_ext"])]) |
| for img_f in img_files: |
| base = os.path.splitext(img_f)[0] |
| img_path = os.path.join(img_dir, img_f) |
| for ext in cfg["mask_ext"]: |
| candidate = os.path.join(mask_dir, base + ext) |
| if os.path.exists(candidate): |
| all_pairs.append((img_path, candidate, f"{s}_{base}")) |
| break |
| random.seed(SPLIT_SEED) |
| |
| pairs_for_shuffle = [(ip, mp) for ip, mp, _ in all_pairs] |
| fnames_for_shuffle = [fn for _, _, fn in all_pairs] |
| combined = list(zip(pairs_for_shuffle, fnames_for_shuffle)) |
| random.shuffle(combined) |
| split_idx = int(len(combined) * (1 - cfg.get("val_ratio", 0.1))) |
| val_combined = combined[split_idx:] |
| self.pairs = [(ip, mp, fn) for (ip, mp), fn in val_combined] |
| else: |
| img_dir = os.path.join(cfg["data_root"], cfg["img_subdir"]) |
| mask_dir = os.path.join(cfg["data_root"], cfg["mask_subdir"]) |
| all_files = sorted([f for f in os.listdir(img_dir) if f.endswith(cfg["file_ext"])]) |
| random.seed(SPLIT_SEED) |
| indices = list(range(len(all_files))) |
| random.shuffle(indices) |
| split_idx = int(len(indices) * cfg["train_ratio"]) |
| val_indices = indices[split_idx:] |
| val_files = [all_files[i] for i in sorted(val_indices)] |
| self.pairs = [] |
| for f in val_files: |
| ip = os.path.join(img_dir, f) |
| mp = os.path.join(mask_dir, f) |
| if os.path.exists(mp): |
| self.pairs.append((ip, mp, os.path.splitext(f)[0])) |
|
|
| print(f"[ValDataset-{dataset_name}] {len(self.pairs)} validation samples") |
|
|
| def __len__(self): |
| return len(self.pairs) |
|
|
| def __getitem__(self, idx): |
| img_path, mask_path, fname = self.pairs[idx] |
| image = Image.open(img_path).convert("RGB") |
| mask = Image.open(mask_path).convert("L") |
|
|
| image = TF.resize(image, (RESOLUTION, RESOLUTION), |
| interpolation=transforms.InterpolationMode.BILINEAR) |
| mask = TF.resize(mask, (RESOLUTION, RESOLUTION), |
| interpolation=transforms.InterpolationMode.NEAREST) |
|
|
| image_tensor = self.normalize(TF.to_tensor(image)) |
| mask_tensor = process_mask(mask, self.task, self.class_mapping) |
| raw_image = TF.to_tensor(image) |
|
|
| return image_tensor, mask_tensor, raw_image, fname |
|
|
|
|
| |
| def make_overlay_binary(raw_img, gt_mask, pred_mask): |
| img_np = (raw_img.permute(1, 2, 0).numpy() * 255).astype(np.uint8) |
|
|
| gt_overlay = img_np.copy() |
| gt_overlay[gt_mask > 0.5, 1] = np.clip(gt_overlay[gt_mask > 0.5, 1].astype(np.int32) + 100, 0, 255).astype(np.uint8) |
|
|
| pred_overlay = img_np.copy() |
| tp = (pred_mask > 0.5) & (gt_mask > 0.5) |
| fp = (pred_mask > 0.5) & (gt_mask < 0.5) |
| fn = (pred_mask < 0.5) & (gt_mask > 0.5) |
| pred_overlay[tp, 1] = np.clip(pred_overlay[tp, 1].astype(np.int32) + 100, 0, 255).astype(np.uint8) |
| pred_overlay[fp, 0] = np.clip(pred_overlay[fp, 0].astype(np.int32) + 100, 0, 255).astype(np.uint8) |
| pred_overlay[fn, 2] = np.clip(pred_overlay[fn, 2].astype(np.int32) + 100, 0, 255).astype(np.uint8) |
|
|
| return Image.fromarray(np.concatenate([img_np, gt_overlay, pred_overlay], axis=1)) |
|
|
|
|
| def make_overlay_multiclass(raw_img, gt_mask, pred_mask, num_classes=3): |
| """Colors: class1=green, class2=blue.""" |
| img_np = (raw_img.permute(1, 2, 0).numpy() * 255).astype(np.uint8) |
| colors = {1: np.array([0, 100, 0]), 2: np.array([0, 0, 100])} |
|
|
| gt_overlay = img_np.copy() |
| for c, delta in colors.items(): |
| mask_c = gt_mask == c |
| for ch in range(3): |
| gt_overlay[mask_c, ch] = np.clip(gt_overlay[mask_c, ch].astype(np.int32) + delta[ch], 0, 255).astype(np.uint8) |
|
|
| pred_overlay = img_np.copy() |
| for c, delta in colors.items(): |
| tp = (pred_mask == c) & (gt_mask == c) |
| fp = (pred_mask == c) & (gt_mask != c) |
| for ch in range(3): |
| pred_overlay[tp, ch] = np.clip(pred_overlay[tp, ch].astype(np.int32) + delta[ch], 0, 255).astype(np.uint8) |
| pred_overlay[fp, 0] = np.clip(pred_overlay[fp, 0].astype(np.int32) + 100, 0, 255).astype(np.uint8) |
|
|
| |
| fn = (pred_mask == 0) & (gt_mask > 0) |
| pred_overlay[fn, 2] = np.clip(pred_overlay[fn, 2].astype(np.int32) + 100, 0, 255).astype(np.uint8) |
|
|
| return Image.fromarray(np.concatenate([img_np, gt_overlay, pred_overlay], axis=1)) |
|
|
|
|
| |
| @torch.no_grad() |
| def evaluate_condition(condition, device, dataset_name, loader, task, num_classes, out_dir, work_dir): |
| ckpt_path = os.path.join(work_dir, "checkpoints", f"full_{condition}_seed{EVAL_SEED}", "best.pth") |
| if not os.path.exists(ckpt_path): |
| print(f" [SKIP] {ckpt_path} not found") |
| return None |
|
|
| out_classes = 1 if task == "binary" else num_classes |
| model = smp.Unet(encoder_name="resnet34", encoder_weights="imagenet", |
| in_channels=3, classes=out_classes) |
| ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False) |
| model.load_state_dict(ckpt["model_state_dict"]) |
| model = model.to(device).eval() |
| print(f" Loaded: {os.path.basename(ckpt_path)} (best_dice={ckpt['best_dice']:.4f}, epoch={ckpt['epoch']})") |
|
|
| cond_dir = os.path.join(out_dir, condition) |
| pred_dir = os.path.join(cond_dir, "predictions") |
| vis_dir = os.path.join(cond_dir, "visualizations") |
| os.makedirs(pred_dir, exist_ok=True) |
| os.makedirs(vis_dir, exist_ok=True) |
|
|
| per_image = [] |
| all_dices = [] |
| all_ious = [] |
|
|
| for images, masks, raw_images, fnames in loader: |
| images = images.to(device) |
| masks = masks.to(device) |
| bs = images.shape[0] |
| logits = model(images) |
|
|
| for i in range(bs): |
| fname = fnames[i] |
|
|
| if task == "binary": |
| dice, iou = compute_dice_iou_binary(logits[i:i+1], masks[i:i+1]) |
| pred_np = (torch.sigmoid(logits[i, 0]).cpu().numpy() > 0.5).astype(np.uint8) * 255 |
| overlay = make_overlay_binary( |
| raw_images[i].cpu(), |
| masks[i, 0].cpu().numpy(), |
| (torch.sigmoid(logits[i, 0]).cpu().numpy() > 0.5).astype(np.float32) |
| ) |
| else: |
| dice, iou, _, _ = compute_dice_iou_multiclass(logits[i:i+1], masks[i:i+1], num_classes) |
| pred_cls = logits[i].argmax(dim=0).cpu().numpy().astype(np.uint8) |
| |
| pred_np = (pred_cls * 127).astype(np.uint8) |
| overlay = make_overlay_multiclass( |
| raw_images[i].cpu(), |
| masks[i].cpu().numpy(), |
| pred_cls, |
| num_classes |
| ) |
|
|
| Image.fromarray(pred_np).save(os.path.join(pred_dir, f"{fname}.png")) |
| overlay.save(os.path.join(vis_dir, f"{fname}.png")) |
|
|
| per_image.append({"filename": fname, "dice": round(dice, 4), "iou": round(iou, 4)}) |
| all_dices.append(dice) |
| all_ious.append(iou) |
|
|
| mean_dice = float(np.mean(all_dices)) |
| mean_iou = float(np.mean(all_ious)) |
| std_dice = float(np.std(all_dices)) |
| std_iou = float(np.std(all_ious)) |
|
|
| result = { |
| "condition": condition, "seed": EVAL_SEED, "dataset": dataset_name, |
| "num_samples": len(per_image), |
| "mean_dice": round(mean_dice, 4), "std_dice": round(std_dice, 4), |
| "mean_iou": round(mean_iou, 4), "std_iou": round(std_iou, 4), |
| "per_image": per_image, |
| } |
| with open(os.path.join(cond_dir, "metrics.json"), "w") as f: |
| json.dump(result, f, indent=2) |
|
|
| print(f" {condition}: Dice={mean_dice:.4f}±{std_dice:.4f}, IoU={mean_iou:.4f}±{std_iou:.4f}") |
| return result |
|
|
|
|
| def main(): |
| parser = argparse.ArgumentParser() |
| parser.add_argument("--dataset", type=str, required=True, choices=["kvasir", "cvc", "refuge2"]) |
| args = parser.parse_args() |
|
|
| cfg = DATASET_CONFIGS[args.dataset] |
| task = cfg["task"] |
| num_classes = cfg["num_classes"] |
| device = torch.device("cuda:0") |
|
|
| work_dir = os.path.join(WORK_DIR_BASE, args.dataset) |
| out_dir = os.path.join(work_dir, "eval_fulldata") |
| os.makedirs(out_dir, exist_ok=True) |
|
|
| dataset = ValDataset(args.dataset) |
| loader = DataLoader(dataset, batch_size=16, shuffle=False, num_workers=4, pin_memory=True) |
|
|
| print(f"\n{'='*60}") |
| print(f" V4 Full-Data Eval: {args.dataset} ({task})") |
| print(f" Checkpoint seed: {EVAL_SEED}") |
| print(f"{'='*60}\n") |
|
|
| all_results = {} |
| for condition in CONDITIONS: |
| print(f"\n--- {condition} ---") |
| result = evaluate_condition(condition, device, args.dataset, loader, |
| task, num_classes, out_dir, work_dir) |
| if result is not None: |
| all_results[condition] = { |
| "mean_dice": result["mean_dice"], "std_dice": result["std_dice"], |
| "mean_iou": result["mean_iou"], "std_iou": result["std_iou"], |
| } |
|
|
| |
| print(f"\n{'='*60}") |
| print(f" {args.dataset.upper()} SUMMARY (seed={EVAL_SEED})") |
| print(f"{'='*60}") |
| print(f"{'Condition':<18s} | {'Dice':>12s} | {'IoU':>12s} | {'vs baseline':>12s}") |
| print("-" * 60) |
| bl = all_results.get("baseline", {}).get("mean_dice") |
| for cond in CONDITIONS: |
| if cond not in all_results: |
| continue |
| r = all_results[cond] |
| d_str = f"{r['mean_dice']:.4f}±{r['std_dice']:.4f}" |
| i_str = f"{r['mean_iou']:.4f}±{r['std_iou']:.4f}" |
| delta = f"{r['mean_dice'] - bl:+.4f}" if bl and cond != "baseline" else "-" |
| print(f"{cond:<18s} | {d_str:>12s} | {i_str:>12s} | {delta:>12s}") |
| print("=" * 60) |
|
|
| with open(os.path.join(out_dir, "summary.json"), "w") as f: |
| json.dump(all_results, f, indent=2) |
| print(f"\nResults saved to: {out_dir}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|