diffcr-datasets / eval /metrics.py
XavierJiezou's picture
Upload visualization folder
dfe630b verified
"""
eval/metrics.py
Unified evaluation script for cloud-removal methods on Sen2_MTC datasets.
Computes PSNR, SSIM, FID and LPIPS – same implementation used in the paper.
Usage
-----
# Evaluate every method on both datasets (prints a summary table):
python metrics.py
# Evaluate one specific method / dataset:
python metrics.py --dataset Sen2_MTC_New --method diffcr
# Evaluate an arbitrary pair of directories:
python metrics.py --gt /path/to/GT --pred /path/to/Out
.. note on reproducibility::
PSNR, FID and LPIPS are fully reproducible on CPU.
**SSIM requires a CUDA-enabled PyTorch build** to match the exact paper
values; the 3-D Gaussian kernel implementation uses `.cuda()` internally
and its floating-point accumulation order differs on CPU, leading to
slightly different SSIM numbers. Install the correct torch wheel for
your GPU from https://pytorch.org before running a full benchmark.
The script expects the following layout (created by migrate.py):
visualization/
├── data/
│ ├── Sen2_MTC_New/GT/ ← ground-truth images ({id}.png)
│ └── Sen2_MTC_Old/GT/
└── results/
├── Sen2_MTC_New/{method}/ ← prediction images ({id}.png)
└── Sen2_MTC_Old/{method}/
"""
from __future__ import annotations
import argparse
import os
import subprocess
import sys
from glob import glob
import cv2
import lpips
import numpy as np
import torch
from tqdm import tqdm
# ---------------------------------------------------------------------------
# Paths
# ---------------------------------------------------------------------------
# eval/ lives one level below the project root
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DATASETS: list[str] = ["Sen2_MTC_Old", "Sen2_MTC_New"]
# Order matches the paper table (top → bottom)
METHODS: list[str] = [
"mcgan",
"pix2pix",
"ae",
"stnet",
"dsen2cr",
"stgan",
"ctgan",
"crtsnet",
"pmaa",
"uncrtaints",
"ddpmcr",
"diffcr",
]
# ---------------------------------------------------------------------------
# Image helpers
# ---------------------------------------------------------------------------
def _convert_input_type_range(img: np.ndarray) -> np.ndarray:
"""Convert image to float32 in [0, 1]."""
img_type = img.dtype
img = img.astype(np.float32)
if img_type == np.uint8:
img /= 255.0
elif img_type != np.float32:
raise TypeError(f"Unsupported dtype: {img_type}")
return img
def _convert_output_type_range(img: np.ndarray, dst_type) -> np.ndarray:
if dst_type == np.uint8:
img = img.round()
else:
img /= 255.0
return img.astype(dst_type)
def reorder_image(img: np.ndarray, input_order: str = "HWC") -> np.ndarray:
if input_order not in ("HWC", "CHW"):
raise ValueError(f"input_order must be 'HWC' or 'CHW', got '{input_order}'")
if img.ndim == 2:
img = img[..., None]
if input_order == "CHW":
img = img.transpose(1, 2, 0)
return img
# ---------------------------------------------------------------------------
# PSNR
# ---------------------------------------------------------------------------
def calculate_psnr(
img1: np.ndarray,
img2: np.ndarray,
crop_border: int,
input_order: str = "HWC",
) -> float:
"""Peak Signal-to-Noise Ratio.
Accepts uint8 [0, 255] or float32 [0, 1] images.
"""
assert img1.shape == img2.shape, f"Shape mismatch: {img1.shape} vs {img2.shape}"
img1 = reorder_image(img1, input_order).astype(np.float64)
img2 = reorder_image(img2, input_order).astype(np.float64)
if crop_border:
img1 = img1[crop_border:-crop_border, crop_border:-crop_border, ...]
img2 = img2[crop_border:-crop_border, crop_border:-crop_border, ...]
mse = np.mean((img1 - img2) ** 2)
if mse == 0:
return float("inf")
max_val = 1.0 if img1.max() <= 1.0 else 255.0
return 20.0 * np.log10(max_val / np.sqrt(mse))
# ---------------------------------------------------------------------------
# SSIM – 3-D Gaussian kernel (paper implementation)
# ---------------------------------------------------------------------------
def _generate_3d_gaussian_kernel(device: torch.device) -> torch.nn.Conv3d:
"""Build the 11×11×11 separable Gaussian Conv3d used in the paper."""
kernel_1d = cv2.getGaussianKernel(11, 1.5) # (11, 1)
window_2d = np.outer(kernel_1d, kernel_1d.T) # (11, 11)
kernel_3d = np.stack(
[window_2d * k for k in kernel_1d],
axis=0, # (11, 11, 11)
)
conv3d = torch.nn.Conv3d(
1,
1,
(11, 11, 11),
stride=1,
padding=(5, 5, 5),
bias=False,
padding_mode="replicate",
)
conv3d.weight.requires_grad_(False)
conv3d.weight[0, 0] = torch.tensor(kernel_3d)
return conv3d.to(device)
def _apply_3d_gaussian(img: torch.Tensor, conv3d: torch.nn.Conv3d) -> torch.Tensor:
return conv3d(img.unsqueeze(0).unsqueeze(0)).squeeze(0).squeeze(0)
def _ssim_3d(
img1: np.ndarray,
img2: np.ndarray,
max_value: float,
device: torch.device,
) -> float:
"""3-D SSIM over all three channels simultaneously (paper metric)."""
assert img1.ndim == 3 and img2.ndim == 3
C1 = (0.01 * max_value) ** 2
C2 = (0.03 * max_value) ** 2
kernel = _generate_3d_gaussian_kernel(device)
t1 = torch.tensor(img1.astype(np.float64)).float().to(device)
t2 = torch.tensor(img2.astype(np.float64)).float().to(device)
mu1 = _apply_3d_gaussian(t1, kernel)
mu2 = _apply_3d_gaussian(t2, kernel)
mu1_sq = mu1**2
mu2_sq = mu2**2
mu1_mu2 = mu1 * mu2
sigma1_sq = _apply_3d_gaussian(t1**2, kernel) - mu1_sq
sigma2_sq = _apply_3d_gaussian(t2**2, kernel) - mu2_sq
sigma12 = _apply_3d_gaussian(t1 * t2, kernel) - mu1_mu2
ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / (
(mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2)
)
return float(ssim_map.mean())
def calculate_ssim(
img1: np.ndarray,
img2: np.ndarray,
crop_border: int,
input_order: str = "HWC",
device: torch.device | None = None,
) -> float:
"""Structural Similarity using the 3-D Gaussian kernel (paper implementation).
Requires CUDA by default; falls back to CPU if no GPU is available.
"""
if device is None:
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
assert img1.shape == img2.shape, f"Shape mismatch: {img1.shape} vs {img2.shape}"
img1 = reorder_image(img1, input_order).astype(np.float64)
img2 = reorder_image(img2, input_order).astype(np.float64)
if crop_border:
img1 = img1[crop_border:-crop_border, crop_border:-crop_border, ...]
img2 = img2[crop_border:-crop_border, crop_border:-crop_border, ...]
max_val = 1 if img1.max() <= 1.0 else 255
with torch.no_grad():
return _ssim_3d(img1, img2, max_val, device)
# ---------------------------------------------------------------------------
# FID
# ---------------------------------------------------------------------------
def calculate_fid(gt_dir: str, pred_dir: str) -> float:
"""Compute FID via the pytorch-fid command-line tool."""
device = "cuda" if torch.cuda.is_available() else "cpu"
num_workers = 0 if sys.platform == "win32" else 4
result = subprocess.run(
[
sys.executable,
"-m",
"pytorch_fid",
gt_dir,
pred_dir,
"--device",
device,
"--batch-size",
"4",
"--num-workers",
str(num_workers),
],
capture_output=True,
text=True,
)
output = result.stdout + result.stderr
for line in output.splitlines():
line = line.strip()
if "fid" in line.lower():
try:
return float(line.split()[-1])
except ValueError:
pass
print(f"[WARN] Could not parse FID output:\n{output}", file=sys.stderr)
return float("nan")
# ---------------------------------------------------------------------------
# LPIPS
# ---------------------------------------------------------------------------
def calculate_lpips(
gt_dir: str,
pred_dir: str,
device: torch.device | None = None,
) -> float:
"""Mean LPIPS (AlexNet backbone) over matched image pairs."""
if device is None:
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
loss_fn = lpips.LPIPS(net="alex", verbose=False).to(device)
gt_map = _stem_map(gt_dir)
pred_map = _stem_map(pred_dir)
keys = sorted(set(gt_map) & set(pred_map))
if not keys:
print(
f"[WARN] No common files between {gt_dir} and {pred_dir}", file=sys.stderr
)
return float("nan")
scores: list[float] = []
for k in tqdm(keys, desc="LPIPS", leave=False):
t1 = lpips.im2tensor(lpips.load_image(gt_map[k])).to(device)
t2 = lpips.im2tensor(lpips.load_image(pred_map[k])).to(device)
scores.append(loss_fn(t1, t2).item())
return float(np.mean(scores))
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _stem_map(directory: str) -> dict[str, str]:
"""Return {stem: full_path} for every .png in *directory*."""
return {
os.path.splitext(os.path.basename(f))[0]: f
for f in glob(os.path.join(directory, "*.png"))
}
def evaluate_pair(
gt_dir: str,
pred_dir: str,
desc: str = "",
device: torch.device | None = None,
) -> dict | None:
"""Compute all four metrics for one (GT, prediction) directory pair.
Returns a dict with keys: n, PSNR, SSIM, FID, LPIPS.
Returns None if no common files are found.
"""
if device is None:
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
gt_map = _stem_map(gt_dir)
pred_map = _stem_map(pred_dir)
keys = sorted(set(gt_map) & set(pred_map))
if not keys:
print(
f"[WARN] No common files – GT: {gt_dir!r} Pred: {pred_dir!r}",
file=sys.stderr,
)
return None
psnr_list: list[float] = []
ssim_list: list[float] = []
for k in tqdm(keys, desc=desc or "PSNR/SSIM", leave=False):
img_gt = cv2.imread(gt_map[k])
img_pred = cv2.imread(pred_map[k])
if img_gt is None or img_pred is None:
print(f"[WARN] Could not read image for key '{k}'", file=sys.stderr)
continue
if img_gt.shape != img_pred.shape:
print(
f"[WARN] Shape mismatch for '{k}': {img_gt.shape} vs {img_pred.shape}",
file=sys.stderr,
)
continue
psnr_list.append(calculate_psnr(img_gt, img_pred, crop_border=0))
ssim_list.append(calculate_ssim(img_gt, img_pred, crop_border=0, device=device))
if not psnr_list:
return None
fid_score = calculate_fid(gt_dir, pred_dir)
lpips_score = calculate_lpips(gt_dir, pred_dir, device=device)
return {
"n": len(psnr_list),
"PSNR": float(np.mean(psnr_list)),
"SSIM": float(np.mean(ssim_list)),
"FID": fid_score,
"LPIPS": lpips_score,
}
# ---------------------------------------------------------------------------
# Pretty table
# ---------------------------------------------------------------------------
def _fmt(v: float | None, width: int, decimals: int) -> str:
if v is None or (isinstance(v, float) and np.isnan(v)):
return f"{'N/A':>{width}}"
return f"{v:>{width}.{decimals}f}"
def print_table(
all_results: dict[str, dict[str, dict]],
datasets: list[str],
methods: list[str],
) -> None:
col = 38 # width of one dataset block
sep = "-" * (16 + col * len(datasets))
# Header
print("\n" + "=" * len(sep))
header = f"{'Method':<16}"
for ds in datasets:
label = ds.replace("Sen2_MTC_", "Sen2_MTC ")
header += f"{'| ' + label:<{col}}"
print(header)
sub = f"{'':16}"
for _ in datasets:
sub += f"| {'PSNR':>7} {'SSIM':>6} {'FID':>9} {'LPIPS':>6} "
print(sub)
print(sep)
for m in methods:
row = f"{m:<16}"
for ds in datasets:
r = all_results.get(ds, {}).get(m)
if r:
row += (
f"| {_fmt(r['PSNR'], 7, 3)}"
f" {_fmt(r['SSIM'], 6, 3)}"
f" {_fmt(r['FID'], 9, 3)}"
f" {_fmt(r['LPIPS'], 6, 3)} "
)
else:
row += f"|{'SKIP':^{col - 2}} "
print(row)
print("=" * len(sep))
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
def _parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(
description="Evaluate cloud-removal metrics (PSNR / SSIM / FID / LPIPS)"
)
p.add_argument(
"--dataset",
type=str,
default=None,
choices=DATASETS,
help="Evaluate only this dataset (default: both)",
)
p.add_argument(
"--method",
type=str,
default=None,
help="Evaluate only this method (default: all)",
)
p.add_argument(
"--gt",
type=str,
default=None,
help="Ground-truth directory (use together with --pred for a custom pair)",
)
p.add_argument(
"--pred",
type=str,
default=None,
help="Prediction directory",
)
p.add_argument(
"--no-fid",
action="store_true",
help="Skip FID computation (much faster, useful for quick checks)",
)
p.add_argument(
"--no-lpips",
action="store_true",
help="Skip LPIPS computation",
)
return p.parse_args()
def main() -> None:
args = _parse_args()
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Device: {device}")
# ---- custom pair -------------------------------------------------------
if args.gt and args.pred:
print(f"GT : {args.gt}")
print(f"Pred: {args.pred}")
res = evaluate_pair(args.gt, args.pred, desc="custom", device=device)
if res:
print(
f"\nPSNR = {res['PSNR']:.3f}\n"
f"SSIM = {res['SSIM']:.3f}\n"
f"FID = {res['FID']:.3f}\n"
f"LPIPS = {res['LPIPS']:.3f}\n"
f"(n = {res['n']})"
)
return
# ---- standard evaluation loop ------------------------------------------
datasets = [args.dataset] if args.dataset else DATASETS
methods = [args.method] if args.method else METHODS
all_results: dict[str, dict[str, dict]] = {ds: {} for ds in datasets}
for ds in datasets:
gt_dir = os.path.join(ROOT, "data", ds, "GT")
if not os.path.isdir(gt_dir):
print(f"[ERROR] GT directory not found: {gt_dir}", file=sys.stderr)
continue
for m in methods:
pred_dir = os.path.join(ROOT, "results", ds, m)
if not os.path.isdir(pred_dir):
print(f" SKIP {ds}/{m} (not found)")
continue
print(f"\n[{ds}] [{m}]")
gt_map = _stem_map(gt_dir)
pred_map = _stem_map(pred_dir)
n_common = len(set(gt_map) & set(pred_map))
print(
f" GT: {len(gt_map)} imgs | Pred: {len(pred_map)} imgs | Common: {n_common}"
)
# PSNR / SSIM
psnr_list: list[float] = []
ssim_list: list[float] = []
keys = sorted(set(gt_map) & set(pred_map))
for k in tqdm(keys, desc="PSNR/SSIM", leave=False):
ig = cv2.imread(gt_map[k])
ip = cv2.imread(pred_map[k])
if ig is None or ip is None or ig.shape != ip.shape:
continue
psnr_list.append(calculate_psnr(ig, ip, crop_border=0))
ssim_list.append(calculate_ssim(ig, ip, crop_border=0, device=device))
if not psnr_list:
print(" [WARN] No valid image pairs found.")
continue
psnr_mean = float(np.mean(psnr_list))
ssim_mean = float(np.mean(ssim_list))
print(f" PSNR = {psnr_mean:.3f} | SSIM = {ssim_mean:.3f}")
# FID
fid_score: float = float("nan")
if not args.no_fid:
print(" Computing FID ...", end=" ", flush=True)
fid_score = calculate_fid(gt_dir, pred_dir)
print(f"{fid_score:.3f}")
# LPIPS
lpips_score: float = float("nan")
if not args.no_lpips:
lpips_score = calculate_lpips(gt_dir, pred_dir, device=device)
print(f" LPIPS = {lpips_score:.3f}")
all_results[ds][m] = {
"n": len(psnr_list),
"PSNR": psnr_mean,
"SSIM": ssim_mean,
"FID": fid_score,
"LPIPS": lpips_score,
}
# ---- summary table -----------------------------------------------------
if any(all_results[ds] for ds in datasets):
print_table(all_results, datasets, methods)
if __name__ == "__main__":
main()