#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""三视图预处理（本机自写版，比 thirds 裁剪更贴合主体）：
按背景阈值切出每个视图的连通列簇，取最左簇 = 正面视图，紧贴裁出；
输出：
  pic1_front.jpg —— 正面视图（<Picture 1> 身份锚定）
  pic2_sheet.jpg —— 完整三视图（<Picture 2>，同一人三角度，仅作外观/服装补充）
用法: python prep_refs.py <三视图图> <输出目录> <前缀>
"""
import sys
from pathlib import Path
from PIL import Image
import numpy as np

src, out_dir, prefix = sys.argv[1], Path(sys.argv[2]), sys.argv[3]
out_dir.mkdir(parents=True, exist_ok=True)

im = Image.open(src).convert("RGB")
a = np.asarray(im).astype(np.int16)
h, w = a.shape[:2]

# 背景 = 接近纯白（三视图是白底）
bg = (a.min(axis=2) > 232) & (a.max(axis=2) - a.min(axis=2) < 14)
fg = ~bg
col = fg.sum(axis=0)          # 每列前景像素数
row = fg.sum(axis=1)

# 列方向：找有内容的列簇（间隙 > 1% 宽 视为分栏）
thresh = max(3, int(0.004 * h))
active = col > thresh
clusters, start = [], None
for i, v in enumerate(active):
    if v and start is None:
        start = i
    elif not v and start is not None:
        if i - start > w * 0.01:
            clusters.append((start, i))
        start = None
if start is not None:
    clusters.append((start, len(active)))
# 合并间隔很小的簇
merged = []
for c in clusters:
    if merged and c[0] - merged[-1][1] < w * 0.02:
        merged[-1] = (merged[-1][0], c[1])
    else:
        merged.append(list(c))
clusters = [tuple(c) for c in merged]

print(f"{prefix}: {w}x{h}, 检测到 {len(clusters)} 个视图列簇: {clusters}")

if clusters:
    x0, x1 = clusters[0]                       # 最左 = 正面
    sub = fg[:, x0:x1]
    rows = np.where(sub.sum(axis=1) > max(2, int(0.004 * (x1 - x0))))[0]
    y0, y1 = (rows[0], rows[-1] + 1) if len(rows) else (0, h)
    m = int(0.04 * (y1 - y0))                  # 4% 余量
    box = (max(0, x0 - m), max(0, y0 - m), min(w, x1 + m), min(h, y1 + m))
else:
    box = (0, 0, w, h)
print(f"{prefix}: 正面裁剪框 {box}")
im.crop(box).save(out_dir / f"{prefix}_front.jpg", quality=95)
im.save(out_dir / f"{prefix}_sheet.jpg", quality=95)
print("saved:", out_dir / f"{prefix}_front.jpg", out_dir / f"{prefix}_sheet.jpg")
