#!/usr/bin/env python3
"""Cut the kid out by flood-filling the flat cream paper background.
The character is closed by a dark ink outline, so a border-connected
bright/low-saturation region is exactly the background -- no sticker halo."""
import numpy as np
from PIL import Image, ImageFilter
from scipy import ndimage

ROOT = "/root/notchlight"
img = Image.open(f"{ROOT}/assets/kid_v2.png").convert("RGB")
a = np.asarray(img).astype(np.int16)
h, w, _ = a.shape

mx = a.max(axis=2); mn = a.min(axis=2)
sat = (mx - mn)
bright = (mx > 205) & (sat < 34)          # cream paper + shirt cream
# label bright regions; keep only ones touching the image border
lab, n = ndimage.label(bright)
border = set(lab[0, :]) | set(lab[-1, :]) | set(lab[:, 0]) | set(lab[:, -1])
border.discard(0)
bgmask = np.isin(lab, list(border))
# close tiny pinholes in the paper texture, then slightly grow into the AA edge
bgmask = ndimage.binary_closing(bgmask, structure=np.ones((3, 3)), iterations=2)
bgmask = ndimage.binary_dilation(bgmask, iterations=1)
alpha = np.where(bgmask, 0, 255).astype(np.uint8)

alpha_img = Image.fromarray(alpha).filter(ImageFilter.GaussianBlur(0.7))
rgba = np.dstack([np.asarray(img), np.asarray(alpha_img)]).astype(np.uint8)
kid = Image.fromarray(rgba, "RGBA")
kid = kid.crop(kid.getbbox())
kid.save(f"{ROOT}/assets/kid_cut.png")
print("kid cut", kid.size, "alpha coverage", (np.asarray(alpha_img) > 128).mean())
