Datasets:
Download CSTD/screen_cstd.py from aviadcohz/Detecture_ICLR_Benchmarking: direct link, hf CLI and curl.
- Browser
- Download file 6.54 kB
-
https://huggingface.co/datasets/aviadcohz/Detecture_ICLR_Benchmarking/resolve/main/CSTD/screen_cstd.py
- Command line
-
hf download hf://datasets/aviadcohz/Detecture_ICLR_Benchmarking/CSTD/screen_cstd.py
-
curl -L -o screen_cstd.py https://huggingface.co/datasets/aviadcohz/Detecture_ICLR_Benchmarking/resolve/main/CSTD/screen_cstd.py
6.54 kB
| #!/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() | |