ThreeKingdomsSlingshot/Tools/bg_extend.py

192 lines
10 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 -*-
"""전장 배경 바깥 여분 그리기(outpaint) — PD 2026-11-21 「각 전장의 배경 화면을 더 그리는 게 좋을 것 같아 ·
더 그리는 배경은 못 가는 이동 불가 지형이기 때문에 산이나 나무들, 울타리나 목책, 성벽 등으로 자연스럽게 연출」.
원본(2000×3200 = 전장 20×32)은 가운데 그대로 두고 둘레(표 Tools/bg_extend_spec.json pad)만 새로 그린다.
게임은 Resources/Board/bg_margin.csv 의 여분 px 를 읽어 가운데가 전장에 맞도록 놓는다(Board.FitArt).
python Tools/bg_extend.py prep [이름…] 1단계(구성) = 밑그림 · 마스크 · 참고 · jobs.json (이름 없으면 전부)
python -I <조직 레포>/scripts/pixel/comfy_krea2.py --jobs <작업 폴더>/jobs.json
python Tools/bg_extend.py prep2 [이름…] 2단계(또렷하게) = 1단계 그림을 밑그림으로 다시 그리기 · jobs2.json
python -I <조직 레포>/scripts/pixel/comfy_krea2.py --jobs <작업 폴더>/jobs2.json
python Tools/bg_extend.py post [이름…] 4x-UltraSharp → 원본 붙이기 → out/<이름>_s<seed>.png + 잠금 차이
두 단계인 까닭(2026-11-21 실측): 마스크로 여분만 처음부터 그리면(세기 1.0) 구성은 좋지만 여분이 흐리다(외곽선이 뭉개짐) →
그 그림을 밑그림으로 같은 마스크에서 세기 refine(0.65)로 한 번 더 그리면 외곽선이 또렷해진다. 마스크 없이 다시 그리면 더 또렷하지만
가운데가 달라져 원본을 붙였을 때 이음새에서 나무·목책이 어긋난다(탈락). 가운데는 마지막에 원본을 그대로 붙인다(차이 0).
python Tools/bg_extend.py sheet <out.jpg> [이름…] 후보 모음(전장 테두리 표시)
python Tools/bg_extend.py install 이름=seed … 원본 백업 → Resources/Board 덮어쓰기 + bg_margin.csv 줄
작업 폴더 = 환경 변수 TKS_BGEXT(기본 E:/Nerdnavis/_tks_bgext) · 생성 서버 = ComfyUI 127.0.0.1:8000(Krea 2 styleref + 마스크).
"""
import csv
import json
import os
import shutil
import sys
import numpy as np
from PIL import Image, ImageDraw
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BOARD = os.path.join(ROOT, "Assets", "Resources", "Board")
WORK = os.environ.get("TKS_BGEXT", "E:/Nerdnavis/_tks_bgext")
ORG_PIXEL = os.environ.get("NN_PIXEL", "E:/NerdNavisAi/scripts/pixel")
SPEC = json.load(open(os.path.join(ROOT, "Tools", "bg_extend_spec.json"), encoding="utf-8"))
PAD = SPEC["pad"]
WW, WH = SPEC["work"] # 2단계(또렷하게) 생성 크기
W1, H1 = SPEC["work1"] # 1단계(구성) 생성 크기 — 흐려도 되므로 작게
OVERLAP = 16 # 원본 안쪽으로 다시 그리게 두는 폭(px · 이음새가 굳지 않게)
FEATHER = 12 # 원본을 붙일 때 가장자리 섞는 폭(px · 전장 테두리 선 0.16 칸 아래)
def d(*p):
path = os.path.join(WORK, *p)
os.makedirs(os.path.dirname(path), exist_ok=True)
return path
def names(args):
return args if args else list(SPEC["items"].keys())
def src(name):
"""늘리기 전 원본(이미 설치했으면 작업 폴더의 백업이 원본)."""
bak = os.path.join(WORK, "orig", name + ".png")
return bak if os.path.isfile(bak) else os.path.join(BOARD, name + ".png")
def full_size(im):
return im.width + PAD["left"] + PAD["right"], im.height + PAD["top"] + PAD["bottom"]
def prep(args):
jobs = []
for n in names(args):
im = Image.open(src(n)).convert("RGB")
a = np.asarray(im)
full = np.pad(a, ((PAD["top"], PAD["bottom"]), (PAD["left"], PAD["right"]), (0, 0)), mode="reflect")
Image.fromarray(full).resize((W1, H1), Image.LANCZOS).save(d("init", n + "_init.png"))
m = np.full(full.shape[:2], 255, np.uint8)
m[PAD["top"] + OVERLAP: PAD["top"] + im.height - OVERLAP, PAD["left"] + OVERLAP: PAD["left"] + im.width - OVERLAP] = 0
ms = np.asarray(Image.fromarray(m).resize((W1, H1), Image.BILINEAR))
Image.fromarray(np.where(ms > 0, 255, 0).astype(np.uint8)).convert("RGB").save(d("init", n + "_mask.png"))
im.resize((im.width // 2, im.height // 2), Image.LANCZOS).save(d("init", n + "_ref.png"))
for s in SPEC["seeds"]:
jobs.append({"mode": "styleref", "prompt": SPEC["prompt"].replace("{around}", SPEC["items"][n]), "seed": s,
"out": d("gen", "%s_s%d.png" % (n, s)), "refs": [d("init", n + "_ref.png")],
"init": d("init", n + "_init.png"), "mask": d("init", n + "_mask.png"),
"denoise": 1.0, "w": W1, "h": H1, "steps": 8, "style": 1.0})
json.dump(jobs, open(d("jobs.json"), "w", encoding="utf-8"), ensure_ascii=False, indent=1)
print("jobs", len(jobs), d("jobs.json"))
def prep2(args):
jobs = []
for n in names(args):
for s in SPEC["seeds"]:
g1 = os.path.join(WORK, "gen", "%s_s%d.png" % (n, s))
if not os.path.isfile(g1):
continue
Image.open(g1).convert("RGB").resize((WW, WH), Image.LANCZOS).save(d("init", "%s_s%d_i2.png" % (n, s)))
Image.open(d("init", n + "_mask.png")).resize((WW, WH), Image.NEAREST).save(d("init", n + "_mask2.png"))
jobs.append({"mode": "styleref", "prompt": SPEC["prompt"].replace("{around}", SPEC["items"][n]), "seed": s,
"out": d("g2", "%s_s%d.png" % (n, s)), "refs": [d("init", n + "_ref.png")],
"init": d("init", "%s_s%d_i2.png" % (n, s)), "mask": d("init", n + "_mask2.png"),
"denoise": SPEC["refine"], "w": WW, "h": WH, "steps": 8, "style": 1.0})
json.dump(jobs, open(d("jobs2.json"), "w", encoding="utf-8"), ensure_ascii=False, indent=1)
print("jobs2", len(jobs), d("jobs2.json"))
def upscale(path, out, w, h):
sys.path.insert(0, ORG_PIXEL)
import comfy_krea2 as ck
wf = {"1": {"class_type": "LoadImage", "inputs": {"image": ck.upload(path)}},
"2": {"class_type": "UpscaleModelLoader", "inputs": {"model_name": "4x-UltraSharp.pth"}},
"3": {"class_type": "ImageUpscaleWithModel", "inputs": {"upscale_model": ["2", 0], "image": ["1", 0]}},
"4": {"class_type": "ImageScale", "inputs": {"image": ["3", 0], "upscale_method": "lanczos", "width": w, "height": h, "crop": "disabled"}},
"9": {"class_type": "SaveImage", "inputs": {"images": ["4", 0], "filename_prefix": "bgext_up"}}}
return ck.run(wf, out, 600)
def post(args):
for n in names(args):
im = Image.open(src(n)).convert("RGB")
fw, fh = full_size(im)
for s in SPEC["seeds"]:
gen = os.path.join(WORK, "g2", "%s_s%d.png" % (n, s))
if not os.path.isfile(gen):
continue
up = d("up_g2", "%s_s%d.png" % (n, s))
if not os.path.isfile(up):
upscale(gen, up, fw, fh)
base = np.asarray(Image.open(up).convert("RGB").resize((fw, fh), Image.LANCZOS)).astype(np.float32)
a = np.asarray(im).astype(np.float32)
yy, xx = np.mgrid[0:im.height, 0:im.width]
edge = np.minimum(np.minimum(xx, im.width - 1 - xx), np.minimum(yy, im.height - 1 - yy)).astype(np.float32)
al = np.clip(edge / FEATHER, 0.0, 1.0)[..., None]
y0, x0 = PAD["top"], PAD["left"]
reg = base[y0:y0 + im.height, x0:x0 + im.width]
base[y0:y0 + im.height, x0:x0 + im.width] = a * al + reg * (1.0 - al)
res = np.clip(base + 0.5, 0, 255).astype(np.uint8)
Image.fromarray(res).save(d("out", "%s_s%d.png" % (n, s)))
f = FEATHER
lock = np.abs(res[y0 + f:y0 + im.height - f, x0 + f:x0 + im.width - f].astype(np.int16) - np.asarray(im)[f:-f, f:-f]).max()
print("OK %s s%d → %dx%d · 잠금(원본 안쪽) 최대 차이 %d" % (n, s, fw, fh, lock), flush=True)
def sheet(args):
out, ns = args[0], names(args[1:])
k = 0.2
cells = []
for n in ns:
for s in SPEC["seeds"]:
p = os.path.join(WORK, "out", "%s_s%d.png" % (n, s))
if not os.path.isfile(p):
continue
im = Image.open(p).convert("RGB")
sm = im.resize((int(im.width * k), int(im.height * k)), Image.LANCZOS)
dr = ImageDraw.Draw(sm)
dr.rectangle([PAD["left"] * k, PAD["top"] * k, (im.width - PAD["right"]) * k, (im.height - PAD["bottom"]) * k], outline=(255, 230, 120))
cells.append(sm)
if not cells:
print("그림 없음")
return
cw, ch = cells[0].size
cols = min(len(cells), 6)
rows = (len(cells) + cols - 1) // cols
sh = Image.new("RGB", (cols * (cw + 6), rows * (ch + 6)), (24, 24, 24))
for i, c in enumerate(cells):
sh.paste(c, ((i % cols) * (cw + 6), (i // cols) * (ch + 6)))
sh.save(out, quality=88)
print(out, len(cells))
def install(args):
table = os.path.join(BOARD, "bg_margin.csv")
rows = {}
if os.path.isfile(table):
for r in csv.DictReader(open(table, encoding="utf-8-sig")):
rows[r["s_file"]] = r
for a in args:
n, s = a.split("=")
res = os.path.join(WORK, "out", "%s_s%s.png" % (n, s))
dst = os.path.join(BOARD, n + ".png")
bak = d("orig", n + ".png")
if not os.path.isfile(bak):
shutil.copy2(dst, bak) # 원본 백업(한 번만)
shutil.copy2(res, dst)
w, h = Image.open(dst).size
rows[n] = {"s_file": n, "n_w": w, "n_h": h, "n_left": PAD["left"], "n_right": PAD["right"], "n_top": PAD["top"], "n_bottom": PAD["bottom"],
"Memo": "바깥 여분(이동 불가 지형) · seed " + s}
print("설치", n, w, h)
with open(table, "w", encoding="utf-8-sig", newline="") as f:
wtr = csv.DictWriter(f, fieldnames=["s_file", "n_w", "n_h", "n_left", "n_right", "n_top", "n_bottom", "Memo"])
wtr.writeheader()
for k in sorted(rows):
wtr.writerow(rows[k])
if __name__ == "__main__":
{"prep": prep, "prep2": prep2, "post": post, "sheet": sheet, "install": install}[sys.argv[1]](sys.argv[2:])