diffcr-datasets / eval /plot.py
XavierJiezou's picture
Upload visualization folder
dfe630b verified
"""
eval/plot.py
Generate comparison figures for all cloud-removal methods.
The script reads from the cleaned-up directory layout created by migrate.py:
visualization/
├── data/
│ ├── Sen2_MTC_New/
│ │ ├── GT/ {id}.png
│ │ └── inputs/ {id}_A1.png {id}_A2.png {id}_A3.png
│ └── Sen2_MTC_Old/
│ ├── GT/
│ └── inputs/
└── results/
├── Sen2_MTC_New/{method}/{id}.png
└── Sen2_MTC_Old/{method}/{id}.png
Usage
-----
# Generate the exact figures that appear in the paper:
python plot.py --paper-samples
# Generate paper figures for one dataset only:
python plot.py --paper-samples --dataset Sen2_MTC_New
python plot.py --paper-samples --dataset Sen2_MTC_Old
# Generate a figure for any arbitrary sample ID:
python plot.py --dataset Sen2_MTC_New --id T12TUR_R027_55
# List all available sample IDs for a dataset:
python plot.py --dataset Sen2_MTC_New --list
# Custom output directory:
python plot.py --paper-samples --out-dir /path/to/figures
"""
from __future__ import annotations
import argparse
import os
from glob import glob
from typing import Optional
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
matplotlib.rcParams["font.family"] = "Times New Roman"
# ---------------------------------------------------------------------------
# Paths
# ---------------------------------------------------------------------------
# eval/ is one level below the project root
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
DATASETS = ["Sen2_MTC_Old", "Sen2_MTC_New"]
# Display order in the 4×4 grid (row-major, after the 4 input/GT panels)
METHODS: list[str] = [
"mcgan",
"pix2pix",
"ae",
"stnet",
"dsen2cr",
"stgan",
"ctgan",
"crtsnet",
"pmaa",
"uncrtaints",
"ddpmcr",
"diffcr",
]
METHOD_LABELS: list[str] = [
"MCGAN",
"Pix2Pix",
"AE",
"STNet",
"DSen2-CR",
"STGAN",
"CTGAN",
"CR-TS-Net",
"PMAA",
"UnCRtainTS",
"DDPM-CR",
"DiffCR [Ours]",
]
INPUT_LABELS: list[str] = [
r"Cloudy $T_1$",
r"Cloudy $T_2$",
r"Cloudy $T_3$",
"Ground-Truth",
]
ALL_LABELS: list[str] = INPUT_LABELS + METHOD_LABELS
# Some methods in the Old dataset store outputs with a horizontal flip
# relative to the other methods' spatial convention. We correct for display.
FLIP_H_FOR_DISPLAY: dict[str, set[str]] = {
"Sen2_MTC_Old": {"diffcr"},
}
# The exact sample IDs used in the paper figures
PAPER_SAMPLES: dict[str, list[str]] = {
"Sen2_MTC_New": ["T12TUR_R027_55"],
"Sen2_MTC_Old": ["42WVD_70008000", "14SQB_20006000"],
}
# ---------------------------------------------------------------------------
# I/O helpers
# ---------------------------------------------------------------------------
def _find_input(inputs_dir: str, sample_id: str, channel: str) -> Optional[str]:
"""Locate {id}_A{1|2|3}.png in *inputs_dir*."""
direct = os.path.join(inputs_dir, f"{sample_id}_{channel}.png")
if os.path.exists(direct):
return direct
# Fallback – glob for any file containing the id and channel tag
hits = glob(os.path.join(inputs_dir, f"{sample_id}*{channel}*"))
return hits[0] if hits else None
def _load(path: str, flip_h: bool = False) -> np.ndarray:
"""Load an image as float [0,1] RGBA/RGB via matplotlib.
matplotlib.imread returns:
- PNG: float32 [0,1] (RGBA or RGB depending on file)
- other: uint8 [0,255]
We normalise everything to float32 [0,1] and strip the alpha channel.
"""
img = plt.imread(path)
# Normalise uint8 to float
if img.dtype == np.uint8:
img = img.astype(np.float32) / 255.0
# Drop alpha channel if present
if img.ndim == 3 and img.shape[2] == 4:
img = img[:, :, :3]
# Clip to valid range (handles tiny float rounding errors)
img = np.clip(img, 0.0, 1.0)
if flip_h:
img = img[:, ::-1, :]
return img
# ---------------------------------------------------------------------------
# Core plotting function
# ---------------------------------------------------------------------------
def plot_sample(
dataset: str,
sample_id: str,
out_dir: Optional[str] = None,
dpi: int = 300,
verbose: bool = True,
) -> Optional[str]:
"""Generate a 4×4 comparison grid for *sample_id* in *dataset*.
Returns the path of the saved figure, or None on failure.
"""
data_dir = os.path.join(ROOT, "data", dataset)
results_dir = os.path.join(ROOT, "results", dataset)
inputs_dir = os.path.join(data_dir, "inputs")
gt_dir = os.path.join(data_dir, "GT")
# ---- Locate source files -----------------------------------------------
a1 = _find_input(inputs_dir, sample_id, "A1")
a2 = _find_input(inputs_dir, sample_id, "A2")
a3 = _find_input(inputs_dir, sample_id, "A3")
gt = os.path.join(gt_dir, f"{sample_id}.png")
missing: list[str] = []
for tag, path in [("A1", a1), ("A2", a2), ("A3", a3), ("GT", gt)]:
if not path or not os.path.exists(path):
missing.append(tag)
if missing:
print(f"[WARN] {dataset}/{sample_id}: missing {missing} – skipping.")
return None
# ---- Build image grid --------------------------------------------------
flip_set = FLIP_H_FOR_DISPLAY.get(dataset, set())
grid: list[np.ndarray] = [
_load(a1),
_load(a2),
_load(a3),
_load(gt),
]
for method in METHODS:
pred_path = os.path.join(results_dir, method, f"{sample_id}.png")
flip = method in flip_set
if os.path.exists(pred_path):
grid.append(_load(pred_path, flip_h=flip))
else:
if verbose:
print(
f" [WARN] missing {dataset}/{method}/{sample_id}.png → black panel"
)
# Placeholder: black image with same shape as GT
grid.append(np.zeros_like(grid[3]))
assert len(grid) == 16, f"Expected 16 panels, got {len(grid)}"
# ---- Render figure -----------------------------------------------------
fig, axes = plt.subplots(4, 4, figsize=(8, 8), dpi=dpi)
fig.subplots_adjust(
left=0.01,
right=0.99,
top=0.99,
bottom=0.06,
wspace=0.04,
hspace=0.10,
)
for idx, (ax, img, label) in enumerate(zip(axes.flat, grid, ALL_LABELS)):
ax.imshow(img)
ax.set_title(label, y=-0.18, fontsize=7)
ax.axis("off")
# ---- Save --------------------------------------------------------------
if out_dir is None:
out_dir = os.path.join(ROOT, "eval", "plots")
os.makedirs(out_dir, exist_ok=True)
out_path = os.path.join(out_dir, f"{dataset}_{sample_id}.pdf")
fig.savefig(out_path, bbox_inches="tight")
plt.close(fig)
if verbose:
print(f"Saved: {out_path}")
return out_path
# ---------------------------------------------------------------------------
# Batch helpers
# ---------------------------------------------------------------------------
def available_ids(dataset: str) -> list[str]:
"""Return sorted list of sample IDs that have at least one input image."""
inputs_dir = os.path.join(ROOT, "data", dataset, "inputs")
a1_files = sorted(glob(os.path.join(inputs_dir, "*_A1.png")))
return [os.path.basename(f).replace("_A1.png", "") for f in a1_files]
def generate_paper_figures(
datasets: Optional[list[str]] = None,
out_dir: Optional[str] = None,
) -> list[str]:
"""Generate all figures referenced in the paper."""
if datasets is None:
datasets = DATASETS
saved: list[str] = []
for ds in datasets:
for sid in PAPER_SAMPLES.get(ds, []):
print(f"\n--- {ds} / {sid} ---")
path = plot_sample(ds, sid, out_dir=out_dir)
if path:
saved.append(path)
return saved
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
def _parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(
description="Generate comparison figures for cloud-removal methods"
)
p.add_argument(
"--dataset",
type=str,
default=None,
choices=DATASETS,
help="Dataset to use (default: both when --paper-samples is set)",
)
p.add_argument(
"--id",
type=str,
default=None,
metavar="SAMPLE_ID",
help="Generate a figure for this specific sample ID",
)
p.add_argument(
"--paper-samples",
action="store_true",
help="Generate the exact figures used in the paper",
)
p.add_argument(
"--all",
action="store_true",
help="Generate figures for ALL available samples in the chosen dataset",
)
p.add_argument(
"--list",
action="store_true",
help="List available sample IDs and exit",
)
p.add_argument(
"--out-dir",
type=str,
default=None,
help="Output directory (default: eval/plots/)",
)
p.add_argument(
"--dpi",
type=int,
default=300,
help="Figure resolution in DPI (default: 300)",
)
return p.parse_args()
def main() -> None:
args = _parse_args()
# Determine which datasets to process
if args.dataset:
datasets = [args.dataset]
else:
datasets = DATASETS
# ---- list mode ---------------------------------------------------------
if args.list:
for ds in datasets:
ids = available_ids(ds)
print(f"\n{ds} ({len(ids)} samples)")
for i, sid in enumerate(ids):
print(f" {sid}")
if i >= 29 and len(ids) > 30:
print(f" ... and {len(ids) - 30} more (use --all to see all)")
break
return
# ---- paper figures -----------------------------------------------------
if args.paper_samples:
saved = generate_paper_figures(datasets=datasets, out_dir=args.out_dir)
print(f"\n{len(saved)} figure(s) saved.")
return
# ---- single sample -----------------------------------------------------
if args.id:
if len(datasets) > 1:
print("[INFO] --id specified without --dataset; trying both datasets.")
for ds in datasets:
plot_sample(ds, args.id, out_dir=args.out_dir, dpi=args.dpi)
return
# ---- all samples -------------------------------------------------------
if args.all:
if not args.dataset:
print("[ERROR] Please specify --dataset when using --all.")
return
ids = available_ids(args.dataset)
print(f"Generating {len(ids)} figures for {args.dataset} …")
for sid in ids:
plot_sample(
args.dataset, sid, out_dir=args.out_dir, dpi=args.dpi, verbose=False
)
print(f" done: {sid}")
print("Finished.")
return
# ---- no action specified -----------------------------------------------
print(
"No action specified. Examples:\n"
" python plot.py --paper-samples\n"
" python plot.py --dataset Sen2_MTC_New --id T12TUR_R027_55\n"
" python plot.py --dataset Sen2_MTC_New --list\n"
" python plot.py --dataset Sen2_MTC_New --all\n"
)
if __name__ == "__main__":
main()