"""Fine shape detail from one photo: high-pass of MoGe-2's predicted normals, for use as a detail layer.
hp = n - blur(n, sigma): creases and folds, without the overall head shape (which comes from FLAME).
Converted to the Blender scene frame (x, -y, -z) and stored as 8-bit RGB: value = hp + 0.5 (clipped to +-0.5).
usage: python3 detail_normals.py <est dir> <sigma px>  -> normal_detail.png
"""
import sys, numpy as np
from PIL import Image
E, sigma = sys.argv[1], float(sys.argv[2])
n = np.load(f"{E}/normal.npy").astype(np.float32); m = np.load(f"{E}/mask.npy").astype(bool)
n = n * np.array([1, -1, -1], np.float32)
r = int(3 * sigma); x = np.arange(-r, r + 1); g = np.exp(-x ** 2 / (2 * sigma ** 2)); g /= g.sum()
def blur(a):
    a = np.apply_along_axis(lambda v: np.convolve(np.pad(v, r, mode="edge"), g, "valid"), 0, a)
    return np.apply_along_axis(lambda v: np.convolve(np.pad(v, r, mode="edge"), g, "valid"), 1, a)
b = np.stack([blur(n[..., c]) for c in range(3)], -1)
hp = np.where(m[..., None], n - b, 0)
print("high-pass magnitude p50/p99:", np.percentile(np.linalg.norm(hp, axis=-1)[m], [50, 99]).round(3))
Image.fromarray(((np.clip(hp, -0.5, 0.5) + 0.5) * 255).round().astype(np.uint8)).save(f"{E}/normal_detail.png")
print("wrote", f"{E}/normal_detail.png")
