File size: 6,541 Bytes
888e09f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Screen CSTD for images whose ground-truth region map actually matches the
generated image.

Why this is needed: `regions/*.png` is the stitching mask fed INTO ControlNet,
not an annotation of what came OUT. Where SD invented extra texture fields, or
drifted from the mask, the ground truth silently stops being true. Three
observed failure modes, all confirmed by eye on 000009 / 000016 / 000017:

  1. a GT region contains two or more distinct textures  (000017, 000009)
  2. the two GT regions are not actually distinguishable (generator blended)
  3. the GT contour does not sit on a real appearance change (000016 edges)

Metrics per image, all computed on texture features rather than raw colour:

  sep        separability of region A vs B          -> want HIGH
  het_max    worst within-region heterogeneity      -> want LOW
  bnd_align  fraction of GT contour that sits on a
             real local appearance change           -> want HIGH
  stray      strongest texture change far from the
             GT contour, relative to the contour    -> want LOW

Usage:
    python screen_cstd.py --out screen_scores.json [--limit N] [--workers 8]
"""
from __future__ import annotations

import argparse
import json
from concurrent.futures import ProcessPoolExecutor
from pathlib import Path

import numpy as np
from PIL import Image
from scipy import ndimage as ndi
from skimage.color import rgb2lab
from skimage.filters import gabor_kernel

ROOT = Path("/home/aviad/datasets/CSTD")
SIDE = 192                      # working resolution
WIN = 9                         # local-statistics window


def _bank():
    ks = []
    for theta in (0, np.pi / 4, np.pi / 2, 3 * np.pi / 4):
        for freq in (0.15, 0.30):
            ks.append(np.real(gabor_kernel(freq, theta=theta)).astype(np.float32))
    return ks


KERNELS = _bank()


def features(rgb: np.ndarray) -> np.ndarray:
    """Per-pixel texture+colour descriptor, standardised. (H, W, C)."""
    lab = rgb2lab(rgb / 255.0).astype(np.float32)
    L = lab[..., 0]
    ch = [lab[..., 0], lab[..., 1], lab[..., 2]]
    # local contrast at two scales: texture energy independent of mean colour
    for w in (5, 13):
        m = ndi.uniform_filter(L, w)
        ch.append(np.sqrt(np.maximum(ndi.uniform_filter(L * L, w) - m * m, 0)))
    # oriented band-pass energy, smoothed -> classic texture descriptor
    for k in KERNELS:
        ch.append(ndi.uniform_filter(np.abs(ndi.convolve(L, k, mode="reflect")), WIN))
    f = np.stack(ch, -1)
    f = (f - f.reshape(-1, f.shape[-1]).mean(0)) / (
        f.reshape(-1, f.shape[-1]).std(0) + 1e-6)
    return f.astype(np.float32)


def _fisher(x: np.ndarray, y: np.ndarray) -> float:
    """Multivariate separability of two feature sets, scale-free."""
    if len(x) < 30 or len(y) < 30:
        return 0.0
    mu = x.mean(0) - y.mean(0)
    sd = np.sqrt(0.5 * (x.var(0) + y.var(0))) + 1e-6
    return float(np.sqrt(((mu / sd) ** 2).mean()))


def _heterogeneity(f: np.ndarray, mask: np.ndarray) -> float:
    """How strongly one GT region splits into two spatially-coherent textures.

    A real second texture must be both separable in feature space AND form a
    compact blob; salt-and-pepper noise must not trigger it.
    """
    idx = np.flatnonzero(mask.ravel())
    if idx.size < 400:
        return 0.0
    X = f.reshape(-1, f.shape[-1])[idx]
    sub = X[np.random.default_rng(0).choice(len(X), min(3000, len(X)), replace=False)]
    # 2-means, few iterations, deterministic init on the principal axis
    v = np.linalg.svd(sub - sub.mean(0), full_matrices=False)[2][0]
    proj = X @ v
    thr = np.median(proj)
    a, b = X[proj <= thr], X[proj > thr]
    sep = _fisher(a, b)
    lab = np.zeros(mask.shape, bool)
    lab.ravel()[idx] = proj > thr
    lab &= mask
    # spatial coherence: biggest connected component of the minority cluster
    cc, n = ndi.label(lab)
    if n == 0:
        return 0.0
    big = max(ndi.sum(lab, cc, range(1, n + 1))) if n else 0
    coh = big / max(mask.sum(), 1)
    return float(sep * min(coh / 0.25, 1.0))     # needs >=25% area to count fully


def _contour_stats(f: np.ndarray, mask: np.ndarray):
    """Alignment of the GT contour with a real appearance change, plus the
    strongest competing change elsewhere."""
    er = ndi.binary_erosion(mask, iterations=3)
    di = ndi.binary_dilation(mask, iterations=3)
    band = di ^ er
    if band.sum() < 50:
        return 0.0, 1.0
    inn = ndi.binary_dilation(mask, iterations=3) & ~mask
    out = mask & ~ndi.binary_erosion(mask, iterations=3)
    d_contour = _fisher(f[out], f[inn])

    # competing change: split each region by its own principal axis and measure
    smooth = ndi.uniform_filter(f, size=(WIN, WIN, 1))
    gx = np.abs(np.diff(smooth, axis=1, prepend=smooth[:, :1])).sum(-1)
    gy = np.abs(np.diff(smooth, axis=0, prepend=smooth[:1])).sum(-1)
    g = gx + gy
    near = ndi.binary_dilation(band, iterations=4)
    far = g.copy()
    far[near] = 0
    on = float(np.percentile(g[band], 75)) + 1e-6
    stray = float(np.percentile(far[~near], 99.5)) / on if (~near).any() else 0.0
    return d_contour, stray


def score_one(sid: str) -> dict:
    rgb = np.array(Image.open(ROOT / "images" / f"{sid}.png").convert("RGB")
                   .resize((SIDE, SIDE), Image.BILINEAR))
    m = np.array(Image.open(ROOT / "textures_mask" / f"{sid}_mask_0.png")
                 .convert("L").resize((SIDE, SIDE), Image.NEAREST)) > 127
    frac = m.mean()
    f = features(rgb)
    A, B = f[m], f[~m]
    sep = _fisher(A, B)
    het = max(_heterogeneity(f, m), _heterogeneity(f, ~m))
    align, stray = _contour_stats(f, m)
    return {"id": sid, "sep": sep, "het_max": het,
            "bnd_align": align, "stray": stray, "area_frac": float(frac)}


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--out", default=str(ROOT / "screen_scores.json"))
    ap.add_argument("--limit", type=int, default=0)
    ap.add_argument("--workers", type=int, default=12)
    a = ap.parse_args()

    ids = sorted(p.stem for p in (ROOT / "images").glob("*.png"))
    if a.limit:
        ids = ids[:a.limit]
    out = []
    with ProcessPoolExecutor(a.workers) as ex:
        for i, r in enumerate(ex.map(score_one, ids, chunksize=16)):
            out.append(r)
            if (i + 1) % 500 == 0:
                print(f"  {i+1}/{len(ids)}", flush=True)
    Path(a.out).write_text(json.dumps(out))
    print(f"[screen] wrote {len(out)} scores -> {a.out}")


if __name__ == "__main__":
    main()