File size: 12,194 Bytes
dfe630b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 | """
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()
|