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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
"""

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()