#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""四角精确复核：裁四角放大图 + 只在角区找高饱和红印/孤立深字"""
import os
import numpy as np
from PIL import Image

WORK = os.path.join(os.path.dirname(os.path.abspath(__file__)), "_s72_work")
FILES = ["ep03_s72_monk_cand1_front.png", "ep03_s72_monk_cand2_front.png"]

for fn in FILES:
    p = os.path.join(WORK, fn)
    im = Image.open(p).convert("RGB")
    a = np.asarray(im).astype(np.float32)
    h, w = a.shape[:2]
    key = "cand1" if "cand1" in fn else "cand2"
    print("====", fn, w, h)
    boxes = {
        "TL": (0, int(w * .22), 0, int(h * .22)),
        "TR": (int(w * .78), w, 0, int(h * .22)),
        "BL": (0, int(w * .22), int(h * .78), h),
        "BR": (int(w * .78), w, int(h * .78), h),
    }
    for tag, (x0, x1, y0, y1) in boxes.items():
        reg = a[y0:y1, x0:x1]
        r, g, b = reg[:, :, 0], reg[:, :, 1], reg[:, :, 2]
        # 红印：高饱和正红/朱红（比肤色更红：r-g>55 且 g<130）
        seal = (r > g + 55) & (r > b + 55) & (r > 110) & (g < 135)
        # 孤立深字/墨点
        ink = (reg.max(axis=2) < 110)
        print("  %s seal_px=%d ink_px=%d" % (tag, int(seal.sum()), int(ink.sum())))
        crop = Image.fromarray(reg.astype(np.uint8))
        crop.resize((crop.width * 3, crop.height * 3), Image.LANCZOS).save(
            os.path.join(WORK, "corner_%s_%s.png" % (key, tag)))
    # 拼一张四角总览
    cs = [Image.open(os.path.join(WORK, "corner_%s_%s.png" % (key, t))) for t in boxes]
    Wd = max(c.width for c in cs) * 2 + 20
    Hd = max(c.height for c in cs) * 2 + 20
    sheet = Image.new("RGB", (Wd, Hd), (235, 230, 220))
    for idx, c in enumerate(cs):
        sheet.paste(c, ((idx % 2) * (max(x.width for x in cs) + 20),
                        (idx // 2) * (max(x.height for x in cs) + 20)))
    sheet.save(os.path.join(WORK, "corners_sheet_%s.png" % key))
    print("  sheet:", os.path.join(WORK, "corners_sheet_%s.png" % key))
