ComfyGen: shared generator tools (images, portraits, vintage, video, audio, voice)

Moved from YourlifeisGame/Spritegenerator; projects are found via _bootstrap.py (cwd or --project) and provide config.py plus list modules.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-10-02 09:41:31 +02:00
commit e3d21e55c9
21 changed files with 1485 additions and 0 deletions

110
cutout.py Normal file
View File

@@ -0,0 +1,110 @@
"""
Deterministic background removal for the generator's raw renders --
a replacement for the "Image Rembg (Remove Background)" node in the
ComfyUI workflow (see generate.py), which is an AI matting model and
sometimes badly mis-segments stylized/glowing game-art: leaves the backdrop
solid instead of transparent, eats holes into light-colored subjects, etc.
(e.g. output/ship_phantom_cutout_00001_.png shipped with its black backdrop
still fully opaque).
Every raw render sits on a plain solid black backdrop by design (see the
"plain solid black background" suffix in prompts.py, added specifically so
the background can be keyed out reliably) -- so instead of trusting a model
to guess the subject silhouette, this flood-fills the near-black region
connected to the image border (the backdrop, and only the backdrop -- a
sprite's own interior black shading isn't connected to the border) and
clears it to alpha 0, feathering a soft edge for glow/anti-aliasing that
fades into black rather than cutting it off hard.
Usage:
python cutout.py # every *_raw_*.png in output/
python cutout.py ship_phantom # only output/ship_phantom_raw_*.png
python cutout.py aq_menu_lock --holes
`--holes` also clears black the subject *encloses*: the inside of a padlock's
shackle, the middle of an anchor's ring, the gap under a rock arch. The flood
fill only reaches black that touches the frame's edge, so those stayed opaque -
a black blob drawn over whatever the sprite stands on. Opt-in rather than the
default because a large deliberately-black detail (a cave mouth, a big pupil)
is indistinguishable from a hole by colour alone; say so per sprite.
"""
import _bootstrap # Projektordner (config.py, Listen) vor allen anderen Modulen
import config
import glob
import os
import sys
import numpy as np
from PIL import Image
from scipy import ndimage
OUT_DIR = config.OUTPUT_DIR
BLACK_THRESHOLD = 20 # max(R,G,B) below this = definitely background
FEATHER_RANGE = 40 # brightness range over which the edge ring fades in
# An enclosed black region at least this share of the frame is a hole the
# background shows through, not a detail. A pupil on a 1024 render is a few
# hundred pixels; the inside of a padlock's shackle is tens of thousands.
HOLE_SHARE = 0.0015
def cutout(path, holes=False, share=HOLE_SHARE):
im = Image.open(path).convert("RGBA")
arr = np.asarray(im).astype(np.int16)
rgb = arr[:, :, :3]
brightness = rgb.max(axis=2)
near_black = brightness <= BLACK_THRESHOLD
labels, _ = ndimage.label(near_black, structure=np.ones((3, 3))) # 8-connected
border_labels = set(labels[0, :]) | set(labels[-1, :]) | set(labels[:, 0]) | set(labels[:, -1])
border_labels.discard(0)
background = np.isin(labels, list(border_labels))
if holes:
# Every near-black region, counted in one pass, and the large ones that
# do not touch the edge added to the background. Sizes by bincount
# rather than a mask per label: a render has thousands of tiny dark
# specks and one comparison over the whole frame each is minutes.
sizes = np.bincount(labels.ravel())
least = share * near_black.size
enclosed = [label for label in np.nonzero(sizes >= least)[0]
if label != 0 and label not in border_labels]
if enclosed:
background |= np.isin(labels, enclosed)
alpha = arr[:, :, 3].copy()
alpha[background] = 0
# feather the ring of foreground pixels touching the backdrop, so a
# glowing edge that anti-aliases into black doesn't get a hard fringe
dilated = ndimage.binary_dilation(background, iterations=1)
edge_ring = dilated & ~background
feather = np.clip((brightness - BLACK_THRESHOLD) / FEATHER_RANGE * 255, 0, 255).astype(np.uint8)
alpha[edge_ring] = np.minimum(alpha[edge_ring], feather[edge_ring])
out = arr.copy()
out[:, :, 3] = alpha
return Image.fromarray(out.astype(np.uint8), "RGBA")
if __name__ == "__main__":
# Flags apart from the name, so `--holes` works on either side of it.
flags = {arg for arg in sys.argv[1:] if arg.startswith("--")}
names = [arg for arg in sys.argv[1:] if not arg.startswith("--")]
only = names[0] if names else None
# `--holes=0.006` raises the bar for one sprite whose pupil is bigger than
# HOLE_SHARE: the seahorse's eye went transparent with its tail's loop.
sized = [flag for flag in flags if flag.startswith("--holes=")]
holes = "--holes" in flags or bool(sized)
share = float(sized[0].split("=", 1)[1]) if sized else HOLE_SHARE
pattern = f"{only}_raw_*.png" if only else "*_raw_*.png"
raws = sorted(glob.glob(os.path.join(OUT_DIR, pattern)))
if not raws:
print(f"No raw renders found matching {pattern} in {OUT_DIR}")
sys.exit(1)
for raw_path in raws:
dest = raw_path.replace("_raw_", "_cutout_")
cutout(raw_path, holes=holes, share=share).save(dest)
print(f"-> {dest}" + (" (enclosed holes cleared)" if holes else ""))