#!/usr/bin/env python3
"""Option A: in one Z-Image sheet, fill the head area of the given body panels with the background so only the
close-up shows a face. Cut line = the narrowest foreground row (the neck) between 12% and 40% of the figure height.
usage: hide_faces.py in.png out.png x0:x1 [x0:x1 ...]   (panel x ranges in pixels)"""
import sys
import numpy as np
from PIL import Image
src, out, *ranges = sys.argv[1:]
im = Image.open(src).convert("RGB"); a = np.asarray(im).astype(int).copy()
for r in ranges:
    x0, x1 = map(int, r.split(":"))
    p = a[:, x0:x1]
    bg = np.median(np.concatenate([p[:30, :].reshape(-1, 3), p[-30:, :].reshape(-1, 3)]), axis=0)
    fg = np.abs(p - bg).sum(2) > 45
    rows = np.where(fg.sum(1) > 4)[0]; y0, y1 = rows[0], rows[-1]; h = y1 - y0
    ws = [(fg[y].sum(), y) for y in range(y0 + int(0.12 * h), y0 + int(0.40 * h))]
    neck = min(ws)[1] + int(0.012 * h)
    edge = p[:neck, :12]      # background at each row, from the panel edges
    rowbg = np.median(edge, axis=1)                                        # (neck, 3) follows the vertical gradient
    a[:neck, x0 + 12:x1] = rowbg[:, None, :].astype(int)
    print(r, "head cut at y", neck, "figure", y0, y1)
Image.fromarray(a.astype("uint8")).save(out)
