Spaces:
Running
Refuse a head swap when the two heads face different ways, and say so
Browse filesfull_head_swap fits a 2D similarity transform, so it can slide, spin and scale
the source head but cannot turn it. Transplanting a head that is nodded down
onto a body with its chin up lands visibly crooked however well the seam is
blended, and nothing downstream can correct it.
Measured against the Library target (pitch +14, yaw 0): of four test photos,
one differed by 26 degrees of pitch, one by 27 of yaw, one by 30 and 20. Those
are exactly the results that come out misaligned.
The pose delta is now checked before transplanting. Past 25 degrees of pitch or
yaw the head swap is skipped and the clean face swap is used instead; between 15
and 25 it runs but says the alignment may be imperfect. Roll is excluded on
purpose — it is in-plane and the transform already corrects it. A 20-degree case
was checked by eye and still looks right, so the cut sits above it.
The frontend never rendered the warnings array at all, so this explanation — and
the pre-existing "face is very small" notes — would have gone nowhere, and a
skipped head swap would just look like the toggle did nothing. Results now show
them.
14 tests pass; frontend builds.
Files changed (3)
641 unmodified lines64264364464564664725 unmodified lines673674675676677678641 unmodified linesreturn cv2.cvtColor(np.clip(out, 0, 255).astype(np.uint8), cv2.COLOR_LAB2BGR)def full_head_swap(source: np.ndarray, target: np.ndarray,feather: float = 0.012):"""25 unmodified linessf = max(src_faces, key=area)tf = max(tgt_faces, key=area)# Similarity (no shear) keeps the source face SHAPE; aligns it to the# target's eyes/nose/mouth position, scale and rotation.M, _ = cv2.estimateAffinePartial2D(641 unmodified lines64264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968025 unmodified lines706707708709710711712713714715716717718719720721722723724725726641 unmodified linesreturn cv2.cvtColor(np.clip(out, 0, 255).astype(np.uint8), cv2.COLOR_LAB2BGR)#: Out-of-plane mismatch (degrees) past which a transplanted head reads as#: crooked. Warn above the first, refuse above the second.HEAD_POSE_WARN = 15.0HEAD_POSE_MAX = 25.0def head_pose_delta(source: np.ndarray, target: np.ndarray):"""(|d_pitch|, |d_yaw|) between the largest face in each image, or None if thedetector doesn't report pose.Roll is deliberately excluded: it is in-plane, and the similarity transformfull_head_swap fits already corrects it. Pitch and yaw are out-of-plane andit cannot — a head nodded down cannot be turned to face up by translating,rotating and scaling a flat image."""app = _get_insightface()if app is None:return Nonetry:area = lambda f: (f.bbox[2] - f.bbox[0]) * (f.bbox[3] - f.bbox[1])sfs, tfs = app.get(source), app.get(target)if not sfs or not tfs:return Nonesp = getattr(max(sfs, key=area), "pose", None)tp = getattr(max(tfs, key=area), "pose", None)if sp is None or tp is None:return Nonereturn abs(float(sp[0]) - float(tp[0])), abs(float(sp[1]) - float(tp[1]))except Exception:return Nonedef full_head_swap(source: np.ndarray, target: np.ndarray,feather: float = 0.012):"""25 unmodified linessf = max(src_faces, key=area)tf = max(tgt_faces, key=area)# Refuse when the two heads face different ways. The transform below is# a 2D similarity, so it can slide, spin and scale the source head but# cannot turn it: transplanting a head nodded down onto a body with its# chin up lands visibly crooked no matter how well the seam is blended.# Better to fall back to the clean face swap than to paste that.sp, tp = getattr(sf, "pose", None), getattr(tf, "pose", None)if sp is not None and tp is not None:d_pitch = abs(float(sp[0]) - float(tp[0]))d_yaw = abs(float(sp[1]) - float(tp[1]))if max(d_pitch, d_yaw) > HEAD_POSE_MAX:print(f"[head_swap] head angles too different "f"(pitch {d_pitch:.0f}deg, yaw {d_yaw:.0f}deg > {HEAD_POSE_MAX:.0f}) "f"— skipping head swap")return None# Similarity (no shear) keeps the source face SHAPE; aligns it to the# target's eyes/nose/mouth position, scale and rotation.M, _ = cv2.estimateAffinePartial2D(
613 unmodified lines614615616617618619613 unmodified lines</TiltedCard></div>{/* download row */}<div className="flex flex-col sm:flex-row gap-3 justify-center mt-2"><a href={result.download_image || result.result_image}613 unmodified lines614615616617618619620621622623624625626627628629630631632633634635636637638613 unmodified lines</TiltedCard></div>{/* Server-side notes about this result — why the head swap wasskipped, a face too small to swap well, and so on. Withoutthese the pipeline silently falls back and the result justlooks like nothing happened. */}{Array.isArray(result.warnings) && result.warnings.length > 0 && (<div className="max-w-md w-full mx-auto mt-3 flex flex-col gap-2">{result.warnings.map((w, i) => (<p key={i}className="flex items-start gap-2 text-[11px] leading-relaxed font-medium text-amber-800 bg-amber-50 border border-amber-200 rounded-lg px-3 py-2"><svg className="w-3.5 h-3.5 shrink-0 mt-px" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24"><path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg><span>{w}</span></p>))}</div>)}{/* download row */}<div className="flex flex-col sm:flex-row gap-3 justify-center mt-2"><a href={result.download_image || result.result_image}
870 unmodified lines871872873874875876877878879870 unmodified linesbase = targetif opts.get("head_swap", "0") in ("1", "true", "on"):try:hs = full_head_swap(source, target)if hs is not None:base = hsexcept Exception as e:print(f"[swap] head swap error: {e}")870 unmodified lines871872873874875876877878879880881882883884885886887888889890891892893894895870 unmodified linesbase = targetif opts.get("head_swap", "0") in ("1", "true", "on"):try:from core.head_swap import (head_pose_delta, HEAD_POSE_WARN,HEAD_POSE_MAX)_pose = head_pose_delta(source, target)hs = full_head_swap(source, target)if hs is not None:base = hsif _pose and max(_pose) > HEAD_POSE_WARN:warnings.append("Your head angle differs from the location photo "f"(about {max(_pose):.0f}°), so the head swap may not line up ""perfectly. A photo taken from the same angle works best.")elif _pose and max(_pose) > HEAD_POSE_MAX:# full_head_swap refused: the heads face different ways and a# 2D transform cannot turn one to match the other.warnings.append(f"Head swap was skipped — your head angle is about "f"{max(_pose):.0f}° away from the location photo, which would have ""looked crooked. The face swap was used instead. Try a photo ""facing the same way as the person in the location.")except Exception as e:print(f"[swap] head swap error: {e}")