Files
ComfyGen/trim.py

73 lines
2.3 KiB
Python
Raw Permalink Normal View History

"""Trim the transparent margin off a cutout, so the asset is the object.
The generator always renders into a 1024x1024 frame and `cutout.py` only
removes the backdrop - it leaves the object floating in a square with a wide
transparent border. Every asset in `assets/ui/` was cropped to its object by
hand afterwards, which is why they have aspect ratios like 939x454.
Doing it by hand is fine once. Doing it for a plate whose aspect ratio the
layout code then has to match is a good way to get a frame that is two pixels
lopsided, so this does it from the alpha channel instead.
py -3.12 trim.py tw_hud_plate one cutout, by name
py -3.12 trim.py every *_cutout_*.png in output/
Writes `<name>_trimmed.png` beside the cutout. Copy into the game by hand -
nothing here touches assets/.
"""
import glob
import os
import sys
from PIL import Image
import _bootstrap # Projektordner (config.py, Listen) vor allen anderen Modulen
import config
OUT = config.OUTPUT_DIR
# Alpha at or below this counts as background. Not zero: the matting model
# leaves a fringe of nearly-transparent pixels around the object, and trimming
# to alpha > 0 keeps a halo several pixels wide.
THRESHOLD = 8
def trim(path):
image = Image.open(path).convert("RGBA")
alpha = image.getchannel("A").point(lambda v: 255 if v > THRESHOLD else 0)
box = alpha.getbbox()
if box is None:
print(f" {os.path.basename(path)}: fully transparent, skipped")
return
cropped = image.crop(box)
stem = os.path.basename(path).split("_cutout_")[0]
dest = os.path.join(OUT, f"{stem}_trimmed.png")
cropped.save(dest)
width, height = cropped.size
print(f" {stem:20s} {image.size[0]}x{image.size[1]} -> {width}x{height}"
f" ({width / height:.2f}:1)")
def main():
if len(sys.argv) > 1:
targets = []
for name in sys.argv[1:]:
found = sorted(glob.glob(os.path.join(OUT, f"{name}_cutout_*.png")))
if not found:
print(f"no cutout found for {name}")
return 1
targets.append(found[-1])
else:
targets = sorted(glob.glob(os.path.join(OUT, "*_cutout_*.png")))
for path in targets:
trim(path)
return 0
if __name__ == "__main__":
raise SystemExit(main())