Files
ComfyGen/paint_mesh.py
2026-11-08 02:13:01 +01:00

277 lines
12 KiB
Python

"""Gives a Hunyuan3D shape its colours back, from the pictures it was made from.
gen paint_mesh <shape.glb> <front.png> [--back=<back.png>] [--back-mirrored]
[--name=hero] [--faces=30000] [--height=180] [--smooth=12]
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** `<name>_painted.glb` (vertex colours, smooth normals),
`<name>_mixamo.obj` (same shape without colour, feet on the ground, facing +Z,
`--height` units tall: what mixamo.com wants for auto-rigging) and
`<name>_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, smooth=12):
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 smooth:
# surface net leaves a grainy, stair-stepped skin; Taubin smooths it without shrinking
trimesh.smoothing.filter_taubin(mesh, iterations=smooth)
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)), int(flags.get("--smooth", 12)))
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))
# Punkte + Farben schlicht binär (fbx2gim überträgt sie auf die Mixamo-Figur; Assimp liest die
# Farben aus der GLB nicht zuverlässig): int Anzahl, je Punkt 3 float + 4 byte RGBA
pcol = os.path.join(out, f"{name}_painted.pcol")
rgba = (np.c_[np.clip(colours, 0, 1), np.ones(len(colours))] * 255).round().astype(np.uint8)
rec = np.zeros(len(colours), dtype=[("p", "<f4", 3), ("c", "u1", 4)])
rec["p"] = mesh.vertices; rec["c"] = rgba
with open(pcol, "wb") as f:
f.write(np.int32(len(rec)).tobytes()); f.write(rec.tobytes())
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-> {pcol}\n-> {obj}\n-> {png}")
return 0
if __name__ == "__main__":
raise SystemExit(main())