ThreeKingdomsSlingshot/Tools/hero_icon_crop.py

149 lines
6.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# -*- coding: utf-8 -*-
"""영웅 아이콘(조각 · 완제품) 얼굴 자리 표 만들기(PD 2026-11-26 「영웅 조각 = 직소 · 완제품 아이콘」) → Assets/Resources/UI/HeroIcon/hero_icon_crop.csv.
영웅 그림 Units/<art>/front_idle/f000.png 에서 머리 · 어깨 정사각(그림 px · 왼쪽 위 원점 · y 아래로):
- 얼굴 가운데 = 살색(색상 0~35° · 채도 0.1~0.62 · 밝기 > 0.55 · 관우 붉은 얼굴 포함)이 가장 몰린 줄 띠(그림 위쪽 60 %)의 가운데
- 변 = 눈 간격(Units/art_size.csv eye_px · 말 탄 영웅은 그림이 작게 그려져 눈 간격으로 같은 머리 크기) × EYE_K · 얼굴 가운데가 위에서 UP 비율 자리
그림을 바꾸거나 영웅을 더하면 다시 돌린다: python -I Tools/hero_icon_crop.py [--sheet 확인.png]
"""
import csv, io, os, re, sys
from PIL import Image
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
RES = os.path.join(ROOT, "Assets", "Resources")
OUT = os.path.join(RES, "UI", "HeroIcon", "hero_icon_crop.csv")
EYE_K = 4.2
UP = 0.48 # 눈 높이가 위에서 이 비율 자리
# 손 보정(art_size 눈 실측이 어긋난 영웅 · QA 2026-11-26 72명 시트 · 110 px 칸 기준 실측을 그림 px 로 옮김)
# side_k = 변 배율 · eye_dy = 실제 눈 높이 - 표 눈 높이(px · 음수 = 위) · dx = 얼굴 가운데 - 살색 가운데(px)
FIX = {
"dongzhuo": {"side_k": 1.43, "eye_dy": -89.0, "dx": 0.0, "why": "얼굴이 넓어 눈 간격이 머리 크기를 작게 잼 · 표 눈 높이가 89 px 아래(QA B)"},
"cc_boss_xuchu": {"side_k": 1.0, "eye_dy": 61.0, "dx": 0.0, "why": "표 눈 높이가 61 px 위(QA M)"},
"wu_chengpu": {"side_k": 1.0, "eye_dy": 0.0, "dx": 60.0, "why": "살색 가운데가 얼굴보다 60 px 왼쪽(QA M)"},
}
def hero_arts():
t = open(os.path.join(RES, "OutGame", "HeroDb.asset"), encoding="utf-8").read()
arts = []
for blk in re.split(r"\n - id: ", t)[1:]:
m = re.search(r"\n art: (.*)", blk)
s = re.search(r"\n isSoldier: (\d)", blk)
if m and m.group(1).strip() and not (s and s.group(1) == "1"):
a = m.group(1).strip()
if a not in arts:
arts.append(a)
return arts
def eye_table():
"""art → (눈 간격 px, 눈 높이 = 그림 아래에서 px) — Units/art_size.csv eye_px · eye_up_px(게임 크기 맞춤 실측)."""
res = {}
for r in csv.DictReader(io.open(os.path.join(RES, "Units", "art_size.csv"), encoding="utf-8-sig")):
try:
res[r["art"]] = (float(r["eye_px"]), float(r["eye_up_px"]))
except (KeyError, ValueError):
pass
return res
def frame0(art):
p = os.path.join(RES, "Units", art, "front_idle", "f000.png")
if os.path.exists(p):
return p
d = os.path.join(RES, "Units", art)
if os.path.isdir(d):
for sub in sorted(os.listdir(d)):
q = os.path.join(d, sub, "f000.png")
if os.path.exists(q):
return q
return None
def face(png, eye=None):
"""얼굴 가운데(x · y) — 눈 높이를 알면 y = 눈 높이 · x = 그 높이 둘레(눈 간격 ±0.9) 살색의 가운데(말 · 소품의 살색 빼기 · 말 탄 영웅 3명 실측 오검출)."""
im = Image.open(png).convert("RGBA")
if eye:
ep, eu = eye
ey = im.size[1] - eu
hsv = im.convert("RGB").convert("HSV").load()
al = im.split()[3].load()
xs = []
for y in range(int(ey - ep * 0.9), int(ey + ep * 0.9), 2):
for x in range(0, im.size[0], 2):
if 0 <= y < im.size[1] and al[x, y] >= 200:
hh, ss, vv = hsv[x, y]
if (hh <= 25 or hh >= 250) and 25 <= ss <= 158 and vv >= 140:
xs.append(x)
if xs:
xs.sort()
return im.size, xs[len(xs) // 2], ey
a = im.split()[3]
x0, y0, x1, y1 = a.getbbox()
hsv = im.convert("RGB").convert("HSV").load()
al = a.load()
rows = {}
for y in range(y0, int(y0 + (y1 - y0) * 0.6), 2):
xs = []
for x in range(x0, x1, 2):
if al[x, y] < 200:
continue
hh, ss, vv = hsv[x, y]
if (hh <= 25 or hh >= 250) and 25 <= ss <= 158 and vv >= 140:
xs.append(x)
rows[y] = xs
mx = max((len(v) for v in rows.values()), default=0)
if mx == 0:
return im.size, (x0 + x1) / 2, y0 + (y1 - y0) * 0.25
ys = sorted(rows)
yb = max(ys, key=lambda y: len(rows[y]))
band = [y for y in ys if abs(y - yb) < (y1 - y0) * 0.18 and len(rows[y]) >= mx * 0.35]
allx = sorted(x for y in band for x in rows[y])
return im.size, allx[len(allx) // 2], (band[0] + band[-1]) / 2
def main():
sys.stdout.reconfigure(encoding="utf-8")
eyes = eye_table()
out, miss = [], []
for art in hero_arts():
p = frame0(art)
if not p:
miss.append(art)
continue
e = eyes.get(art)
(w, h), cx, cy = face(p, e)
side = (e[0] if e else 142.0) * EYE_K
fx = FIX.get(art)
note = ""
if fx:
side *= fx["side_k"]
cy += fx["eye_dy"]
cx += fx["dx"]
note = "손 보정: " + fx["why"]
out.append((art, round(cx - side / 2, 1), round(cy - side * UP, 1), round(side, 1), w, h, note))
os.makedirs(os.path.dirname(OUT), exist_ok=True)
with open(OUT, "w", encoding="utf-8-sig", newline="\n") as f:
f.write("# 영웅 아이콘 얼굴 자리(Tools/hero_icon_crop.py 가 만듦 · 손으로 고치면 note 에 적고 도구를 다시 돌릴 때 확인) · 그림 = Units/<art>/front_idle/f000 · px · 왼쪽 위 원점 · y 아래로\n")
f.write("# x · y = 자를 정사각 왼쪽 위 · side = 변(눈 간격 × %.1f) · w · h = 그림 크기(게임이 스프라이트 크기와 다르면 비율로 맞춤)\n" % EYE_K)
f.write("art,x,y,side,w,h,note\n")
for r in out:
f.write("%s,%s,%s,%s,%d,%d,%s\n" % r)
print("영웅 %d · 그림 없음 %d %s → %s" % (len(out), len(miss), miss[:8], OUT))
if "--sheet" in sys.argv:
sh_path = sys.argv[sys.argv.index("--sheet") + 1]
n = len(out)
cols = 12
sh = Image.new("RGBA", (cols * 110, ((n + cols - 1) // cols) * 110), (60, 60, 70, 255))
for i, (art, x, y, s, w, h, _) in enumerate(out):
im = Image.open(frame0(art)).convert("RGBA")
c = Image.new("RGBA", (int(s), int(s)), (0, 0, 0, 0))
c.paste(im.crop((max(0, int(x)), max(0, int(y)), min(w, int(x + s)), min(h, int(y + s)))), (max(0, -int(x)), max(0, -int(y))))
sh.alpha_composite(c.resize((100, 100), Image.LANCZOS), ((i % cols) * 110 + 5, (i // cols) * 110 + 5))
sh.convert("RGB").save(sh_path)
if __name__ == "__main__":
main()