File size: 15,281 Bytes
fb9bad4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Local A/B harness: old (deployed) vs new PBR heuristics on a dev texture.

Run:  python dev_process.py [texture.png]

  * Never touches the HF API / ZeroGPU (dev quota is precious) — pure local
    numpy/OpenCV.
  * Writes both map sets, a labelled contact sheet and a metrics report to
    ./_dev/ (gitignored).
  * "Old" implementations are verbatim copies of the previously deployed
    app.py heuristics.

Metrics address the reported issues:
  1. specular highlights surviving de-lighting          -> albedo top-tail
  2. metalness missing dark metals                      -> coverage + dark-neutral probe
  3. roughness being a mirror of metalness              -> Pearson correlation
  4. gold buttons / skin / leather behavior             -> region probes
"""

import argparse
import itertools
import os
import time

import cv2
import numpy as np

import pbr

# ---------------------------------------------------------------------------
# Old (deployed) implementations, verbatim from the previous app.py
# ---------------------------------------------------------------------------
_OLD_LUM = np.array([0.299, 0.587, 0.114], dtype=np.float32)


def _old_lum(rgb):
    return rgb @ _OLD_LUM


def old_de_light(img, strength):
    lum = _old_lum(img)
    h, w = lum.shape
    small = cv2.resize(lum, (256, 256), interpolation=cv2.INTER_AREA)
    small = cv2.GaussianBlur(small, (0, 0), 32.0)
    shading = cv2.resize(small, (w, h), interpolation=cv2.INTER_LINEAR)
    shading = np.clip(shading, 1e-3, None)
    target = float(np.mean(lum))
    factor = np.clip((target / shading) ** strength, 0.2, 5.0)
    albedo = np.clip(img * factor[..., None], 0.0, 1.0)
    if strength > 0:
        lo, hi = np.percentile(albedo, (0.5, 99.5))
        albedo = np.clip((albedo - lo) / max(hi - lo, 1e-6), 0.0, 1.0)
        hsv = cv2.cvtColor((albedo * 255.0).astype(np.uint8), cv2.COLOR_RGB2HSV).astype(
            np.float32
        )
        hsv[..., 1] = np.clip(hsv[..., 1] * 1.12, 0, 255)
        albedo = cv2.cvtColor(hsv.astype(np.uint8), cv2.COLOR_HSV2RGB).astype(
            np.float32
        ) / 255.0
    return albedo


def old_roughness_map(rgb, sensitivity):
    lum = _old_lum(rgb)
    smooth = np.clip((lum - 0.30) / 0.70, 0.0, 1.0) ** 1.6
    detail = np.abs(lum - cv2.GaussianBlur(lum, (0, 0), 2.0))
    detail = detail / max(float(detail.max()), 1e-6)
    smooth = smooth * 0.75 + (1.0 - detail) * 0.25
    rough = 0.5 + ((1.0 - smooth) - 0.5) * sensitivity
    return (np.clip(rough, 0, 1) * 255.0).astype(np.uint8)


def old_metalness_map(rgb, threshold, sensitivity):
    lum = _old_lum(rgb)
    mx = np.max(rgb, axis=-1)
    sat = np.clip((mx - np.min(rgb, axis=-1)) / np.maximum(mx, 1e-6), 0.0, 1.0)
    bright = np.clip((lum - threshold) / max(1.0 - threshold, 1e-6), 0.0, 1.0)
    metal = np.clip(bright * (1.0 - sat) ** 1.5 * sensitivity, 0.0, 1.0)
    return (metal * 255.0).astype(np.uint8)


# ---------------------------------------------------------------------------
# Metrics
# ---------------------------------------------------------------------------
def pearson(a, b):
    return float(np.corrcoef(a.ravel(), b.ravel())[0, 1])


def mean(arr):
    return float(np.mean(arr))


def frac(arr, cutoff):
    return float(np.mean(arr > cutoff))


def region_stats(rgb, mask):
    """Mean color stats of a probe region (sanity-check what it contains)."""
    hsv = cv2.cvtColor((rgb * 255.0).astype(np.uint8), cv2.COLOR_RGB2HSV).astype(
        np.float32
    )
    hue, sat, val = hsv[..., 0], hsv[..., 1] / 255.0, hsv[..., 2] / 255.0
    r, g, b = rgb[..., 0], rgb[..., 1], rgb[..., 2]
    warmth = np.clip((r - b) / np.maximum(r + g + b, 1e-6), 0.0, 1.0)
    if not mask.any():
        return None
    return {
        "px": int(mask.sum()),
        "hue": float(np.mean(hue[mask])),
        "sat": float(np.mean(sat[mask])),
        "val": float(np.mean(val[mask])),
        "warmth": float(np.mean(warmth[mask])),
    }


def probe_masks(rgb):
    """Region masks derived from the ORIGINAL texture."""
    hsv = cv2.cvtColor((rgb * 255.0).astype(np.uint8), cv2.COLOR_RGB2HSV).astype(
        np.float32
    )
    hue, sat, val = hsv[..., 0], hsv[..., 1] / 255.0, hsv[..., 2] / 255.0
    r, g, b = rgb[..., 0], rgb[..., 1], rgb[..., 2]
    warmth = np.clip((r - b) / np.maximum(r + g + b, 1e-6), 0.0, 1.0)

    gold = (hue >= 24) & (hue <= 34) & (sat > 0.45) & (val > 0.45)
    dark_neutral = (val < 0.30) & (sat < 0.25)
    skin_like = (warmth >= 0.10) & (warmth <= 0.30) & (sat >= 0.25) & (sat <= 0.55) & (
        val >= 0.35
    ) & (val <= 0.80)
    return {"gold": gold, "dark_neutral": dark_neutral, "skin_like": skin_like}


def label(img, text, color=(255, 255, 255)):
    out = img.copy()
    cv2.putText(out, text, (6, 16), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 1, cv2.LINE_AA)
    return out


def to_bgr_gray(gray_u8):
    return cv2.cvtColor(gray_u8, cv2.COLOR_GRAY2BGR)


def compute_metal_metrics(albedo, rough_u8, masks, args, metal_kwargs=None):
    """Metalness + metric dict for one knob config (albedo/rough/masks precomputed)."""
    metal = pbr.metalness_map(
        albedo, args.metal_thresh, args.metal_sens, **(metal_kwargs or {})
    )
    m = metal.astype(np.float32) / 255.0
    r = rough_u8.astype(np.float32) / 255.0
    return {
        "cov": frac(m, 0.5),
        "dark": mean(m[masks["dark_neutral"]]) if masks["dark_neutral"].any() else float("nan"),
        "gold": mean(m[masks["gold"]]) if masks["gold"].any() else float("nan"),
        "skin": mean(m[masks["skin_like"]]) if masks["skin_like"].any() else float("nan"),
        "corr": pearson(r, m),
        "rstd": float(np.std(r)),
    }


def sweep(rgb, albedo, rough_u8, args):
    """Grid-search the metalness tuning knobs; return the best (kwargs, metrics).

    Constraints (from the user's requirements): dark metal must stay detected
    (>= 0.60), gold buttons must register (>= 0.30), metal coverage must stay
    meaningful (>= 0.40) and roughness must stay decorrelated from metalness
    (|corr| <= 0.35). Among passing combos, minimize skin-like metalness.
    """
    grid = {
        "warm_start": [0.02, 0.04, 0.06],
        "warm_width": [0.09, 0.12, 0.15],
        "gold_hue_center": [26.0, 28.0, 30.0],
        "gold_hue_sigma": [9.0, 12.0, 16.0],
        "gold_sat_exp": [1.4, 1.8, 2.2],
    }
    keys = list(grid)
    combos = [dict(zip(keys, c)) for c in itertools.product(*[grid[k] for k in keys])]
    masks = probe_masks(rgb)
    rows = []
    t0 = time.perf_counter()
    for kw in combos:
        rows.append((compute_metal_metrics(albedo, rough_u8, masks, args, kw), kw))
    dt = time.perf_counter() - t0

    def ok(m):
        return (
            m["dark"] >= 0.60
            and m["gold"] >= 0.30
            and m["cov"] >= 0.40
            and abs(m["corr"]) <= 0.35
        )

    passing = [r for r in rows if ok(r[0])]
    pool = passing or rows
    pool.sort(key=lambda r: r[0]["skin"])

    lines = [
        f"grid: {len(rows)} combos in {dt:.1f}s | {len(passing)} pass constraints "
        "(dark>=0.60, gold>=0.30, cov>=0.40, |corr|<=0.35)"
    ]
    lines.append(f"{'skin':>6} {'dark':>6} {'gold':>6} {'cov':>6} {'corr':>7} {'rstd':>6}  knobs")
    lines.append("-" * 80)
    for m, kw in pool[:15]:
        lines.append(
            f"{m['skin']:6.3f} {m['dark']:6.3f} {m['gold']:6.3f} {m['cov']:6.3f} "
            f"{m['corr']:+7.3f} {m['rstd']:6.3f}  "
            + " ".join(f"{k}={v:g}" for k, v in kw.items())
        )
    lines.append("")
    report = "\n".join(lines)
    print(report)
    with open("_dev/sweep_top.txt", "w", encoding="utf-8") as f:
        f.write(report + "\n")

    best_m, best_kw = pool[0]
    if not passing:
        print("  ! no combo passed all constraints; BEST below is the global min-skin "
              "(constraints violated)")
    print(
        f"BEST (min skin): skin {best_m['skin']:.3f} | dark {best_m['dark']:.3f} | "
        f"gold {best_m['gold']:.3f} | cov {best_m['cov']:.3f} | corr {best_m['corr']:+.3f}"
    )
    print("  knobs: " + " ".join(f"{k}={v:g}" for k, v in best_kw.items()))
    return best_kw, best_m


# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------
def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("texture", nargs="?", default="DKnightfrnt.png")
    ap.add_argument("--delight", type=float, default=0.85)
    ap.add_argument("--highlight", type=float, default=0.8)
    ap.add_argument("--rough-sens", type=float, default=1.0)
    ap.add_argument("--metal-thresh", type=float, default=0.45)
    ap.add_argument("--metal-sens", type=float, default=1.0)
    ap.add_argument("--sweep", action="store_true", help="grid-search the metalness tuning knobs")
    args = ap.parse_args()

    os.makedirs("_dev", exist_ok=True)
    img = cv2.imread(args.texture, cv2.IMREAD_UNCHANGED)
    if img is None:
        raise SystemExit(f"cannot read {args.texture}")
    if img.ndim == 2:
        img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
    elif img.shape[2] == 4:
        img = cv2.cvtColor(img, cv2.COLOR_BGRA2RGB)
    else:
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    img_u8 = img
    rgb = img_u8.astype(np.float32) / 255.0
    print(f"texture: {args.texture}  {img_u8.shape[1]}x{img_u8.shape[0]}")

    # --- what are the probe regions actually seeing? ---
    for name, msk in probe_masks(rgb).items():
        st = region_stats(rgb, msk)
        if st:
            total = rgb.shape[0] * rgb.shape[1]
            print(
                f"  probe {name:<13} px={st['px']:>5} ({100 * st['px'] / total:4.1f}%) "
                f"hue={st['hue']:5.1f} sat={st['sat']:.2f} val={st['val']:.2f} warmth={st['warmth']:.2f}"
            )
        else:
            print(f"  probe {name:<13} empty")

    # --- optional sweep over metalness tuning knobs ---
    albedo_sweep = pbr.de_light(rgb, args.delight, args.highlight)
    rough_sweep = pbr.roughness_map(albedo_sweep, args.rough_sens)
    best_kw = None
    if args.sweep:
        best_kw, _ = sweep(rgb, albedo_sweep, rough_sweep, args)
        print()

    # --- run both pipelines ---
    t = time.perf_counter()
    albedo_new = pbr.de_light(rgb, args.delight, args.highlight)
    albedo_old = old_de_light(rgb, args.delight)
    t_de = time.perf_counter() - t

    t = time.perf_counter()
    rough_new = pbr.roughness_map(albedo_new, args.rough_sens)
    rough_old = old_roughness_map(albedo_old, args.rough_sens)
    t_rough = time.perf_counter() - t

    t = time.perf_counter()
    metal_new = pbr.metalness_map(
        albedo_new, args.metal_thresh, args.metal_sens, **(best_kw or {})
    )
    metal_old = old_metalness_map(albedo_old, args.metal_thresh, args.metal_sens)
    t_metal = time.perf_counter() - t

    normal_new = pbr.normal_map(albedo_new, 1.0, 0.5)

    # --- save maps ---
    cv2.imwrite("_dev/albedo_old.png", cv2.cvtColor((albedo_old * 255).astype(np.uint8), cv2.COLOR_RGB2BGR))
    cv2.imwrite("_dev/albedo_new.png", cv2.cvtColor((albedo_new * 255).astype(np.uint8), cv2.COLOR_RGB2BGR))
    cv2.imwrite("_dev/rough_old.png", rough_old)
    cv2.imwrite("_dev/rough_new.png", rough_new)
    cv2.imwrite("_dev/metal_old.png", metal_old)
    cv2.imwrite("_dev/metal_new.png", metal_new)
    cv2.imwrite("_dev/normal_new.png", cv2.cvtColor(normal_new, cv2.COLOR_RGB2BGR))

    # --- contact sheet ---
    in_bgr = cv2.cvtColor(img_u8, cv2.COLOR_RGB2BGR)
    row1 = np.hstack(
        [
            label(in_bgr, "input", (0, 200, 255)),
            label(cv2.cvtColor((albedo_old * 255).astype(np.uint8), cv2.COLOR_RGB2BGR), "albedo OLD"),
            label(cv2.cvtColor((albedo_new * 255).astype(np.uint8), cv2.COLOR_RGB2BGR), "albedo NEW"),
        ]
    )
    row2 = np.hstack(
        [
            label(to_bgr_gray(rough_old), "rough OLD", (0, 200, 255)),
            label(to_bgr_gray(rough_new), "rough NEW"),
            label(to_bgr_gray(metal_old), "metal OLD", (0, 200, 255)),
            label(to_bgr_gray(metal_new), "metal NEW"),
        ]
    )
    row3 = np.hstack(
        [
            label(cv2.cvtColor(normal_new, cv2.COLOR_RGB2BGR), "normal NEW"),
        ]
    )
    def _pad(row, width):
        pad = width - row.shape[1]
        return np.hstack([row, np.zeros((row.shape[0], pad, 3), np.uint8)]) if pad > 0 else row

    width = max(r.shape[1] for r in (row1, row2, row3))
    sheet = np.vstack([_pad(row1, width), _pad(row2, width), _pad(row3, width)])
    cv2.imwrite("_dev/contact.png", sheet)

    # --- metrics ---
    masks = probe_masks(rgb)
    lum_new = pbr.luminance(albedo_new)
    lum_old = _old_lum(albedo_old)
    lum_in = pbr.luminance(rgb)
    m_new = metal_new.astype(np.float32) / 255.0
    m_old = metal_old.astype(np.float32) / 255.0
    r_new = rough_new.astype(np.float32) / 255.0
    r_old = rough_old.astype(np.float32) / 255.0

    lines = []
    lines.append(f"texture: {args.texture} ({img_u8.shape[1]}x{img_u8.shape[0]})")
    lines.append("")
    lines.append("== 1. Albedo / specular highlights (lower is better) ==")
    lines.append(f"  frac lum>0.95      old {frac(lum_old, 0.95):.3f}   new {frac(lum_new, 0.95):.3f}")
    lines.append(f"  mean top-1% lum    old {mean(np.sort(lum_old.ravel())[-int(lum_old.size*0.01):]):.3f}   "
                 f"new {mean(np.sort(lum_new.ravel())[-int(lum_new.size*0.01):]):.3f}")
    lines.append(f"  albedo mean vs in  old {mean(lum_old):.3f}/{mean(lum_in):.3f}   new {mean(lum_new):.3f}/{mean(lum_in):.3f}")
    lines.append("")
    lines.append("== 2. Metalness (dark metal SHOULD be detected) ==")
    lines.append(f"  coverage frac>0.5      old {frac(m_old, 0.5):.3f}   new {frac(m_new, 0.5):.3f}")
    lines.append(f"  mean on dark-neutral   old {mean(m_old[masks['dark_neutral']]) if masks['dark_neutral'].any() else float('nan'):.3f}   "
                 f"new {mean(m_new[masks['dark_neutral']]) if masks['dark_neutral'].any() else float('nan'):.3f}")
    lines.append(f"  mean on gold region    old {mean(m_old[masks['gold']]) if masks['gold'].any() else float('nan'):.3f}   "
                 f"new {mean(m_new[masks['gold']]) if masks['gold'].any() else float('nan'):.3f}")
    lines.append(f"  mean on skin-like      old {mean(m_old[masks['skin_like']]) if masks['skin_like'].any() else float('nan'):.3f}   "
                 f"new {mean(m_new[masks['skin_like']]) if masks['skin_like'].any() else float('nan'):.3f}")
    lines.append("")
    lines.append("== 3. Roughness vs metalness decorrelation (|corr| lower is better) ==")
    lines.append(f"  Pearson(rough,metal)   old {pearson(r_old, m_old):+.3f}   new {pearson(r_new, m_new):+.3f}")
    lines.append(f"  roughness std          old {float(np.std(r_old)):.3f}   new {float(np.std(r_new)):.3f}")
    lines.append("")
    lines.append(f"== timings (128px) — de_light {t_de*1000:.0f}ms, rough {t_rough*1000:.0f}ms, metal {t_metal*1000:.0f}ms ==")

    report = "\n".join(lines)
    print(report)
    with open("_dev/metrics.txt", "w", encoding="utf-8") as f:
        f.write(report + "\n")
    print("\nwrote: _dev/{albedo,rough,metal}_{old,new}.png, _dev/normal_new.png, _dev/contact.png, _dev/metrics.txt")


if __name__ == "__main__":
    main()