From f5fdd4a6d4d1866c4f4998cf94b993f3e9ffb5ed Mon Sep 17 00:00:00 2001 From: Michi Date: Sun, 8 Nov 2026 01:41:02 +0100 Subject: [PATCH] 3D: square mesh input, paint_mesh projection painter, cutout_ai generate_mesh pads portrait images to a white square (CLIPVisionEncode centre-crops, which cut off helmet and feet). paint_mesh cleans a Hunyuan3D shape, projects front/back views onto it with z-buffer visibility and writes a painted GLB, an OBJ for Mixamo and a preview. cutout_ai/adopt --ai let rembg decide near-black regions. Co-Authored-By: Claude Opus 5.5 --- adopt.py | 12 ++- cutout.py | 22 ++++ generate_mesh.py | 30 +++++- paint_mesh.py | 265 +++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 323 insertions(+), 6 deletions(-) create mode 100644 paint_mesh.py diff --git a/adopt.py b/adopt.py index 277d869..9feb532 100644 --- a/adopt.py +++ b/adopt.py @@ -10,6 +10,7 @@ PictureBoxSizeMode.Zoom, so square keeps every icon the same visual size. py -3.12 adopt.py --all every name in the prompt list py -3.12 adopt.py --size 512 hero larger square (default 128) py -3.12 adopt.py --holes archer also clear enclosed black (see cutout.py) + py -3.12 adopt.py --ai hero dark parts decided by a matting model (rembg) """ import glob import importlib @@ -20,7 +21,7 @@ from PIL import Image import _bootstrap # Projektordner (config.py, Listen) vor allen anderen Modulen import config -from cutout import cutout +from cutout import cutout, cutout_ai HERE = os.path.dirname(os.path.abspath(__file__)) DEST = os.path.join(config.ASSETS_DIR, "Sprites") @@ -29,7 +30,7 @@ MARGIN = 0.04 # share of the side left free around the icon ALPHA_THRESHOLD = 8 -def adopt(name, size=None, holes=False): +def adopt(name, size=None, holes=False, ai=False): size = size or SIZE raws = sorted(glob.glob(os.path.join(config.OUTPUT_DIR, f"{name}_raw_*.png")), key=os.path.getmtime) @@ -37,7 +38,7 @@ def adopt(name, size=None, holes=False): print(f" {name}: no raw render in output/, skipped") return False - image = cutout(raws[-1], holes=holes) + image = cutout_ai(raws[-1]) if ai else cutout(raws[-1], holes=holes) box = image.getchannel("A").point(lambda v: 255 if v > ALPHA_THRESHOLD else 0).getbbox() if box is None: print(f" {name}: fully transparent after cutout, skipped") @@ -78,7 +79,8 @@ if __name__ == "__main__": args = sys.argv[1:] size = None holes = "--holes" in args - args = [a for a in args if a != "--holes"] + ai = "--ai" in args + args = [a for a in args if a not in ("--holes", "--ai")] if len(args) >= 2 and args[0] == "--size": size = int(args[1]) args = args[2:] @@ -90,5 +92,5 @@ if __name__ == "__main__": if args == ["--all"]: prompts = importlib.import_module(getattr(config, "PROMPTS_MODULE", "prompts_life")) args = [p[0] for p in prompts.PROMPTS] - ok = sum(adopt(n, size, holes) for n in args) + ok = sum(adopt(n, size, holes, ai) for n in args) print(f"{ok}/{len(args)} adopted") diff --git a/cutout.py b/cutout.py index bd4673b..5ca4089 100644 --- a/cutout.py +++ b/cutout.py @@ -88,6 +88,28 @@ def cutout(path, holes=False, share=HOLE_SHARE): return Image.fromarray(out.astype(np.uint8), "RGBA") +_SESSION = None + + +def cutout_ai(path, model="isnet-general-use"): + """Wie cutout(), aber fast schwarze Stellen entscheidet ein Freistell-Modell (rembg): + dunkle Haut, dunkler Stoff oder Haare bleiben Figur, eingeschlossene Lücken (zwischen Arm + und Körper, im Lasso) werden Hintergrund. Helle Bildteile behalten die genaue Kante.""" + global _SESSION + from rembg import new_session, remove + if _SESSION is None: + _SESSION = new_session(model) + base = cutout(path) # Kante und helle Teile + arr = np.asarray(base).copy() + rgb = arr[:, :, :3].astype(np.int16) + brightness = rgb.max(axis=2) + mask = np.asarray(remove(Image.open(path).convert("RGB"), session=_SESSION, only_mask=True).convert("L")) + dark = ndimage.binary_dilation(brightness <= BLACK_THRESHOLD + 25, iterations=2) + # dunkle Bereiche: Deckkraft vom Modell (weich), sonst unverändert + arr[:, :, 3] = np.where(dark, mask, arr[:, :, 3]).astype(np.uint8) + return Image.fromarray(arr, "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("--")} diff --git a/generate_mesh.py b/generate_mesh.py index ca22d5a..c9bc9e3 100644 --- a/generate_mesh.py +++ b/generate_mesh.py @@ -7,6 +7,8 @@ Usage: or transparent background. What the sprite generator already produces, in other words. [name] what the GLB is called. Defaults to the image's own stem. + --no-square send the image as it is (otherwise it is padded to a white + square first, see `square`) Hunyuan3D v2 turns one picture into geometry: image -> CLIP vision -> a diffusion pass in a 3D latent -> voxels -> a mesh, saved as a GLB. It produces @@ -78,6 +80,32 @@ def upload_image(path): return answer.get("name", name) +def square(path, margin=0.08): + """Pads the picture to a square, object centred, on white. + + CLIPVisionEncode crops the centre square, so a portrait image lost its top + and bottom (a gladiator's helmet and feet) and the shape came out squashed. + Hunyuan3D was trained on objects filling ~85 % of a white square; with an + alpha channel the transparent part becomes white too. + """ + from PIL import Image + im = Image.open(path) + if im.mode == "RGBA": + bbox = im.getchannel("A").point(lambda a: 255 if a > 40 else 0).getbbox() or (0, 0) + im.size + im = im.crop(bbox) + flat = Image.new("RGB", im.size, (255, 255, 255)) + flat.paste(im, mask=im.getchannel("A")) + im = flat + else: + im = im.convert("RGB") + side = round(max(im.size) / (1 - 2 * margin)) + out = Image.new("RGB", (side, side), (255, 255, 255)) + out.paste(im, ((side - im.width) // 2, (side - im.height) // 2)) + dest = os.path.join(config.OUTPUT_DIR, "_mesh_input_" + os.path.splitext(os.path.basename(path))[0] + ".png") + out.save(dest) + return dest + + def build(image_name, name, seed, octree): path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "workflows", WORKFLOW) with open(path, "r", encoding="utf-8") as handle: @@ -164,7 +192,7 @@ def main(): octree = int(flag.split("=", 1)[1]) os.makedirs(config.OUTPUT_DIR, exist_ok=True) - uploaded = upload_image(source) + uploaded = upload_image(source if "--no-square" in flags else square(source)) print(f"[{name}] uploaded {uploaded}") workflow = build(uploaded, name, random.randint(1, 2 ** 32 - 1), octree) diff --git a/paint_mesh.py b/paint_mesh.py new file mode 100644 index 0000000..c6637b2 --- /dev/null +++ b/paint_mesh.py @@ -0,0 +1,265 @@ +"""Gives a Hunyuan3D shape its colours back, from the pictures it was made from. + + gen paint_mesh [--back=] [--back-mirrored] + [--name=hero] [--faces=30000] [--height=180] + +Hunyuan3D (generate_mesh) returns shape only. This tool: + +* **cleans** the shape: keeps the big parts (the raw mesh has tens of thousands + of crumbs), decimates to `--faces` with quadric simplification (smooth, not + faceted like mesh_prep), and turns all faces outwards; +* **lines up** every view with the shape: the mesh's silhouette is fitted to the + picture's silhouette (bounding box first, then a small search for the best + overlap), so a view does not have to match pixel for pixel; +* **projects** the colours: each vertex takes the colour of the pixel it lands on + in each view where it is visible (z-buffer, so the shield does not paint the + arm behind it), weighted by how squarely it faces that view; whatever no view + sees is filled from its neighbours; +* **writes** `_painted.glb` (vertex colours, smooth normals), + `_mixamo.obj` (same shape without colour, feet on the ground, facing +Z, + `--height` units tall: what mixamo.com wants for auto-rigging) and + `_painted.png` (front, three-quarter, side and back preview). + +Views are orthographic: the front picture looks from +Z (the side Hunyuan puts +the picture's subject on), the back picture from -Z. A back view drawn as a +mirror image (shield on the same side as in the front view - image models do +that) needs `--back-mirrored`. Pictures may be RGBA, or RGB on black (then +cutout_ai finds the figure). Magenta and every other colour pass through as +they are, so a game can still recolour team colours. +""" +import os +import sys + +import numpy as np +import trimesh +from PIL import Image +from scipy import ndimage, sparse + +import _bootstrap # noqa: F401 Projektordner (config.py) vor allen anderen Modulen +import config + + +# ── shape ──────────────────────────────────────────────────────────────── + +def clean(path, faces): + mesh = trimesh.load(path, force="mesh") + parts = mesh.split(only_watertight=False) + big = max(len(p.faces) for p in parts) + keep = [p for p in parts if len(p.faces) >= big * 0.02] + mesh = trimesh.util.concatenate(keep) + print(f"shape: {len(parts)} parts, kept {len(keep)} -> {len(mesh.faces)} faces") + if len(mesh.faces) > faces: + mesh = mesh.simplify_quadric_decimation(face_count=faces) + mesh.merge_vertices() + mesh.remove_unreferenced_vertices() + trimesh.repair.fix_winding(mesh) + trimesh.repair.fix_inversion(mesh, multibody=True) + print(f"shape: {len(mesh.vertices)} vertices, {len(mesh.faces)} faces") + return mesh + + +# ── views ──────────────────────────────────────────────────────────────── + +def load_view(path, mirrored=False): + """RGB (float 0..1) and mask (bool) of a picture; holes in the mask filled.""" + im = Image.open(path) + if im.mode == "RGBA": + rgba = np.asarray(im) + else: + from cutout import cutout_ai + cut = np.asarray(cutout_ai(path)) + rgba = np.dstack([np.asarray(im.convert("RGB")), cut[:, :, 3]]) + if mirrored: + rgba = rgba[:, ::-1] + rgb = rgba[:, :, :3].astype(np.float32) / 255 + mask = ndimage.binary_fill_holes(rgba[:, :, 3] > 100) + return rgb, mask + + +def robust_box(mask): + cols = np.nonzero(mask.sum(0) > 3)[0] + rows = np.nonzero(mask.sum(1) > 3)[0] + return cols.min(), cols.max(), rows.min(), rows.max() + + +def project(points, sign): + """Orthographic view from +Z (sign 1) or -Z (sign -1): image x, image y (up) and depth toward the camera.""" + return points[:, 0] * sign, points[:, 1], points[:, 2] * sign + + +def fit(samples, sign, mask): + """Scale/offset that put the mesh's silhouette on the picture's: (sx, sy, tx, ty), pixel = x*sx+tx, row = ty-y*sy.""" + h, w = mask.shape + x, y, _ = project(samples, sign) + c0, c1, r0, r1 = robust_box(mask) + sx = (c1 - c0) / max(np.ptp(x), 1e-6) + sy = (r1 - r0) / max(np.ptp(y), 1e-6) + p = np.array([sx, sy, c0 - x.min() * sx, r0 + y.max() * sy]) + + small = 4 # search on a quarter-size grid + target = mask[::small, ::small] + sh, sw = target.shape + + def score(q): + u = ((x * q[0] + q[2]) / small).astype(np.int32) + v = ((q[3] - y * q[1]) / small).astype(np.int32) + ok = (u >= 0) & (u < sw) & (v >= 0) & (v < sh) + sil = np.zeros((sh, sw), bool) + sil[v[ok], u[ok]] = True + sil = ndimage.binary_closing(sil, iterations=1) + return (sil & target).sum() / max((sil | target).sum(), 1) + + best = score(p) + for step in (0.04, 0.02, 0.01, 0.005): + improved = True + while improved: + improved = False + for i in range(4): + for d in (-1, 1): + q = p.copy() + q[i] += d * step * (p[i] if i < 2 else (w if i == 2 else h)) + s = score(q) + if s > best + 1e-4: + best, p, improved = s, q, True + print(f" fit: overlap {best:.3f}") + return p + + +def zbuffer(samples, sign, p, shape, scale=2): + """Nearest depth per (scale x smaller) pixel, from dense surface samples.""" + h, w = shape[0] // scale, shape[1] // scale + x, y, z = project(samples, sign) + u = ((x * p[0] + p[2]) / scale).astype(np.int64) + v = ((p[3] - y * p[1]) / scale).astype(np.int64) + ok = (u >= 0) & (u < w) & (v >= 0) & (v < h) + buf = np.full(h * w, -np.inf) + np.maximum.at(buf, v[ok] * w + u[ok], z[ok]) + return buf.reshape(h, w), scale + + +def sample_view(verts, normals, sign, view, samples, tol): + rgb, mask = view + p = fit(samples, sign, mask) + zb, sc = zbuffer(samples, sign, p, mask.shape) + x, y, z = project(verts, sign) + u = x * p[0] + p[2] + v = p[3] - y * p[1] + h, w = mask.shape + ui = np.clip(u.round().astype(int), 0, w - 1) + vi = np.clip(v.round().astype(int), 0, h - 1) + inside = (u >= 0) & (u < w) & (v >= 0) & (v < h) & mask[vi, ui] + # visible: no surface noticeably nearer the camera in the 3x3 around it + near = ndimage.maximum_filter(zb, size=3) + zi = near[np.clip(vi // sc, 0, zb.shape[0] - 1), np.clip(ui // sc, 0, zb.shape[1] - 1)] + visible = z >= zi - tol + facing = np.clip(normals[:, 2] * sign, 0, 1) + weight = np.where(inside & visible, facing ** 1.5, 0.0) + # bilinear colour + u0 = np.clip(np.floor(u).astype(int), 0, w - 2); v0 = np.clip(np.floor(v).astype(int), 0, h - 2) + fu = np.clip(u - u0, 0, 1)[:, None]; fv = np.clip(v - v0, 0, 1)[:, None] + col = (rgb[v0, u0] * (1 - fu) * (1 - fv) + rgb[v0, u0 + 1] * fu * (1 - fv) + + rgb[v0 + 1, u0] * (1 - fu) * fv + rgb[v0 + 1, u0 + 1] * fu * fv) + print(f" {int((weight > 0).sum())} of {len(verts)} vertices coloured") + return col, weight + + +def fill(mesh, colours, known): + """Unknown vertices take the mean of their known neighbours, repeatedly.""" + edges = mesh.edges_unique + n = len(mesh.vertices) + adj = sparse.coo_matrix((np.ones(len(edges) * 2), (np.r_[edges[:, 0], edges[:, 1]], np.r_[edges[:, 1], edges[:, 0]])), + shape=(n, n)).tocsr() + known = known.copy() + for _ in range(400): + if known.all(): + break + k = known.astype(np.float64) + s = adj @ (colours * k[:, None]) + c = adj @ k + grow = (~known) & (c > 0) + if not grow.any(): + break + colours[grow] = s[grow] / c[grow, None] + known |= grow + return colours + + +# ── preview ────────────────────────────────────────────────────────────── + +def preview(mesh, colours, path, size=600): + pts, fi = trimesh.sample.sample_surface(mesh, 900_000) + bary = trimesh.triangles.points_to_barycentric(mesh.triangles[fi], pts) + col = (colours[mesh.faces[fi]] * bary[:, :, None]).sum(1) + nrm = mesh.face_normals[fi] + lo, hi = mesh.bounds + scale = (size - 40) / (hi[1] - lo[1]) + tiles = [] + for yaw in (0, -35, -90, 180): + a = np.radians(yaw) + rot = np.array([[np.cos(a), 0, np.sin(a)], [0, 1, 0], [-np.sin(a), 0, np.cos(a)]]) + p = (pts - (lo + hi) / 2) @ rot.T + n = nrm @ rot.T + light = 0.45 + 0.55 * np.clip(n @ np.array([0.3, 0.5, 0.81]), 0, 1) + u = (p[:, 0] * scale + size / 2).astype(int) + v = (size / 2 - p[:, 1] * scale).astype(int) + ok = (u >= 0) & (u < size) & (v >= 0) & (v < size) + order = np.argsort(p[ok, 2]) + img = np.full((size, size, 3), 40, np.float32) + img[v[ok][order], u[ok][order]] = (col[ok] * light[ok, None])[order] * 255 + tiles.append(img) + Image.fromarray(np.hstack(tiles).clip(0, 255).astype(np.uint8)).save(path) + + +# ── main ───────────────────────────────────────────────────────────────── + +def main(): + args = [a for a in sys.argv[1:] if not a.startswith("--")] + flags = {a.split("=", 1)[0]: (a.split("=", 1)[1] if "=" in a else True) for a in sys.argv[1:] if a.startswith("--")} + if len(args) < 2: + print(__doc__) + return 1 + name = flags.get("--name") or os.path.splitext(os.path.basename(args[0]))[0] + out = config.OUTPUT_DIR + os.makedirs(out, exist_ok=True) + + mesh = clean(args[0], int(flags.get("--faces", 30000))) + verts = np.asarray(mesh.vertices) + normals = np.asarray(mesh.vertex_normals) + samples, _ = trimesh.sample.sample_surface(mesh, 600_000) + tol = np.ptp(verts[:, 1]) * 0.012 + + total = np.zeros((len(verts), 3)); weight = np.zeros(len(verts)) + views = [("front", args[1], 1, False)] + if flags.get("--back"): + views.append(("back", flags["--back"], -1, bool(flags.get("--back-mirrored")))) + for label, path, sign, mirrored in views: + print(f"{label}: {path}") + col, w = sample_view(verts, normals, sign, load_view(path, mirrored), samples, tol) + total += col * w[:, None]; weight += w + known = weight > 0.02 + colours = np.where(known[:, None], total / np.maximum(weight, 1e-9)[:, None], 0.5) + colours = fill(mesh, colours, known) + + # standing on the ground, centred, --height tall (same transform for both files) + lo, hi = mesh.bounds + scale = float(flags.get("--height", 180)) / (hi[1] - lo[1]) + mesh.apply_translation([-(lo[0] + hi[0]) / 2, -lo[1], -(lo[2] + hi[2]) / 2]) + mesh.apply_scale(scale) + + painted = mesh.copy() + painted.visual = trimesh.visual.ColorVisuals(painted, vertex_colors=(np.c_[colours, np.ones(len(colours))] * 255).astype(np.uint8)) + glb = os.path.join(out, f"{name}_painted.glb") + with open(glb, "wb") as f: + f.write(trimesh.exchange.gltf.export_glb(painted, include_normals=True)) + obj = os.path.join(out, f"{name}_mixamo.obj") + plain = trimesh.Trimesh(mesh.vertices, mesh.faces, process=False) + with open(obj, "w", encoding="utf-8") as f: + f.write(trimesh.exchange.obj.export_obj(plain, include_normals=True, include_color=False, include_texture=False)) + png = os.path.join(out, f"{name}_painted.png") + preview(mesh, colours, png) + print(f"-> {glb}\n-> {obj}\n-> {png}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main())