"""Put the photo's fine detail back onto a smoothed albedo: albedo * (photo / blur(photo)), per channel luminance.

usage: python3 detail_restore.py <est dir> <sigma px> [strength] -> writes albedo_detail.png
High-pass of the photo = freckles, pores, fine wrinkles (and a little of the original small-scale shading).
"""
import sys
import numpy as np
from PIL import Image, ImageFilter
E, sigma = sys.argv[1], float(sys.argv[2])
strength = float(sys.argv[3]) if len(sys.argv) > 3 else 1.0
ph = Image.open(f"{E}/image.png").convert("RGB")
al = np.asarray(Image.open(f"{E}/albedo.png").convert("RGB").resize(ph.size), np.float32) / 255
lum = ph.convert("L")
blur = np.asarray(lum.filter(ImageFilter.GaussianBlur(sigma)), np.float32) + 4
hp = (np.asarray(lum, np.float32) + 4) / blur
hp = (np.clip(hp, 0.6, 1.4) ** strength)[..., None]
Image.fromarray((np.clip(al * hp, 0, 1) * 255).astype(np.uint8)).save(f"{E}/albedo_detail.png")
print("wrote", f"{E}/albedo_detail.png", "high-pass range", hp.min(), hp.max())
