okami.mom/strata

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

Niko1221Merge f-own-5 56630caca into f-own-int (round 14: Strata's own VAE decoder for sd-cli and the images "vae_decoder" switch)736266e87

main
3.3 KiB73 linesraw
1"""tools/image/gate/diff_where.py - TEST-ONLY (OWN-5 gate harness): where two picture sets differ, and what the user
2sees after the server's compositing.
3
4    python -I -B diff_where.py <pics root> <tagA> <tagB>
5
6Per pair (p*_s*.png in both): the largest absolute difference over R, G, B and alpha with its pixel (row, column) and
7channel, whether that pixel lies within 16 px of the border, the share of pixels whose largest RGB or alpha difference
8is above 8 / 255, and the RGB PSNR of the RGBA pictures and of the pictures as the server sends them by default
9(serve/images.py flatten_png: on white, 8-bit RGB).  The last lines are the worst picture of the set by RGB PSNR."""
10from __future__ import annotations
11
12import io
13import math
14import sys
15from pathlib import Path
16
17import numpy as np
18from PIL import Image
19
20sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
21from serve.images import flatten_png  # noqa: E402
22
23CH = "RGBA"
24
25
26def psnr(a: np.ndarray, b: np.ndarray) -> float:
27    d = a.astype(np.float64) - b.astype(np.float64)
28    mse = float((d * d).mean())
29    return math.inf if mse == 0 else 10 * math.log10(255 * 255 / mse)
30
31
32def one(pa: Path, pb: Path) -> dict:
33    A = np.asarray(Image.open(pa).convert("RGBA")).astype(np.int16)
34    B = np.asarray(Image.open(pb).convert("RGBA")).astype(np.int16)
35    d = np.abs(A - B)
36    y, x, c = np.unravel_index(int(np.argmax(d)), d.shape)
37    H, W = d.shape[:2]
38    fa = np.asarray(Image.open(io.BytesIO(flatten_png(pa.read_bytes()))).convert("RGB"))
39    fb = np.asarray(Image.open(io.BytesIO(flatten_png(pb.read_bytes()))).convert("RGB"))
40    return {"name": pa.name, "max": int(d.max()), "at": (int(y), int(x)), "channel": CH[c],
41            "border": bool(min(y, x, H - 1 - y, W - 1 - x) < 16),
42            "max_rgb": int(d[..., :3].max()), "max_alpha": int(d[..., 3].max()),
43            "pct_rgb_over8": float((d[..., :3].max(axis=2) > 8).mean() * 100),
44            "pct_alpha_over8": float((d[..., 3] > 8).mean() * 100),
45            "psnr_rgb": psnr(A[..., :3], B[..., :3]), "psnr_flat": psnr(fa, fb),
46            "flat_max": int(np.abs(fa.astype(np.int16) - fb.astype(np.int16)).max())}
47
48
49def main(argv) -> int:
50    root, ta, tb = Path(argv[0]), argv[1], argv[2]
51    rows = []
52    for pa in sorted((root / ta).glob("p*_s*.png")):
53        pb = root / tb / pa.name
54        if pb.is_file():
55            r = one(pa, pb)
56            rows.append(r)
57            print(f"{r['name']}: max |d| {r['max']} at row {r['at'][0]} col {r['at'][1]} channel {r['channel']}"
58                  f"{' (border)' if r['border'] else ''}; RGB max {r['max_rgb']}, alpha max {r['max_alpha']}; "
59                  f"pixels > 8: RGB {r['pct_rgb_over8']:.4f}%, alpha {r['pct_alpha_over8']:.4f}%; "
60                  f"PSNR RGBA-pictures {r['psnr_rgb']:.2f} dB, flattened on white {r['psnr_flat']:.2f} dB "
61                  f"(max |d| {r['flat_max']})")
62    if not rows:
63        print("no pairs")
64        return 1
65    w = min(rows, key=lambda r: r["psnr_rgb"])
66    print(f"WORST {ta} vs {tb}: {w['name']} PSNR {w['psnr_rgb']:.2f} dB (flattened {w['psnr_flat']:.2f} dB)")
67    fl = [r["psnr_flat"] for r in rows if math.isfinite(r["psnr_flat"])]
68    print(f"FLATTENED {ta} vs {tb}: n {len(rows)}, PSNR worst {min(fl):.2f} mean {np.mean(fl):.2f} dB")
69    return 0
70
71
72if __name__ == "__main__":
73    sys.exit(main(sys.argv[1:]))