"""Lock original face (and hair color) onto a pose-edited still. CelebAMask-HQ parsing (jonathandinu/face-parsing) finds face parts on the user photo and the AnyPose result. Eyes+nose landmarks drive a similarity warp so the original expression is pasted (mouth is not used for alignment). Dest hair keeps its posed silhouette and is recolored to the original hair. """ from __future__ import annotations import os from typing import Optional import numpy as np from PIL import Image, ImageFilter SKIN, NOSE, EYE_G = 1, 2, 3 L_EYE, R_EYE, L_BROW, R_BROW = 4, 5, 6, 7 L_EAR, R_EAR, MOUTH, U_LIP, L_LIP = 8, 9, 10, 11, 12 HAIR, HAT, NECK = 13, 14, 17 # Do NOT treat raw SKIN as the face: on a sex-pose still, class 1 is the # whole body (torso/genitals). Face = landmarks + skin near those landmarks. FACE_CORE = { NOSE, EYE_G, L_EYE, R_EYE, L_BROW, R_BROW, L_EAR, R_EAR, MOUTH, U_LIP, L_LIP, } FACE_IDS = FACE_CORE LOCK_IDS = FACE_CORE | {HAIR, HAT} PERSON_IDS = set(range(1, 19)) # everything except background # Mouth is intentionally omitted: aligning on it stretches the source expression # to the dest (ref) mouth shape. LANDMARK_ORDER = ("l_eye", "r_eye", "nose", "l_brow", "r_brow") LANDMARK_IDS = { "l_eye": L_EYE, "r_eye": R_EYE, "nose": NOSE, "l_brow": L_BROW, "r_brow": R_BROW, } _PROCESSOR = None _MODEL = None def _load(): global _PROCESSOR, _MODEL if _MODEL is not None: return _PROCESSOR, _MODEL import torch from transformers import AutoModelForSemanticSegmentation try: from transformers import SegformerImageProcessor as _Proc except Exception: from transformers import AutoImageProcessor as _Proc repo = os.getenv("FACE_PARSE_REPO", "jonathandinu/face-parsing") print(f"[face-lock] loading parser {repo}", flush=True) try: _PROCESSOR = _Proc.from_pretrained(repo, use_fast=False) except TypeError: _PROCESSOR = _Proc.from_pretrained(repo) _MODEL = AutoModelForSemanticSegmentation.from_pretrained(repo) _MODEL.eval() _MODEL.to("cpu") return _PROCESSOR, _MODEL def parse_labels(pil: Image.Image) -> np.ndarray: import torch import torch.nn.functional as F processor, model = _load() rgb = pil.convert("RGB") w, h = rgb.size max_side = int(os.getenv("FACE_PARSE_MAX", "512")) scale = min(1.0, max_side / float(max(w, h))) if scale < 1.0: infer_im = rgb.resize( (max(1, int(w * scale)), max(1, int(h * scale))), Image.BILINEAR) else: infer_im = rgb inputs = processor(images=infer_im, return_tensors="pt") want = os.getenv("FACE_PARSE_DEVICE", "cuda" if torch.cuda.is_available() else "cpu") device = torch.device("cuda" if want == "cuda" and torch.cuda.is_available() else "cpu") try: model.to(device) except Exception: device = torch.device("cpu") model.to(device) inputs = {k: v.to(device) for k, v in inputs.items()} with torch.no_grad(): logits = model(**inputs).logits ih, iw = infer_im.size[1], infer_im.size[0] up = F.interpolate(logits, size=(ih, iw), mode="bilinear", align_corners=False) labels_small = up.argmax(dim=1)[0].detach().cpu().numpy().astype(np.uint8) del logits, up, inputs if (iw, ih) != (w, h): import cv2 labels = cv2.resize(labels_small, (w, h), interpolation=cv2.INTER_NEAREST) else: labels = labels_small return labels def _mask_from(labels: np.ndarray, ids: set[int]) -> np.ndarray: m = np.zeros(labels.shape, dtype=np.uint8) for i in ids: m |= (labels == i).astype(np.uint8) return m def _centroid(mask: np.ndarray) -> Optional[tuple[float, float]]: ys, xs = np.nonzero(mask) if xs.size < 8: return None return float(xs.mean()), float(ys.mean()) def _landmarks(labels: np.ndarray, roi: Optional[np.ndarray] = None) -> dict: pts = {} for name, lid in LANDMARK_IDS.items(): m = labels == lid if roi is not None: m = np.logical_and(m, roi) c = _centroid(m.astype(np.uint8)) if c is not None: pts[name] = c return pts def _paired_pts(src_pts: dict, dst_pts: dict): s, d = [], [] for k in LANDMARK_ORDER: if k in src_pts and k in dst_pts: s.append(src_pts[k]) d.append(dst_pts[k]) if len(s) < 3: return None, None return np.asarray(s, np.float32), np.asarray(d, np.float32) def _skin_components(labels: np.ndarray, min_area: int = 400): import cv2 skin = (labels == SKIN).astype(np.uint8) * 255 n, cc, stats, _ = cv2.connectedComponentsWithStats(skin, connectivity=8) out = [] for i in range(1, n): area = int(stats[i, cv2.CC_STAT_AREA]) if area < min_area: continue out.append((area, cc == i)) out.sort(key=lambda x: -x[0]) return out def _expand_roi(comp_bool: np.ndarray, radius: int) -> np.ndarray: import cv2 r = max(9, min(80, int(radius))) dist = cv2.distanceTransform( (comp_bool == 0).astype(np.uint8), cv2.DIST_L2, 5) return dist <= r def _face_core_mask(labels: np.ndarray) -> np.ndarray: """Eyes/nose/mouth/ears plus a little skin around them — never whole-body skin.""" import cv2 core = _mask_from(labels, FACE_CORE) if int(core.sum()) < 20: return core ys, xs = np.nonzero(core) fh = max(8, int(ys.max() - ys.min())) r = max(6, min(40, int(fh * 0.35))) dist = cv2.distanceTransform((core == 0).astype(np.uint8), cv2.DIST_L2, 5) near_skin = (labels == SKIN) & (dist <= r) return (core | near_skin.astype(np.uint8)).astype(np.uint8) def _pick_dest_roi(src_labels, dst_labels, src_bgr, dst_bgr) -> Optional[np.ndarray]: """ROI of the dest *head*, not the largest skin blob (body/genitals).""" h, w = dst_labels.shape core = _face_core_mask(dst_labels) if int(core.sum()) >= 40: ys, xs = np.nonzero(core) cy = float(ys.mean()) / float(h) if cy <= 0.72: return _expand_roi(core > 0, max(12, int(min(h, w) * 0.04))) print("[face-lock] dest face-core too low in frame — skip paste", flush=True) return None # Fallback: a skin blob that has eye/nose landmarks and sits in the upper frame. comps = _skin_components(dst_labels) radius = max(16, int(min(h, w) * 0.04)) best = None best_score = -1.0 for area, comp in comps[:6]: ys, xs = np.nonzero(comp) cy = float(ys.mean()) / float(h) if cy > 0.58: continue roi = _expand_roi(comp, radius) pts = _landmarks(dst_labels, roi) nmark = sum(1 for k in ("l_eye", "r_eye", "nose") if k in pts) if nmark < 1: continue score = nmark * 10.0 + (1.0 - cy) * 3.0 + np.log1p(area / 500.0) if score > best_score: best_score = score best = roi if best is None: print("[face-lock] no dest head landmarks — skip paste", flush=True) return best def _feather(mask_u8: np.ndarray, blur: int) -> np.ndarray: import cv2 blur = max(3, int(blur) | 1) k = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7, 7)) m = cv2.morphologyEx(mask_u8, cv2.MORPH_CLOSE, k) m = cv2.GaussianBlur(m, (blur, blur), 0) return m.astype(np.float32) / 255.0 def _near_head_hair(labels: np.ndarray, face_mask: np.ndarray) -> np.ndarray: """Hair that sits on the head, not a cape / wind / background blob.""" import cv2 hair = (labels == HAIR).astype(np.uint8) if int(face_mask.sum()) < 30 or int(hair.sum()) < 30: return hair ys, xs = np.nonzero(face_mask) fh = max(8, int(ys.max() - ys.min())) dist = cv2.distanceTransform( (face_mask == 0).astype(np.uint8), cv2.DIST_L2, 5) return ((hair > 0) & (dist <= fh * 0.55)).astype(np.uint8) def _convex_u8(mask: np.ndarray) -> np.ndarray: import cv2 m = (mask > 0).astype(np.uint8) cnts, _ = cv2.findContours(m * 255, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) if not cnts: return m hull = np.zeros_like(m) cv2.fillConvexPoly(hull, cv2.convexHull(max(cnts, key=cv2.contourArea)), 1) return hull def _affine_scale(M: np.ndarray) -> float: return float(np.sqrt(M[0, 0] ** 2 + M[0, 1] ** 2)) def _match_hair_color(dst_bgr, dst_hair, src_bgr, src_hair): """Recolor dest hair toward source hair; keep dest hair shape.""" ds = dst_hair > 0 ss = src_hair > 0 if int(ds.sum()) < 80 or int(ss.sum()) < 80: return dst_bgr src_pix = src_bgr[ss].astype(np.float32) dst_pix = dst_bgr[ds].astype(np.float32) src_mean, src_std = src_pix.mean(0), src_pix.std(0) + 1e-6 dst_mean, dst_std = dst_pix.mean(0), dst_pix.std(0) + 1e-6 out = dst_bgr.astype(np.float32) ys, xs = np.nonzero(ds) adj = (out[ys, xs] - dst_mean) * (src_std / dst_std) + src_mean out[ys, xs] = np.clip(adj * 0.9 + out[ys, xs] * 0.1, 0, 255) return out.astype(np.uint8) def _bbox_affine(src_mask: np.ndarray, dst_mask: np.ndarray) -> Optional[np.ndarray]: sy, sx = np.nonzero(src_mask) dy, dx = np.nonzero(dst_mask) if sx.size < 20 or dx.size < 20: return None sbox = [int(sx.min()), int(sy.min()), int(sx.max()), int(sy.max())] dbox = [int(dx.min()), int(dy.min()), int(dx.max()), int(dy.max())] sw, sh = max(1, sbox[2] - sbox[0]), max(1, sbox[3] - sbox[1]) dw, dh = max(1, dbox[2] - dbox[0]), max(1, dbox[3] - dbox[1]) scale = 0.5 * (dw / sw + dh / sh) cx_s, cy_s = 0.5 * (sbox[0] + sbox[2]), 0.5 * (sbox[1] + sbox[3]) cx_d, cy_d = 0.5 * (dbox[0] + dbox[2]), 0.5 * (dbox[1] + dbox[3]) return np.array( [[scale, 0.0, cx_d - scale * cx_s], [0.0, scale, cy_d - scale * cy_s]], dtype=np.float32, ) def lock_face_hair(src: Image.Image, dst: Image.Image) -> Image.Image: """Replace dest face+hair pixels with the source person's (expression kept).""" import cv2 src_rgb = np.asarray(src.convert("RGB")) dst_rgb = np.asarray(dst.convert("RGB")) src_bgr = cv2.cvtColor(src_rgb, cv2.COLOR_RGB2BGR) dst_bgr = cv2.cvtColor(dst_rgb, cv2.COLOR_RGB2BGR) src_lab = parse_labels(src) dst_lab = parse_labels(dst) if src_lab.shape[:2] != src_rgb.shape[:2]: src_lab = cv2.resize( src_lab, (src_rgb.shape[1], src_rgb.shape[0]), interpolation=cv2.INTER_NEAREST) if dst_lab.shape[:2] != dst_rgb.shape[:2]: dst_lab = cv2.resize( dst_lab, (dst_rgb.shape[1], dst_rgb.shape[0]), interpolation=cv2.INTER_NEAREST) src_face = _convex_u8(_face_core_mask(src_lab)) src_hair = _near_head_hair(src_lab, src_face) src_lock = cv2.bitwise_or(src_face, src_hair) if int(src_lock.sum()) < 200: print("[face-lock] no source face/hair — skip", flush=True) return dst.convert("RGB") dest_roi = _pick_dest_roi(src_lab, dst_lab, src_bgr, dst_bgr) if dest_roi is None: return dst.convert("RGB") dst_face = _convex_u8( np.logical_and(_face_core_mask(dst_lab), dest_roi).astype(np.uint8)) if int(dst_face.sum()) < 40: print("[face-lock] dest head mask empty — skip paste", flush=True) return dst.convert("RGB") H0, W0 = dst_rgb.shape[:2] ys0, _ = np.nonzero(dst_face) if ys0.size and (int(ys0.max() - ys0.min()) > int(0.35 * H0)): print("[face-lock] dest still a close-up — skip paste (pose did not transfer)", flush=True) return dst.convert("RGB") dst_hair = _near_head_hair(dst_lab, dst_face) dst_lock = cv2.bitwise_or(dst_face, dst_hair) src_pts, dst_pts = _paired_pts(_landmarks(src_lab), _landmarks(dst_lab, dest_roi)) H, W = dst_rgb.shape[:2] M = None how = "landmarks" if src_pts is not None and dst_pts is not None: M, _ = cv2.estimateAffinePartial2D(src_pts, dst_pts, method=cv2.LMEDS) if M is not None: sc = _affine_scale(M) if sc < 0.4 or sc > 2.4: print(f"[face-lock] landmark scale {sc:.2f} out of range — bbox", flush=True) M = None if M is None: M = _bbox_affine( src_face if int(src_face.sum()) > 80 else src_lock, dst_face if int(dst_face.sum()) > 80 else dst_lock, ) how = "bbox" if M is None: print("[face-lock] could not align — skip", flush=True) return dst.convert("RGB") dy, dx = np.nonzero(dst_face) if dy.size and float(dy.mean()) / float(H) > 0.62: print("[face-lock] dest head too low — skip paste (would cover body)", flush=True) return dst.convert("RGB") warped = cv2.warpAffine( src_bgr, M, (W, H), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REFLECT) face_w = cv2.warpAffine(src_face * 255, M, (W, H), flags=cv2.INTER_LINEAR) if int((face_w > 40).sum()) > 0.16 * W * H: print("[face-lock] warped face too large — skip paste", flush=True) return dst.convert("RGB") guide = dst_face if int(dst_face.sum()) > 80 else dst_lock r = max(12, min(48, int(min(H, W) * 0.025))) dist = cv2.distanceTransform((guide == 0).astype(np.uint8), cv2.DIST_L2, 5) dest_face_dil = (dist <= r).astype(np.uint8) face_w = cv2.bitwise_and(face_w, dest_face_dil * 255) er = max(3, min(9, int(min(H, W) * 0.004) | 1)) face_w = cv2.erode( face_w, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (er, er))) blur_f = max(13, int(min(H, W) * 0.014) | 1) face_a = _feather(face_w, blur_f) # Hair: keep dest silhouette (pose), match color to the original hair. dst_bgr = _match_hair_color(dst_bgr, dst_hair, src_bgr, src_hair) a = face_a[..., None] out = warped.astype(np.float32) * a + dst_bgr.astype(np.float32) * (1.0 - a) out_u8 = np.clip(out, 0, 255).astype(np.uint8) out_rgb = cv2.cvtColor(out_u8, cv2.COLOR_BGR2RGB) print(f"[face-lock] composited face ({how}) + hair color", flush=True) return Image.fromarray(out_rgb) def lock_background(src: Image.Image, dst: Image.Image) -> Image.Image: """Keep the user photo's room: paste the posed person onto image-1 background.""" import cv2 dst_rgb = np.asarray(dst.convert("RGB")) src_rgb = np.asarray(src.convert("RGB").resize((dst_rgb.shape[1], dst_rgb.shape[0]), Image.LANCZOS)) dst_lab = parse_labels(dst) if dst_lab.shape[:2] != dst_rgb.shape[:2]: dst_lab = cv2.resize( dst_lab, (dst_rgb.shape[1], dst_rgb.shape[0]), interpolation=cv2.INTER_NEAREST) person = _mask_from(dst_lab, PERSON_IDS) if int(person.sum()) < 400: print("[bg-lock] no person mask — skip", flush=True) return dst.convert("RGB") dist_out = cv2.distanceTransform((person == 0).astype(np.uint8), cv2.DIST_L2, 5) dist_in = cv2.distanceTransform(person, cv2.DIST_L2, 5) # keep a little of the dest person, feather ~2% of min side feather = max(8, int(min(dst_rgb.shape[0], dst_rgb.shape[1]) * 0.018)) alpha = np.clip((dist_in + (feather - dist_out)) / float(feather), 0.0, 1.0) alpha = np.where(person > 0, np.maximum(alpha, 0.85), alpha) a = alpha[..., None] out = dst_rgb.astype(np.float32) * a + src_rgb.astype(np.float32) * (1.0 - a) print("[bg-lock] composited posed person onto image-1 room", flush=True) return Image.fromarray(np.clip(out, 0, 255).astype(np.uint8)) def try_lock_background(src: Image.Image, dst: Image.Image) -> Image.Image: try: return lock_background(src, dst) except Exception as e: print(f"[bg-lock] skipped: {type(e).__name__}: {e}", flush=True) return dst.convert("RGB") if isinstance(dst, Image.Image) else dst _REMBG = None def _rembg_session(): global _REMBG if _REMBG is None: from rembg import new_session _REMBG = new_session("u2net") print("[matte] rembg u2net ready", flush=True) return _REMBG def fit_contain(im: Image.Image, size: tuple[int, int]) -> Image.Image: """Scale image 1 to fit inside the pose canvas; pad with blurred room.""" tw, th = size im = im.convert("RGB") w, h = im.size scale = min(tw / float(w), th / float(h)) nw, nh = max(1, int(w * scale)), max(1, int(h * scale)) resized = im.resize((nw, nh), Image.LANCZOS) pad = im.resize((tw, th), Image.LANCZOS).filter(ImageFilter.GaussianBlur(28)) pad.paste(resized, ((tw - nw) // 2, (th - nh) // 2)) return pad def fit_cover(im: Image.Image, size: tuple[int, int]) -> Image.Image: """Fill the pose canvas with image 1's room (center crop).""" tw, th = size im = im.convert("RGB") w, h = im.size scale = max(tw / float(w), th / float(h)) nw, nh = max(1, int(w * scale)), max(1, int(h * scale)) resized = im.resize((nw, nh), Image.LANCZOS) left = max(0, (nw - tw) // 2) top = max(0, (nh - th) // 2) return resized.crop((left, top, left + tw, top + th)) def composite_person_on_bg(person: Image.Image, bg: Image.Image) -> Image.Image: """Cut the posed person (rembg) and paste onto the user-photo room.""" from rembg import remove person = person.convert("RGB") bg = bg.convert("RGB") if bg.size != person.size: bg = fit_cover(bg, person.size) rgba = remove(person, session=_rembg_session()) alpha = np.asarray(rgba.split()[-1]).astype(np.float32) / 255.0 if float(alpha.mean()) < 0.02: print("[matte] empty alpha — skip", flush=True) return person # slight erode so leftover ref-room fringe is dropped import cv2 a8 = (alpha * 255).astype(np.uint8) a8 = cv2.erode(a8, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))) a8 = cv2.GaussianBlur(a8, (7, 7), 0) a = (a8.astype(np.float32) / 255.0)[..., None] fg = np.asarray(person).astype(np.float32) bg_n = np.asarray(bg).astype(np.float32) out = fg * a + bg_n * (1.0 - a) print("[matte] posed person on image-1 room", flush=True) return Image.fromarray(np.clip(out, 0, 255).astype(np.uint8)) def try_composite_person_on_bg(person: Image.Image, bg: Image.Image) -> Image.Image: try: return composite_person_on_bg(person, bg) except Exception as e: print(f"[matte] skipped: {type(e).__name__}: {e}", flush=True) return person.convert("RGB") def try_lock_face_hair(src: Image.Image, dst: Image.Image) -> Image.Image: try: return lock_face_hair(src, dst) except Exception as e: print(f"[face-lock] skipped: {type(e).__name__}: {e}", flush=True) return dst.convert("RGB") if isinstance(dst, Image.Image) else dst