okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-own-5 fccdb48a3 (image noise switch, step 1 only) into f-own-int150c2394f

main
4.9 KiB102 linesraw
1"""OWN-5: pixel comparison of two picture sets with the same names (p<i>_s<seed>.png).
2
3    python -I -B compare.py <pics_root> <tagA> <tagB> [--label NAME]
4
5Per pair: identical bytes, identical pixels, max and mean absolute difference (0-255, RGB; alpha separately),
6PSNR (RGB, dB; inf when equal), SSIM (RGB mean of per-channel SSIM, Gaussian 11x11 sigma 1.5, Wang et al. constants).
7Writes <pics_root>/cmp/<label>.json, a diff picture per pair (|A-B| x 8, clipped) and <pics_root>/cmp/<label>.html with
8A | B | diff side by side.  Prints a summary line."""
9from __future__ import annotations
10
11import hashlib
12import html
13import json
14import math
15import sys
16from pathlib import Path
17
18import numpy as np
19from PIL import Image
20
21
22def gauss_kernel(n=11, sigma=1.5):
23    x = np.arange(n) - n // 2
24    k = np.exp(-(x * x) / (2 * sigma * sigma))
25    return k / k.sum()
26
27
28def blur(a, k):
29    # separable 'valid' convolution
30    a = np.apply_along_axis(lambda r: np.convolve(r, k, mode="valid"), 0, a)
31    return np.apply_along_axis(lambda r: np.convolve(r, k, mode="valid"), 1, a)
32
33
34def ssim_channel(x, y, k):
35    c1, c2 = (0.01 * 255) ** 2, (0.03 * 255) ** 2
36    mx, my = blur(x, k), blur(y, k)
37    sxx = blur(x * x, k) - mx * mx
38    syy = blur(y * y, k) - my * my
39    sxy = blur(x * y, k) - mx * my
40    s = ((2 * mx * my + c1) * (2 * sxy + c2)) / ((mx * mx + my * my + c1) * (sxx + syy + c2))
41    return float(s.mean())
42
43
44def main() -> int:
45    a = sys.argv[1:]
46    root, ta, tb = Path(a[0]), a[1], a[2]
47    label = a[a.index("--label") + 1] if "--label" in a else f"{ta}__vs__{tb}"
48    da, db = root / ta, root / tb
49    out = root / "cmp"
50    (out / label).mkdir(parents=True, exist_ok=True)
51    k = gauss_kernel()
52    rows = []
53    for pa in sorted(da.glob("p*_s*.png")):
54        pb = db / pa.name
55        if not pb.is_file():
56            continue
57        ba, bb = pa.read_bytes(), pb.read_bytes()
58        ia, ib = Image.open(pa), Image.open(pb)
59        A, B = np.asarray(ia.convert("RGBA"), dtype=np.float64), np.asarray(ib.convert("RGBA"), dtype=np.float64)
60        if A.shape != B.shape:
61            rows.append({"name": pa.name, "error": f"shape {A.shape} vs {B.shape}"})
62            continue
63        d = np.abs(A[..., :3] - B[..., :3])
64        da_ = np.abs(A[..., 3] - B[..., 3])
65        mse = float((d * d).mean())
66        psnr = math.inf if mse == 0 else 10 * math.log10(255 * 255 / mse)
67        ssim = 1.0 if mse == 0 else float(np.mean([ssim_channel(A[..., c], B[..., c], k) for c in range(3)]))
68        diffp = out / label / pa.name.replace(".png", "_diff.png")
69        Image.fromarray(np.clip(d * 8, 0, 255).astype(np.uint8)).save(diffp)
70        rows.append({"name": pa.name, "mode": f"{ia.mode}/{ib.mode}", "bytes_equal": ba == bb,
71                     "pixels_equal": bool((A == B).all()), "max_abs": float(d.max()), "mean_abs": float(d.mean()),
72                     "alpha_max_abs": float(da_.max()), "psnr_db": psnr, "ssim": ssim,
73                     "pct_pixels_diff": float((d.max(axis=2) > 0).mean() * 100),
74                     "sha_a": hashlib.sha256(ba).hexdigest()[:12], "sha_b": hashlib.sha256(bb).hexdigest()[:12]})
75    ok = [r for r in rows if "error" not in r]
76    summ = {"label": label, "a": ta, "b": tb, "pairs": len(rows),
77            "bytes_equal": sum(r["bytes_equal"] for r in ok), "pixels_equal": sum(r["pixels_equal"] for r in ok)}
78    if ok:
79        fin = [r["psnr_db"] for r in ok if math.isfinite(r["psnr_db"])]
80        summ.update(max_abs=max(r["max_abs"] for r in ok), mean_abs=float(np.mean([r["mean_abs"] for r in ok])),
81                    psnr_min=min(fin) if fin else math.inf, psnr_mean=float(np.mean(fin)) if fin else math.inf,
82                    ssim_min=min(r["ssim"] for r in ok), ssim_mean=float(np.mean([r["ssim"] for r in ok])))
83    (out / f"{label}.json").write_text(json.dumps({"summary": summ, "pairs": rows}, indent=1))
84    rel = lambda p: Path(p).relative_to(root).as_posix()  # noqa: E731
85    h = [f"<!doctype html><meta charset=utf-8><title>{html.escape(label)}</title>",
86         "<style>body{font:14px sans-serif;margin:16px}img{width:32%;max-width:512px}td{vertical-align:top}</style>",
87         f"<h1>{html.escape(ta)} vs {html.escape(tb)}</h1><pre>{html.escape(json.dumps(summ, indent=1))}</pre>"]
88    for r in rows:
89        if "error" in r:
90            h.append(f"<p>{r['name']}: {html.escape(r['error'])}</p>")
91            continue
92        h.append(f"<h3>{r['name']}: bytes equal {r['bytes_equal']}, max |d| {r['max_abs']:.0f}, mean |d| "
93                 f"{r['mean_abs']:.3f}, PSNR {r['psnr_db']:.2f} dB, SSIM {r['ssim']:.5f}</h3>"
94                 f"<div><img src='../{rel(da / r['name'])}' title='A'> <img src='../{rel(db / r['name'])}' title='B'> "
95                 f"<img src='{label}/{r['name'].replace('.png', '_diff.png')}' title='|A-B| x 8'></div>")
96    (out / f"{label}.html").write_text("\n".join(h), encoding="utf-8")
97    print(json.dumps(summ))
98    return 0
99
100
101if __name__ == "__main__":
102    sys.exit(main())