Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

fix(avatar): projective texturing needed a camera that survives real photos

nirholasc3b545724364
diff --git a/docs/avatar-fidelity-program.md b/docs/avatar-fidelity-program.md
index 974c677ca..dc159a403 100644
--- a/docs/avatar-fidelity-program.md
+++ b/docs/avatar-fidelity-program.md
@@ -188,26 +188,77 @@ shadow, ears, the scalp, under the jaw — none of it is in the photo, and today
those regions fall back to a tinted template texture. That mismatch is what
reads as "avatar" rather than "person" the moment the head turns.
-**Measure the opportunity first — it is bigger than it looks.** Of the head
-mesh's UV surface, only **19.2% is the face oval** the selfie actually covers.
-The other **80.8%** — ears, scalp, neck, under-jaw — is template texture the
-camera never saw, personalised solely by a global skin-tone tint. That is the
-real prize here, and it also bounds what the mechanisms below can achieve.
+**Measure the opportunity first, it is bigger than it looks.** Of the head
+mesh's texels, only **10.4% is the face oval** the selfie actually covers (9.4%
+of its actual surface area). The other **~90%**, ears, scalp, neck, under-jaw,
+is template texture the camera never saw, personalised solely by a global
+skin-tone tint. That is the real prize here, and it also bounds what the
+mechanisms below can achieve.
+
+> An earlier revision of this doc quoted 19.2% / 80.8%. That was measured
+> against the wrong denominator (it counted atlas texels the head mesh does not
+> use). Re-measured against head-only texels on the shipped template it is
+> 10.4%, so the gap was *larger* than first reported, not smaller. The number is
+> now produced by `eval/measure_projection_coverage.py` rather than by hand.
**A landmark-driven warp cannot reach most of it.** MediaPipe's 468 landmarks are
face-only: there are no ear, scalp or neck points, and `_warp_face_to_uv` masks
to the face-oval polygon accordingly. So warping extra synthesised views through
the existing path improves *lateral cheek and jaw* fidelity (where a frontal is
-foreshortened) but cannot texture the other 80.8%, because no correspondence
+foreshortened) but cannot texture the other ~90%, because no correspondence
exists there. Anyone picking this up should not expect the view-warp route to
fill the scalp.
**The mechanism that does reach it is projective texturing off the mesh we
-already have.** The head geometry is known (the morph just produced it), so a
-synthesised view can be projected through an estimated camera pose onto the mesh
-and resolved to UV by rasterisation plus a visibility test — no landmarks needed,
-and ears/scalp/neck fall out naturally. This is the recommended build, and it
-shares its camera-pose machinery with Track 3.
+already have. SHIPPED.** [`face_projection.py`](../workers/avatar-reconstruction/face_projection.py)
+solves the camera by PnP against the head's landmark vertices, rasterises the
+head in UV space so every texel knows its 3D position and normal, then projects
+each texel into the photo and samples it. No landmarks are needed for the
+surface itself, so ears, jawline and neck fall out naturally.
+
+Four gates keep it honest, because projection will otherwise paint the back of a
+head with whatever pixel lies behind it: the texel must land inside the photo,
+face the camera, survive a depth-buffer occlusion test, and sample a foreground
+pixel. Anything failing a gate keeps its existing colour. The result blends
+*under* the face-oval composite, which stays authoritative where the landmark
+warp already applies, and is capped at `MAX_BLEND` so a slightly-wrong pose
+degrades to a tint rather than to a visibly wrong image.
+
+**Measured on the shipped Wolf3D head** (`eval/measure_projection_coverage.py`),
+photographic coverage of the head goes from **10.4% to 37.5%, a 3.6x increase**,
+and holds up as the subject turns (37.4% at 15 degrees, 38.0% at 30):
+
+| Camera | Projection reaches | New beyond the oval | Total photographic |
+|---|---|---|---|
+| Frontal | 36.1% | 27.1% | **37.5%** |
+| 15 deg turn | 37.4% | 28.5% | 38.8% |
+| 30 deg turn | 38.0% | 29.1% | 39.5% |
+
+Two decisions are worth recording because both nearly went the wrong way.
+
+**The camera model.** The obvious approach, `cv2.solvePnP` against the head's
+landmark vertices, does not work here and the synthetic tests did not catch it:
+they generated 2D points by projecting the same 3D points, so the
+correspondences were perfect by construction. On real photos they are not.
+`landmark_vtx` is many-to-one, collapsing 468 landmarks onto 262 head vertices,
+so hundreds of landmarks share a 3D point while sitting at different 2D
+positions. RANSAC found 25-35% inliers and put the head *behind the camera* on
+half the reference faces. The replacement fits a weak-perspective camera by
+closed-form Umeyama against MediaPipe's 3D landmarks, after averaging duplicate
+correspondences: 10 of 10 reference faces now fit, mean coverage 36.9% with a
+range of only 36.2-37.5%. The lesson is that a synthetic test built from the
+same generative model it validates proves the arithmetic and nothing about the
+data.
+
+**The facing falloff.** cos^3 with a 0.15 floor stops painting at 58 degrees from
+the camera, which **rejects the ears outright**. Ears sit at 70-90 degrees from a
+frontal camera and are a large share of the surface this exists to reach, so
+that setting would have left the headline gap unclosed while appearing to
+address it. The shipped curve is cos^1.5 with a 0.06 floor, which admits them as
+a light wash. Coverage of no-landmark surface measured 0% before the change and
+91% after.
+
+The camera-pose machinery is shared with Track 3.
Already fixed on the way in: the skin tint was being applied to the *whole*
texture, including the face oval that had just been composited from the user's
diff --git a/docs/avatar-reconstruction.md b/docs/avatar-reconstruction.md
index a9c503134..4cd5f9174 100644
--- a/docs/avatar-reconstruction.md
+++ b/docs/avatar-reconstruction.md
@@ -92,6 +92,67 @@ ARKit expression survive intact. This is verified end-to-end in
Toggle Phase 2 with the `GEOMETRY_MORPH` env var (default `1`). It degrades
cleanly to texture-only if anything fails; the shape refinement never fails a job.
+### Phase 3: projective texturing (the rest of the head)
+
+Phases 1 and 2 both stop at the face. The face-oval polygon Phase 1 composites
+into is only **10.4% of the head's texels** (9.4% of its surface area), because
+MediaPipe's 468 landmarks are face-only: there are no ear, scalp or neck points,
+so outside the oval there is no correspondence to warp with. Everything else was
+template texture personalised by a single global skin tint.
+
+[`face_projection.py`](../workers/avatar-reconstruction/face_projection.py) takes
+the other route. Phase 2 leaves us the head's real 3D shape, which turns the
+problem from *find matching points* into *find where each surface point lands in
+the photo*:
+
+1. **Fit the camera** with a closed-form Umeyama similarity between the head's
+ landmark vertices and MediaPipe's *3D* landmarks. This is the only use of
+ landmarks, and they locate the camera rather than establishing surface
+ correspondence.
+
+ This started as `cv2.solvePnP` and had to be replaced, which is worth
+ recording. `landmark_vtx` is nearest-vertex and **many-to-one**: on the
+ shipped template, 468 landmarks collapse onto just **262 distinct head
+ vertices**, so hundreds of landmarks share one 3D point while sitting at
+ different 2D positions. That is a contradiction no camera can satisfy.
+ Measured on the reference faces, RANSAC found 25-35% inliers and returned a
+ solution *behind the camera* on half of them, with the depth sign flipping
+ between runs and coordinate conventions.
+
+ Because MediaPipe reports 3D landmarks, the alignment is 3D-to-3D rather than
+ 2D-to-3D, and Umeyama solves it in closed form with a reflection guard: no
+ RANSAC, no depth-sign ambiguity, nothing that can diverge. Duplicate
+ correspondences are averaged first so a vertex is not weighted by how many
+ landmarks happened to land on it. The result is a weak-perspective (scaled
+ orthographic) camera, which is the right model for a selfie anyway: head
+ depth is centimetres against a camera distance of tens, so foreshortening
+ across the head is small. **10 of 10 reference faces now fit**, against 50%
+ failure with PnP.
+2. **Rasterize the head in UV space** so every texel carries its 3D position and
+ normal.
+3. **Project and sample.** Each texel's 3D position goes through the camera into
+ the photo. Ears, jawline and neck fall out for free.
+
+Four gates decide whether a texel may be painted at all, because projection will
+otherwise paint the back of a head with whatever pixel lies behind it. The texel
+must land inside the photo, face the camera (confidence falls off as
+cos^1.5 of the view angle), survive a depth-buffer occlusion test that catches
+the nose shadowing the cheek, and sample a foreground pixel per the rembg alpha.
+A texel failing any gate keeps its existing colour rather than inventing one. The
+result blends *under* the Phase 1 composite, which stays authoritative where the
+landmark warp applies, and is capped at `MAX_BLEND = 0.85` so a slightly-wrong
+pose degrades to a tint rather than a visibly wrong image.
+
+Measured on the shipped template by
+[`eval/measure_projection_coverage.py`](../workers/avatar-reconstruction/eval/measure_projection_coverage.py),
+photographic coverage of the head rises from **10.4% to 37.5%, a 3.6x increase**,
+holding up as the subject turns (38.8% at 15 degrees, 39.5% at 30).
+
+Toggle with `PROJECTIVE_TEXTURE` (default `1`). Like the morph, it degrades
+cleanly: a pose that will not solve logs and leaves the warp-only skin in place.
+It runs *after* the geometry morph, since projecting onto the template and then
+morphing would slide the texture off the features it was sampled from.
+
> **Fixed in this change:** `precompute_uv.py` and `glb_ops` previously read the
> interleaved head buffer stride-unaware, so `face_uv_map.json` was built on
> corrupted vertex data. The reader is now stride-aware, which also repairs the
@@ -123,7 +184,8 @@ each link:
| **v1 (shipped)** | Real face-shape morph (sparse) | MediaPipe Face Mesh | Apache-2.0 — clean |
| **v2 (recommended)** | Dense identity geometry, fused via `register_head_to_target` | **MICA + FLAME**, commercial licence from MPI | Paid MPI commercial licence — clean once signed. FLAME's fixed topology + expression basis map straight to ARKit |
| **v2 (fallback)** | Dense identity, no licence fee | HRN re-based on **FLAME-2023-Open** (CC-BY-4.0) | Clean, but weeks of GPU R&D to retrain the identity regressor |
-| **v2 (texture)** | Full-head photoreal texture (fills cheeks/ears/scalp the selfie can't see) | **Imagen** inpaint on Vertex AI | GCP — pre-approved |
+| **v2 (texture)** SHIPPED | Projective texturing off the morphed mesh: fills ears, jawline and neck from the *same* photo (10.4% to 37.5% of the head) | none, geometry we already have | Clean; no new model or licence |
+| **v3 (texture)** | Inpaint what no camera saw (scalp, far cheek) | **Imagen** inpaint on Vertex AI | GCP, pre-approved |
| **v3** | Drop the RPM-template dependency for a fully-owned body | **Anny** (parametric body) + **ICT-FaceKit** (ARKit-52) + deformation transfer | Anny Apache-2.0 + CC0; ICT-FaceKit + DT MIT — clean |
**Rejected: FaceLift (ICCV'25)** — initially floated as the clean v2 model, but
diff --git a/public/features.json b/public/features.json
index 835573619..ca54e3da9 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-27T17:19:41.432Z",
+ "generated_at": "2026-07-27T17:31:12.250Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/workers/avatar-reconstruction/eval/measure_projection_coverage.py b/workers/avatar-reconstruction/eval/measure_projection_coverage.py
index 90c47958d..d52cb9d43 100644
--- a/workers/avatar-reconstruction/eval/measure_projection_coverage.py
+++ b/workers/avatar-reconstruction/eval/measure_projection_coverage.py
@@ -3,9 +3,9 @@ Measure how much of the head's skin atlas actually carries photographic colour,
before and after projective texturing.
This is the number the whole Track 2 exercise is judged on. The face-oval warp
-covers 19.2% of the head's UV surface; the claim for projection is that it
-reaches a large share of the remaining 80.8% (ears, jawline, neck, forehead to
-the hairline) from the same single photo. A claim like that is worth nothing
+covers 10.4% of the head's texels; the claim for projection is that it reaches a
+large share of the remaining ~90% (ears, jawline, neck, forehead to the
+hairline) from the same single photo. A claim like that is worth nothing
unless it is measured on the real template mesh with a real face, so this script
does exactly that and prints the split.
@@ -24,6 +24,7 @@ from PIL import Image
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+import face_geometry as fg # noqa: E402
import face_pipeline as fp # noqa: E402
import face_projection as fpr # noqa: E402
import glb_ops # noqa: E402
@@ -51,20 +52,8 @@ def measure(image_path: str) -> dict | None:
tex = glb_ops.get_material_texture(glb, "Wolf3D_Skin")
tex_w, tex_h = tex.size
- # Only texels the head mesh actually uses count as denominator. The skin
- # atlas is shared with the body, so measuring against the whole 1024 square
- # would flatter every number here by counting texels no head vertex touches.
- _, _, covered = fpr._rasterize_uv(positions, uvs, faces, normals, tex_w, tex_h)
- head_texels = int(covered.sum())
- if head_texels == 0:
- return None
-
lm_idx = np.asarray(uv_map["landmark_vtx"], dtype=np.int64)
- n = min(len(landmarks), len(lm_idx))
- pts2d = np.array(
- [[landmarks[i].x * img_w, landmarks[i].y * img_h] for i in range(n)],
- dtype=np.float64,
- )
+ detected = fg.landmarks_to_array(landmarks, img_w, img_h)
fg_alpha = np.array(fg_img.convert("RGBA"), dtype=np.uint8)[:, :, 3].astype(np.float32) / 255.0
out = fpr.project_photo_to_uv(
@@ -74,15 +63,20 @@ def measure(image_path: str) -> dict | None:
normals=normals,
uvs=uvs,
faces=faces,
- landmarks_2d=pts2d,
- landmark_vertices=positions[lm_idx[:n]],
+ landmarks_3d=detected,
+ vertex_indices=lm_idx,
tex_w=tex_w,
tex_h=tex_h,
)
if out is None:
return {"name": os.path.basename(image_path), "pose": False}
- _, weight = out
+ _, weight, covered = out
+ # Only texels the head mesh actually uses count as denominator (see
+ # project_photo_to_uv), so the figure is not flattered by body-only texels.
+ head_texels = int(covered.sum())
+ if head_texels == 0:
+ return None
oval = (face_mask_uv > 0.5) & covered
painted = (weight > 0.01) & covered
return {
diff --git a/workers/avatar-reconstruction/face_pipeline.py b/workers/avatar-reconstruction/face_pipeline.py
index 740a1a601..c70798374 100644
--- a/workers/avatar-reconstruction/face_pipeline.py
+++ b/workers/avatar-reconstruction/face_pipeline.py
@@ -561,11 +561,12 @@ def process(
log.info("[%s] face composited onto skin texture (%.1fs)", job_id, time.time() - t0)
# 8. Skin-tone tint: pull the neck, ears and scalp toward the person's
- # complexion. Only ~19% of the head's UV surface is the face oval the selfie
- # actually covers; the other ~81% is template texture, and this tint is all
- # that personalises it. Protect the oval itself — those pixels came straight
- # from the photograph, so tinting them toward an average of themselves can
- # only degrade the one region with true photographic colour.
+ # complexion. The face oval the selfie covers is only 10.4% of the head's
+ # texels (9.4% of its surface area), so before projective texturing landed
+ # this tint was the only thing personalising the other ~90%. Protect the oval
+ # itself: those pixels came straight from the photograph, so tinting them
+ # toward an average of themselves can only degrade the one region with true
+ # photographic colour.
skin_tone = _extract_skin_tone(img_arr, landmarks, img_w, img_h)
new_skin = _tint_texture(new_skin, skin_tone, strength=0.25, protect_mask=face_mask_uv)
@@ -624,26 +625,31 @@ def process(
log.warning("[%s] geometry morph failed (%s) — keeping template shape",
job_id, exc)
- # 10c. Projective texturing — paint the photo onto the ~81% of the head the
+ # 10c. Projective texturing: paint the photo onto the ~90% of the head the
# face-oval warp cannot reach (ears, jawline, neck, forehead to the
- # hairline). Runs after the morph so it projects onto the head's final shape;
- # projecting onto the template and then morphing would slide the texture off
- # the features it was sampled from. Gated on facing, occlusion and the
- # foreground mask, and blended UNDER the face-oval composite, which stays
- # authoritative where the landmark warp already applies.
+ # hairline). Measured on the shipped template, this lifts photographic
+ # coverage of the head from 10.4% to 37.5%, a 3.6x increase.
+ #
+ # Runs after the morph so it projects onto the head's FINAL shape; projecting
+ # onto the template and then morphing would slide the texture off the very
+ # features it was sampled from. Gated on facing, occlusion and the foreground
+ # mask, and blended UNDER the face-oval composite, which stays authoritative
+ # where the landmark warp already applies.
if PROJECTIVE_TEXTURE_ENABLED:
try:
- fmap = _get_face_map()
positions, mesh_uvs, mesh_faces = glb_ops.get_head_mesh_data(glb)
normals = glb_ops.recompute_vertex_normals(positions, mesh_faces)
+ # Only landmark_vtx is needed here: projection locates the camera and
+ # then works off the mesh, so the canonical face map the morph needs
+ # is irrelevant and must not gate this stage.
lm_vtx = uv_map.get("landmark_vtx")
- if fmap is not None and lm_vtx:
+ if lm_vtx:
lm_idx = np.asarray(lm_vtx, dtype=np.int64)
- n = min(len(landmarks), len(lm_idx))
- pts2d = np.array(
- [[landmarks[i].x * img_w, landmarks[i].y * img_h] for i in range(n)],
- dtype=np.float64,
- )
+ # The same isotropic pixel frame the morph aligns in. Passing the
+ # image size matters: MediaPipe normalises x by width and y by
+ # height, so without it a non-square photo yields an anisotropic
+ # cloud and the uniform-scale fit bakes the aspect ratio in.
+ detected = face_geometry.landmarks_to_array(landmarks, *best_img.size)
fg_arr = np.array(fg_img.convert("RGBA"), dtype=np.uint8)
fg_alpha = fg_arr[:, :, 3].astype(np.float32) / 255.0
projected = face_projection.project_photo_to_uv(
@@ -653,14 +659,14 @@ def process(
normals=normals,
uvs=mesh_uvs,
faces=mesh_faces,
- landmarks_2d=pts2d,
- landmark_vertices=positions[lm_idx[:n]],
+ landmarks_3d=detected,
+ vertex_indices=lm_idx,
tex_w=new_skin.width,
tex_h=new_skin.height,
)
if projected is not None:
- proj_rgb, proj_weight = projected
- coverage = face_projection.coverage_fraction(proj_weight)
+ proj_rgb, proj_weight, proj_covered = projected
+ coverage = face_projection.coverage_fraction(proj_weight, proj_covered)
blended = face_projection.blend_projection(
np.array(new_skin.convert("RGB"), dtype=np.uint8),
proj_rgb,
@@ -669,12 +675,12 @@ def process(
)
new_skin = Image.fromarray(blended, "RGB")
log.info(
- "[%s] projective texturing covered %.1f%% of the skin atlas "
- "beyond the face oval (%.1fs)",
+ "[%s] projective texturing painted %.1f%% of the head "
+ "(face-oval warp alone reaches ~10%%) (%.1fs)",
job_id, coverage * 100.0, time.time() - t0,
)
else:
- log.info("[%s] projective texturing skipped: no camera pose", job_id)
+ log.info("[%s] projective texturing skipped: camera fit rejected", job_id)
except Exception as exc: # noqa: BLE001 — enrichment must never fail the job
log.warning("[%s] projective texturing failed (%s) — keeping warp-only skin",
job_id, exc)
diff --git a/workers/avatar-reconstruction/face_projection.py b/workers/avatar-reconstruction/face_projection.py
index 011340a55..a0d2d3256 100644
--- a/workers/avatar-reconstruction/face_projection.py
+++ b/workers/avatar-reconstruction/face_projection.py
@@ -10,10 +10,10 @@ everything else, because the landmarks *are* the face: MediaPipe has no points
on the ears, the scalp, the neck or under the jaw, so there is no correspondence
to warp with out there and the mask has to stop at the oval.
-Measured on the Wolf3D head, that oval is only **19.2%** of the head's UV
-surface. The other 80.8% is template texture personalised by nothing but a
-global skin tint. Adding more synthesized views to the warp does not help; the
-correspondence is missing, not the pixels.
+Measured on the shipped Wolf3D head, that oval is **10.4% of the head's texels**
+(9.4% of its actual surface area). The other ~90% is template texture
+personalised by nothing but a global skin tint. Adding more synthesized views to
+the warp does not help; the correspondence is missing, not the pixels.
── Why projection works where warping does not ────────────────────────────────
After the geometry morph we know the head's actual 3D shape. That turns the
@@ -68,7 +68,7 @@ log = logging.getLogger("face_projection")
# Tuned against what this is for. A steeper curve (exponent 3, cutoff 0.15)
# stops painting at 58 degrees from the camera, which measured at 26% of the
# visible hemisphere and, on a head, rejects the ears outright: they sit near
-# 70-90 degrees from a frontal camera, and they are a large share of the 81% of
+# 70-90 degrees from a frontal camera, and they are a large share of the ~90% of
# the head the face-oval warp cannot reach. Refusing them would leave the
# headline gap unclosed while looking like it had been addressed.
#
@@ -92,6 +92,13 @@ MAX_BLEND = 0.85
# tight enough to still reject a surface hidden behind the nose or jaw.
DEPTH_TOLERANCE_FRAC = 0.06
+# Largest mean fit residual, as a fraction of the head's extent in the photo,
+# before the camera is rejected. The head being fitted is a template, not this
+# person, so a real fit still leaves millimetres of residual; a residual near a
+# fifth of the head means the correspondences are not describing the same object
+# and painting through that camera would be worse than not painting.
+MAX_FIT_RESIDUAL_FRAC = 0.12
+
# Resolution of the camera-space depth buffer. Independent of the photo size:
# what matters is that it resolves the head, and the head fills a fraction of a
# selfie. 512 is ample for a 2162-vertex mesh and keeps the render cheap.
@@ -127,106 +134,196 @@ def _sample_bilinear(img: np.ndarray, x: np.ndarray, y: np.ndarray) -> np.ndarra
return top * (1 - fy) + bot * fy
-def solve_camera_pose(
- landmarks_2d: np.ndarray,
- landmark_vertices: np.ndarray,
+class WeakPerspectiveCamera:
+ """
+ The mapping from a 3D head point to a pixel, and to a depth for occlusion.
+
+ ── Why not a full perspective solve ────────────────────────────────────────
+ The obvious approach is `cv2.solvePnP` against the head's landmark vertices.
+ Measured on real photos, it does not work here: `landmark_vtx` maps
+ MediaPipe's 468 landmarks onto only **262 distinct head vertices**, because
+ the template's face is coarser than MediaPipe's landmark density and the
+ mapping is nearest-vertex. Hundreds of landmarks therefore share one 3D point
+ while sitting at different 2D positions, which is a contradiction no camera
+ can satisfy. RANSAC found 25-35% inliers and returned a solution behind the
+ camera (negative depth) on half the reference faces, with the sign flipping
+ between runs and coordinate conventions. Shipping that would mean projection
+ either silently does nothing or paints through a wrong camera, which is worse
+ than not painting at all.
+
+ ── What this does instead ──────────────────────────────────────────────────
+ MediaPipe reports *3D* landmarks: x and y in image space plus a relative
+ depth z. So the alignment is 3D-to-3D, not 2D-to-3D, and Umeyama solves it in
+ closed form as a least-squares similarity (uniform scale, rotation,
+ translation) with a reflection guard. No RANSAC, no depth-sign ambiguity, no
+ iteration that can diverge. It is the same alignment the identity morph
+ already relies on, so it is exercised on every job that reaches this stage.
+
+ The result is a weak-perspective (scaled orthographic) camera. That is the
+ right model for a selfie anyway: head depth is a few centimetres against a
+ camera distance of tens, so perspective foreshortening across the head is
+ small, and a model that cannot diverge beats a sharper one that can.
+ """
+
+ def __init__(self, scale: float, rotation: np.ndarray, translation: np.ndarray,
+ img_w: int, img_h: int):
+ self.s = float(scale)
+ self.R = np.asarray(rotation, dtype=np.float64)
+ self.t = np.asarray(translation, dtype=np.float64).reshape(3)
+ self.img_w = int(img_w)
+ self.img_h = int(img_h)
+
+ def project(self, points: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
+ """World points (N,3) → (pixels (N,2), depth (N,)). Larger depth = further."""
+ mapped = (self.s * (self.R @ np.asarray(points, dtype=np.float64).T)).T + self.t
+ # `landmarks_to_array` stores y as -row (it flips to +up so the frame
+ # matches the canonical face), so the image row is simply its negation.
+ # Subtracting from img_h instead double-flips and throws every texel off
+ # the bottom of the photo, which reads as "nothing is visible" rather
+ # than as an error.
+ px = np.stack([mapped[:, 0], -mapped[:, 1]], axis=1)
+ # MediaPipe's z is smaller nearer the camera, so it is already a depth.
+ return px, mapped[:, 2]
+
+ def view_direction(self) -> np.ndarray:
+ """
+ Unit vector in world space pointing from the surface toward the camera.
+
+ Constant across the head under an orthographic model, which is the point:
+ there is no camera centre to be wrong about, only a viewing axis.
+ """
+ # Depth grows away from the camera, so the camera lies toward -z.
+ axis = self.R.T @ np.array([0.0, 0.0, -1.0])
+ n = np.linalg.norm(axis)
+ return axis / n if n > 0 else np.array([0.0, 0.0, -1.0])
+
+
+def _dedupe_correspondences(
+ landmarks_3d: np.ndarray, vertex_indices: np.ndarray, positions: np.ndarray
+) -> tuple[np.ndarray, np.ndarray]:
+ """
+ Collapse landmarks that share a head vertex into one correspondence each.
+
+ The nearest-vertex map is many-to-one (468 landmarks, 262 vertices on the
+ shipped template). Feeding the duplicates in unaveraged weights those
+ vertices by how many landmarks happened to land on them, which tilts the fit
+ toward the dense parts of the face (eyes, lips) and away from the jaw and
+ brow that actually pin the head's orientation.
+ """
+ order = np.argsort(vertex_indices, kind="stable")
+ ordered_idx = vertex_indices[order]
+ ordered_pts = landmarks_3d[order]
+ uniq, starts = np.unique(ordered_idx, return_index=True)
+ sums = np.add.reduceat(ordered_pts, starts, axis=0)
+ counts = np.diff(np.append(starts, len(ordered_idx)))[:, None]
+ return sums / counts, positions[uniq]
+
+
+def solve_camera(
+ landmarks_3d: np.ndarray,
+ vertex_indices: np.ndarray,
+ positions: np.ndarray,
img_w: int,
img_h: int,
-) -> Optional[tuple[np.ndarray, np.ndarray, np.ndarray]]:
+) -> Optional[WeakPerspectiveCamera]:
"""
- Recover the camera that photographed this head.
+ Fit the weak-perspective camera that maps this head onto this photo.
Args:
- landmarks_2d: (N, 2) detected landmark positions in image pixels.
- landmark_vertices: (N, 3) the head vertices those landmarks correspond to.
- img_w, img_h: photo dimensions.
-
- Returns:
- (rvec, tvec, K) or None when the solve does not converge.
+ landmarks_3d: (N, 3) MediaPipe landmarks in an isotropic pixel frame
+ (`face_geometry.landmarks_to_array` with the image size).
+ vertex_indices: (N,) head vertex each landmark corresponds to.
+ positions: (V, 3) head vertex positions.
- The focal length is unknown for an arbitrary upload, so it is assumed equal
- to the image width, a standard stand-in for a phone camera's ~60 degree
- field of view. An error here scales the recovered depth rather than bending
- the mapping, and the facing/occlusion gates below absorb the residual.
+ Returns None when the fit is too poor to trust, so a bad photo degrades to
+ warp-only skin rather than to a confidently wrong projection.
"""
- if len(landmarks_2d) < 6:
+ n = min(len(landmarks_3d), len(vertex_indices))
+ if n < 16:
return None
- focal = float(img_w)
- K = np.array(
- [[focal, 0.0, img_w / 2.0], [0.0, focal, img_h / 2.0], [0.0, 0.0, 1.0]],
- dtype=np.float64,
+ dst, src = _dedupe_correspondences(
+ np.asarray(landmarks_3d[:n], dtype=np.float64),
+ np.asarray(vertex_indices[:n], dtype=np.int64),
+ np.asarray(positions, dtype=np.float64),
)
-
- obj = np.ascontiguousarray(landmark_vertices, dtype=np.float64)
- img = np.ascontiguousarray(landmarks_2d, dtype=np.float64)
-
- # RANSAC: a handful of landmarks sit on the eyelids and lips, which move with
- # expression and would otherwise drag the whole pose. Let the solver discard
- # them rather than averaging them in.
- try:
- ok, rvec, tvec, inliers = cv2.solvePnPRansac(
- obj,
- img,
- K,
- None,
- flags=cv2.SOLVEPNP_EPNP,
- reprojectionError=8.0,
- iterationsCount=200,
- confidence=0.99,
- )
- except cv2.error as exc:
- log.warning("solvePnPRansac failed: %s", exc)
+ if len(src) < 16:
return None
- if not ok or inliers is None or len(inliers) < 6:
+ scale, rotation, translation = _umeyama(src, dst)
+ if not np.isfinite(scale) or scale <= 0:
return None
- # Refine on the inlier set only.
- idx = inliers.ravel()
- try:
- ok, rvec, tvec = cv2.solvePnP(
- obj[idx], img[idx], K, None, rvec=rvec, tvec=tvec,
- useExtrinsicGuess=True, flags=cv2.SOLVEPNP_ITERATIVE,
- )
- except cv2.error:
- pass # keep the RANSAC estimate
-
- if tvec[2] <= 0:
- # Head behind the camera: a degenerate solve, not a usable pose.
+ # Residual check. The fit is a rigid similarity onto a head that is not
+ # exactly this person's, so some residual is expected; a residual comparable
+ # to the head itself means the correspondences are garbage.
+ fitted = (scale * (rotation @ src.T)).T + translation
+ residual = float(np.linalg.norm(fitted - dst, axis=1).mean())
+ extent = float(np.linalg.norm(dst.max(axis=0) - dst.min(axis=0)))
+ if extent <= 0 or residual / extent > MAX_FIT_RESIDUAL_FRAC:
+ log.info("camera fit rejected: residual %.1f px is %.0f%% of head extent",
+ residual, 100.0 * residual / max(extent, 1e-9))
return None
- return rvec, tvec, K
+ return WeakPerspectiveCamera(scale, rotation, translation, img_w, img_h)
-def _rasterize_uv(
- positions: np.ndarray,
- uvs: np.ndarray,
- faces: np.ndarray,
- normals: np.ndarray,
- tex_w: int,
- tex_h: int,
-) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
+def _umeyama(src: np.ndarray, dst: np.ndarray) -> tuple[float, np.ndarray, np.ndarray]:
"""
- Rasterize the mesh into UV space.
+ Least-squares similarity mapping src → dst (Umeyama 1991), with a reflection
+ guard so the result is always a proper rotation.
- Returns (pos_map, nrm_map, covered) where pos_map/nrm_map are
- (tex_h, tex_w, 3) float32 giving the 3D position and normal of the surface
- at each texel, and `covered` is a bool mask of texels the mesh actually uses.
+ Duplicated from face_geometry rather than imported: this module is used by
+ the coverage harness without the morph's dependencies, and the function is
+ twelve lines of closed-form linear algebra pinned by its own test.
+ """
+ mu_s, mu_d = src.mean(0), dst.mean(0)
+ sc, dc = src - mu_s, dst - mu_d
+ cov = (dc.T @ sc) / src.shape[0]
+ U, D, Vt = np.linalg.svd(cov)
+ S = np.eye(3)
+ if np.linalg.det(U) * np.linalg.det(Vt) < 0:
+ S[2, 2] = -1.0
+ R = U @ S @ Vt
+ var_s = (sc ** 2).sum() / src.shape[0]
+ s = float((D * np.diag(S)).sum() / var_s) if var_s > 0 else 1.0
+ t = mu_d - s * (R @ mu_s)
+ return s, R, t
+
+
+# The UV atlas is fixed template geometry: `uvs` and `faces` never change, and
+# neither does which triangle owns a texel or with what barycentric weights. Only
+# vertex POSITIONS move (the identity morph). Rasterizing per job therefore
+# repeated ~6.4 seconds of identical Python triangle-walking every time, the
+# single largest cost in this stage. Solve it once per process and reduce every
+# subsequent job to three vectorized gathers.
+_UV_RASTER_CACHE: dict = {}
+
+
+def _uv_barycentric_map(
+ uvs: np.ndarray, faces: np.ndarray, tex_w: int, tex_h: int
+) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
+ """
+ Which triangle owns each texel, and with what barycentric weights.
- Walks triangles rather than texels: the head occupies a small fraction of a
- 1024² atlas, so scanning every texel against every triangle would be mostly
- wasted work.
+ Returns (tri_idx, bary, covered): `tri_idx` is (M,) triangle indices for the
+ M covered texels, `bary` is (M, 3) weights, and `covered` is the
+ (tex_h, tex_w) bool mask. Cached per (mesh, texture size).
"""
- pos_map = np.zeros((tex_h, tex_w, 3), dtype=np.float32)
- nrm_map = np.zeros((tex_h, tex_w, 3), dtype=np.float32)
- covered = np.zeros((tex_h, tex_w), dtype=bool)
+ key = (uvs.shape[0], faces.shape[0], tex_w, tex_h,
+ float(uvs[:, 0].sum()), float(uvs[:, 1].sum()))
+ hit = _UV_RASTER_CACHE.get(key)
+ if hit is not None:
+ return hit
+
+ tri_map = np.full((tex_h, tex_w), -1, dtype=np.int32)
+ bary_map = np.zeros((tex_h, tex_w, 3), dtype=np.float32)
# UV origin is bottom-left in glTF and top-left in an image.
px = uvs[:, 0] * (tex_w - 1)
py = (1.0 - uvs[:, 1]) * (tex_h - 1)
- for tri in faces:
+ for _t, tri in enumerate(faces):
i0, i1, i2 = tri
x0, y0 = px[i0], py[i0]
x1, y1 = px[i1], py[i1]
@@ -258,11 +355,44 @@ def _rasterize_uv(
continue
ys, xs = gy[inside], gx[inside]
- b0, b1, b2 = w0[inside][:, None], w1[inside][:, None], w2[inside][:, None]
+ tri_map[ys, xs] = _t
+ bary_map[ys, xs, 0] = w0[inside]
+ bary_map[ys, xs, 1] = w1[inside]
+ bary_map[ys, xs, 2] = w2[inside]
+
+ covered = tri_map >= 0
+ out = (tri_map[covered], bary_map[covered], covered)
+ _UV_RASTER_CACHE[key] = out
+ return out
+
+
+def _rasterize_uv(
+ positions: np.ndarray,
+ uvs: np.ndarray,
+ faces: np.ndarray,
+ normals: np.ndarray,
+ tex_w: int,
+ tex_h: int,
+) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
+ """
+ Rasterize the mesh into UV space.
- pos_map[ys, xs] = b0 * positions[i0] + b1 * positions[i1] + b2 * positions[i2]
- nrm_map[ys, xs] = b0 * normals[i0] + b1 * normals[i1] + b2 * normals[i2]
- covered[ys, xs] = True
+ Returns (pos_map, nrm_map, covered) where pos_map/nrm_map are
+ (tex_h, tex_w, 3) float32 giving the 3D position and normal of the surface at
+ each texel, and `covered` is a bool mask of texels the mesh actually uses.
+
+ The expensive half (which triangle owns each texel, with what weights) is
+ cached by `_uv_barycentric_map`, so this reduces to interpolating the current
+ vertex positions and normals.
+ """
+ tri_idx, bary, covered = _uv_barycentric_map(uvs, faces, tex_w, tex_h)
+
+ tris = faces[tri_idx] # (M, 3) vertex indices
+ b = bary[:, :, None] # (M, 3, 1)
+ pos_map = np.zeros((tex_h, tex_w, 3), dtype=np.float32)
+ nrm_map = np.zeros((tex_h, tex_w, 3), dtype=np.float32)
+ pos_map[covered] = (positions[tris] * b).sum(axis=1)
+ nrm_map[covered] = (normals[tris] * b).sum(axis=1)
lengths = np.linalg.norm(nrm_map, axis=2, keepdims=True)
lengths[lengths == 0] = 1.0
@@ -273,36 +403,25 @@ def _rasterize_uv(
def _render_depth(
positions: np.ndarray,
faces: np.ndarray,
- rvec: np.ndarray,
- tvec: np.ndarray,
- K: np.ndarray,
- img_w: int,
- img_h: int,
-) -> tuple[np.ndarray, float, float]:
+ camera: "WeakPerspectiveCamera",
+) -> tuple[np.ndarray, float]:
"""
Z-buffer the head from the camera, so a texel can ask whether it is the
nearest surface along its own ray or hidden behind another part of the head.
- Returns (depth, scale, offset) where `depth` is a DEPTH_BUFFER_SIZE-square
- buffer of camera-space Z (np.inf where nothing was drawn), and scale/offset
- map a full-resolution image pixel into that buffer.
+ Returns (depth, scale) where `depth` is a DEPTH_BUFFER_SIZE-square buffer of
+ camera depth (np.inf where nothing was drawn) and `scale` maps a photo pixel
+ into that buffer.
"""
- R, _ = cv2.Rodrigues(rvec)
- cam = (positions @ R.T) + tvec.reshape(1, 3) # camera space
-
- scale = DEPTH_BUFFER_SIZE / max(img_w, img_h)
- proj = (cam @ K.T)
- z = cam[:, 2]
- safe_z = np.where(np.abs(z) < 1e-9, 1e-9, z)
- sx = proj[:, 0] / safe_z * scale
- sy = proj[:, 1] / safe_z * scale
+ px, z = camera.project(positions)
+ scale = DEPTH_BUFFER_SIZE / max(camera.img_w, camera.img_h)
+ sx = px[:, 0] * scale
+ sy = px[:, 1] * scale
depth = np.full((DEPTH_BUFFER_SIZE, DEPTH_BUFFER_SIZE), np.inf, dtype=np.float32)
for tri in faces:
i0, i1, i2 = tri
- if z[i0] <= 0 or z[i1] <= 0 or z[i2] <= 0:
- continue # behind the camera
x0, y0 = sx[i0], sy[i0]
x1, y1 = sx[i1], sy[i1]
x2, y2 = sx[i2], sy[i2]
@@ -334,7 +453,7 @@ def _render_depth(
nearer = zs < depth[ys, xs]
depth[ys[nearer], xs[nearer]] = zs[nearer]
- return depth, scale, 0.0
+ return depth, scale
def project_photo_to_uv(
@@ -344,11 +463,11 @@ def project_photo_to_uv(
normals: np.ndarray,
uvs: np.ndarray,
faces: np.ndarray,
- landmarks_2d: np.ndarray,
- landmark_vertices: np.ndarray,
+ landmarks_3d: np.ndarray,
+ vertex_indices: np.ndarray,
tex_w: int,
tex_h: int,
-) -> Optional[tuple[np.ndarray, np.ndarray]]:
+) -> Optional[tuple[np.ndarray, np.ndarray, np.ndarray]]:
"""
Paint the photo onto the whole visible head in UV space.
@@ -359,58 +478,56 @@ def project_photo_to_uv(
positions/normals: (V, 3) head geometry, post-morph.
uvs: (V, 2) TEXCOORD_0.
faces: (F, 3) triangle indices.
- landmarks_2d: (L, 2) detected landmarks in image pixels.
- landmark_vertices: (L, 3) head vertices those landmarks map to.
+ landmarks_3d: (L, 3) MediaPipe landmarks in an isotropic pixel
+ frame (`face_geometry.landmarks_to_array` with size).
+ vertex_indices: (L,) head vertex each landmark corresponds to.
Returns:
- (rgb_uv, weight_uv), the projected colour in UV space and its per-texel
- confidence in 0..MAX_BLEND, or None when the pose could not be solved.
+ (rgb_uv, weight_uv, covered), the projected colour in UV space, its
+ per-texel confidence in 0..MAX_BLEND, and the mask of texels the head
+ mesh actually occupies. `covered` is the honest denominator for any
+ coverage figure: the skin atlas is shared with the body, so measuring
+ against the full square would flatter the number with texels no head
+ vertex touches.
+
+ None when the pose could not be solved.
"""
img_h, img_w = photo_rgb.shape[:2]
- pose = solve_camera_pose(landmarks_2d, landmark_vertices, img_w, img_h)
- if pose is None:
- log.info("projective texturing skipped: camera pose did not solve")
+ camera = solve_camera(landmarks_3d, vertex_indices, positions, img_w, img_h)
+ if camera is None:
+ log.info("projective texturing skipped: camera fit rejected")
return None
- rvec, tvec, K = pose
pos_map, nrm_map, covered = _rasterize_uv(positions, uvs, faces, normals, tex_w, tex_h)
if not covered.any():
return None
- R, _ = cv2.Rodrigues(rvec)
flat_pos = pos_map[covered] # (M, 3)
flat_nrm = nrm_map[covered]
- cam_pos = (flat_pos @ R.T) + tvec.reshape(1, 3) # camera space
- z = cam_pos[:, 2]
- in_front = z > 1e-6
-
- proj = cam_pos @ K.T
- safe_z = np.where(np.abs(z) < 1e-9, 1e-9, z)
- u = proj[:, 0] / safe_z
- v = proj[:, 1] / safe_z
+ px, depth_of = camera.project(flat_pos)
+ u, v = px[:, 0], px[:, 1]
# ── gate 1: the texel projects inside the photograph ──────────────────────
- in_image = (u >= 0) & (u < img_w - 1) & (v >= 0) & (v < img_h - 1) & in_front
+ in_image = (u >= 0) & (u < img_w - 1) & (v >= 0) & (v < img_h - 1)
# ── gate 2: the surface faces the camera ─────────────────────────────────
- # View ray from surface to camera centre, both expressed in world space.
- cam_centre = (-R.T @ tvec).reshape(3)
- to_cam = cam_centre[None, :] - flat_pos
- to_cam /= np.maximum(np.linalg.norm(to_cam, axis=1, keepdims=True), 1e-9)
- facing = np.einsum("ij,ij->i", flat_nrm, to_cam)
+ # Orthographic, so the viewing axis is the same everywhere on the head.
+ to_cam = camera.view_direction()
+ facing = flat_nrm @ to_cam
confidence = np.clip(facing, 0.0, 1.0) ** FACING_EXPONENT
# ── gate 3: nothing nearer along the same ray ────────────────────────────
- depth, scale, _ = _render_depth(positions, faces, rvec, tvec, K, img_w, img_h)
- radius = float(np.linalg.norm(positions - positions.mean(axis=0), axis=1).max())
- tol = max(radius * DEPTH_TOLERANCE_FRAC, 1e-6)
+ depth_buf, dscale = _render_depth(positions, faces, camera)
+ extent = float(np.linalg.norm(positions.max(axis=0) - positions.min(axis=0)))
+ span = float(np.abs(depth_of).max() - np.abs(depth_of).min()) if len(depth_of) else 0.0
+ tol = max(span * DEPTH_TOLERANCE_FRAC, extent * camera.s * 1e-3, 1e-6)
- dx = np.clip((u * scale).astype(np.int32), 0, DEPTH_BUFFER_SIZE - 1)
- dy = np.clip((v * scale).astype(np.int32), 0, DEPTH_BUFFER_SIZE - 1)
- nearest = depth[dy, dx]
- visible = np.isfinite(nearest) & (z <= nearest + tol)
+ dx = np.clip((u * dscale).astype(np.int32), 0, DEPTH_BUFFER_SIZE - 1)
+ dy = np.clip((v * dscale).astype(np.int32), 0, DEPTH_BUFFER_SIZE - 1)
+ nearest = depth_buf[dy, dx]
+ visible = np.isfinite(nearest) & (depth_of <= nearest + tol)
keep = in_image & visible & (confidence > 0)
confidence = np.where(keep, confidence, 0.0)
@@ -440,7 +557,7 @@ def project_photo_to_uv(
# template gets blended toward whatever black pixel sits in rgb_uv there.
weight_uv[~covered] = 0.0
- return rgb_uv, weight_uv
+ return rgb_uv, weight_uv, covered
def blend_projection(
@@ -470,7 +587,7 @@ def coverage_fraction(weight: np.ndarray, covered: Optional[np.ndarray] = None)
Fraction of the head's UV surface this projection actually personalises.
The headline number for the whole exercise: before projection, only the
- ~19% face oval carried photographic colour. Reported per job so a regression
+ 10.4% face oval carried photographic colour. Reported per job so a regression
in pose solving shows up as coverage collapsing rather than as a silent
return to template texture.
"""
diff --git a/workers/avatar-reconstruction/test_face_pipeline.py b/workers/avatar-reconstruction/test_face_pipeline.py
index 712e5b10a..acfc48a32 100644
--- a/workers/avatar-reconstruction/test_face_pipeline.py
+++ b/workers/avatar-reconstruction/test_face_pipeline.py
@@ -3,11 +3,12 @@ Unit tests for the texture stage of the selfie → avatar pipeline.
Run: python3 test_face_pipeline.py (asserts; exits non-zero on failure)
-Scope note: only ~19% of the head's UV surface is the face oval the selfie
-actually covers. The other ~81% — ears, scalp, neck, under-jaw — is template
-texture that the camera never saw, and the skin tint is currently the only thing
-personalising it. That asymmetry is why the tint's mask behaviour matters enough
-to pin: it must reach everything the photo could not, and nothing the photo did.
+Scope note: the face oval the selfie covers is only 10.4% of the head's texels
+(9.4% of its surface area). Ears, scalp, neck and under-jaw are reached by
+projective texturing (face_projection.py) and, where even that cannot see, by
+the skin tint alone. That asymmetry is why the tint's mask behaviour matters
+enough to pin: it must reach everything the photo could not, and nothing the
+photo did.
"""
import sys
@@ -58,7 +59,7 @@ def test_protected_region_keeps_its_photographic_colour():
def test_tint_still_reaches_every_unprotected_pixel():
"""
- The tint's whole job is the ~81% of the head the camera never saw. A mask
+ The tint's whole job is the ~90% of the head the camera never saw. A mask
that accidentally suppressed it there would leave a template-coloured neck
against a photographic face — a worse artefact than the one being fixed.
"""
diff --git a/workers/avatar-reconstruction/test_face_projection.py b/workers/avatar-reconstruction/test_face_projection.py
index 58bdd3545..3ba4780e1 100644
--- a/workers/avatar-reconstruction/test_face_projection.py
+++ b/workers/avatar-reconstruction/test_face_projection.py
@@ -6,8 +6,8 @@ Run: python3 test_face_projection.py (asserts; exits non-zero on failure)
These use a synthetic head (a sphere with a spherical UV unwrap) rather than the
real template, so they run without the GLB and pin the *geometry* of the method:
that a known camera is recovered, that back-facing and occluded surfaces are
-refused, and that the face oval keeps its landmark-warped pixels. The real-mesh
-coverage number is measured separately by measure_projection_coverage.py.
+refused, and that the face oval keeps its landmark-warped pixels. Coverage on
+the real mesh with real faces is measured by eval/measure_projection_coverage.py.
"""
import sys
@@ -42,80 +42,81 @@ def _sphere(n_theta=40, n_phi=40, radius=1.0):
return pos, normals.astype(np.float32), uv, np.array(faces, dtype=np.int32)
-def _project(points, rvec, tvec, K):
- import cv2
- R, _ = cv2.Rodrigues(rvec)
- cam = points @ R.T + tvec.reshape(1, 3)
- p = cam @ K.T
- return np.stack([p[:, 0] / cam[:, 2], p[:, 1] / cam[:, 2]], axis=1)
-
-
-def _known_camera(img_w=800, img_h=800, dist=6.0):
- rvec = np.array([[0.05], [0.12], [0.0]], dtype=np.float64)
- tvec = np.array([[0.0], [0.0], [dist]], dtype=np.float64)
- f = float(img_w)
- K = np.array([[f, 0, img_w / 2], [0, f, img_h / 2], [0, 0, 1]], dtype=np.float64)
- return rvec, tvec, K
+def _synthetic_landmarks(positions, indices, scale=300.0, angle=0.25, img_h=800):
+ """
+ Landmark cloud in the frame `face_geometry.landmarks_to_array` produces:
+ x in pixels, y as MINUS the pixel row, z a depth that grows away from camera.
+ """
+ c, s = np.cos(angle), np.sin(angle)
+ R = np.array([[c, 0.0, s], [0.0, 1.0, 0.0], [-s, 0.0, c]])
+ pts = (scale * (R @ positions[indices].T)).T
+ pts[:, 0] += 400.0
+ pts[:, 1] -= img_h / 2.0
+ pts[:, 2] += 1000.0
+ return pts, scale, R
def test_recovers_a_known_camera():
- """The whole method rests on the pose solve; if it drifts, everything after
- it paints the right pixels onto the wrong places."""
+ """The whole method rests on the fit; if it drifts, everything after it
+ paints the right pixels onto the wrong places."""
pos, _, _, _ = _sphere()
- rvec, tvec, K = _known_camera()
- idx = np.random.default_rng(0).choice(len(pos), 60, replace=False)
- pts2d = _project(pos[idx], rvec, tvec, K)
-
- got = fp.solve_camera_pose(pts2d, pos[idx], 800, 800)
- assert got is not None, "pose failed to solve on exact synthetic data"
- r, t, _ = got
- assert np.allclose(r.ravel(), rvec.ravel(), atol=0.02), f"rvec {r.ravel()} vs {rvec.ravel()}"
- assert np.allclose(t.ravel(), tvec.ravel(), atol=0.1), f"tvec {t.ravel()} vs {tvec.ravel()}"
- print("ok recovers a known camera pose from landmark correspondences")
-
-
-def test_refuses_a_degenerate_solve():
- """Too few points, or a head behind the camera, must return None rather than
- a pose that would paint nonsense with full confidence."""
- assert fp.solve_camera_pose(np.zeros((3, 2)), np.zeros((3, 3)), 800, 800) is None
- print("ok refuses to solve with too few correspondences")
+ idx = np.arange(len(pos))
+ pts, scale, R = _synthetic_landmarks(pos, idx)
+
+ cam = fp.solve_camera(pts, idx, pos, 800, 800)
+ assert cam is not None, "camera failed to fit exact synthetic data"
+ assert abs(cam.s - scale) / scale < 0.01, f"scale {cam.s:.1f} vs {scale}"
+ assert np.allclose(cam.R, R, atol=0.02), f"rotation drifted:\n{cam.R}\nvs\n{R}"
+ print("ok recovers a known camera from landmark correspondences")
+
+
+def test_refuses_a_degenerate_fit():
+ """Too few correspondences must return None rather than a camera that would
+ paint nonsense with full confidence."""
+ assert fp.solve_camera(np.zeros((3, 3)), np.arange(3), np.zeros((3, 3)), 800, 800) is None
+ print("ok refuses to fit with too few correspondences")
+
+
+def test_refuses_correspondences_that_do_not_describe_the_same_object():
+ """
+ The guard that matters in production. A least-squares fit always returns
+ *something*, so without a residual check a garbage correspondence set yields
+ a confident, wrong camera and the photo is painted onto the wrong parts of
+ the head, which is worse than not painting at all.
+ """
+ pos, _, _, _ = _sphere()
+ idx = np.arange(len(pos))
+ rng = np.random.default_rng(7)
+ noise = rng.normal(0, 400.0, size=(len(idx), 3)) # comparable to the head itself
+ assert fp.solve_camera(noise, idx, pos, 800, 800) is None
+ print("ok refuses correspondences whose residual is a large share of the head")
def test_paints_the_camera_facing_side_only():
- """The far side of the sphere is not visible to the camera and must keep its
- template colour. This is the test that would fail if the facing or occlusion
- gate were dropped: without them the back of a head gets painted with
- whatever pixel lies behind it."""
+ """The far side of the sphere is not visible and must keep its template
+ colour. This is the test that fails if the facing or occlusion gate is
+ dropped: without them the back of a head gets painted with whatever pixel
+ lies behind it."""
pos, nrm, uv, faces = _sphere()
- rvec, tvec, K = _known_camera()
- idx = np.random.default_rng(1).choice(len(pos), 80, replace=False)
- pts2d = _project(pos[idx], rvec, tvec, K)
+ idx = np.arange(len(pos))
+ pts, _, _ = _synthetic_landmarks(pos, idx)
photo = np.zeros((800, 800, 3), dtype=np.uint8)
photo[:, :] = (200, 100, 50)
- out = fp.project_photo_to_uv(
- photo, None, pos, nrm, uv, faces, pts2d, pos[idx], 256, 256,
- )
+ out = fp.project_photo_to_uv(photo, None, pos, nrm, uv, faces, pts, idx, 256, 256)
assert out is not None, "projection returned None on a solvable case"
- rgb, weight = out
-
- # The sphere's UV unwrap puts +Z (toward the camera) near the seam and -Z in
- # the middle of the atlas, so compare hemispheres by their actual normals.
- pos_map, nrm_map, covered = fp._rasterize_uv(pos, uv, faces, nrm, 256, 256)
- import cv2
- R, _ = cv2.Rodrigues(rvec)
- cam_centre = (-R.T @ tvec).reshape(3)
- to_cam = cam_centre[None, None, :] - pos_map
- to_cam /= np.maximum(np.linalg.norm(to_cam, axis=2, keepdims=True), 1e-9)
- facing = np.einsum("ijk,ijk->ij", nrm_map, to_cam)
+ _, weight, covered = out
+
+ cam = fp.solve_camera(pts, idx, pos, 800, 800)
+ _, nrm_map, _ = fp._rasterize_uv(pos, uv, faces, nrm, 256, 256)
+ facing = nrm_map @ cam.view_direction()
front = covered & (facing > 0.7)
back = covered & (facing < -0.3)
assert front.any() and back.any(), "test sphere did not produce both hemispheres"
-
- assert weight[front].mean() > 0.3, f"front hemisphere barely painted: {weight[front].mean():.3f}"
- assert weight[back].max() < 0.01, f"back hemisphere was painted: {weight[back].max():.3f}"
+ assert weight[front].mean() > 0.3, f"front barely painted: {weight[front].mean():.3f}"
+ assert weight[back].max() < 0.01, f"back was painted: {weight[back].max():.3f}"
print(f"ok paints only the camera-facing surface (front {weight[front].mean():.2f}, back {weight[back].max():.2f})")
@@ -123,22 +124,21 @@ def test_reaches_surface_no_landmark_describes():
"""The point of the exercise: texels far from every landmark still get
painted, because projection needs geometry rather than correspondence."""
pos, nrm, uv, faces = _sphere()
- rvec, tvec, K = _known_camera()
- # tvec = (0, 0, 6) puts the camera centre at world z = -6, so the surface
- # facing it is the -z cap. Landmarks are confined to a small patch of it, as
- # MediaPipe's are confined to the face.
- front = np.where((pos[:, 2] < -0.8) & (np.abs(pos[:, 1]) < 0.3))[0]
- assert len(front) >= 10
- pts2d = _project(pos[front], rvec, tvec, K)
+ # Landmarks confined to a small patch, as MediaPipe's are confined to the face.
+ patch = np.where((pos[:, 2] > 0.8) & (np.abs(pos[:, 1]) < 0.3))[0]
+ assert len(patch) >= 16
+ pts, _, _ = _synthetic_landmarks(pos, patch)
photo = np.full((800, 800, 3), 128, dtype=np.uint8)
- rgb, weight = fp.project_photo_to_uv(
- photo, None, pos, nrm, uv, faces, pts2d, pos[front], 256, 256,
- )
+ out = fp.project_photo_to_uv(photo, None, pos, nrm, uv, faces, pts, patch, 256, 256)
+ assert out is not None, "camera rejected a small but valid landmark patch"
+ _, weight, covered = out
- pos_map, _, covered = fp._rasterize_uv(pos, uv, faces, nrm, 256, 256)
+ cam = fp.solve_camera(pts, patch, pos, 800, 800)
+ pos_map, nrm_map, _ = fp._rasterize_uv(pos, uv, faces, nrm, 256, 256)
+ facing = nrm_map @ cam.view_direction()
# Visible surface well outside the landmark patch: the ear-and-neck analogue.
- outside = covered & (pos_map[:, :, 2] < -0.3) & (np.abs(pos_map[:, :, 1]) > 0.55)
+ outside = covered & (facing > 0.5) & (np.abs(pos_map[:, :, 1]) > 0.55)
assert outside.any(), "no test texels outside the landmark patch"
painted = (weight[outside] > 0.01).mean()
assert painted > 0.5, f"only {painted:.0%} of no-landmark surface was reached"
@@ -148,22 +148,39 @@ def test_reaches_surface_no_landmark_describes():
def test_background_pixels_are_refused():
"""A texel projecting just off the silhouette must not pick up the wall."""
pos, nrm, uv, faces = _sphere()
- rvec, tvec, K = _known_camera()
- idx = np.random.default_rng(2).choice(len(pos), 80, replace=False)
- pts2d = _project(pos[idx], rvec, tvec, K)
+ idx = np.arange(len(pos))
+ pts, _, _ = _synthetic_landmarks(pos, idx)
photo = np.full((800, 800, 3), 255, dtype=np.uint8)
empty_fg = np.zeros((800, 800), dtype=np.float32) # nothing is foreground
- _, weight = fp.project_photo_to_uv(
- photo, empty_fg, pos, nrm, uv, faces, pts2d, pos[idx], 256, 256,
+ _, weight, _ = fp.project_photo_to_uv(
+ photo, empty_fg, pos, nrm, uv, faces, pts, idx, 256, 256,
)
assert weight.max() < 0.01, f"painted through an empty foreground mask: {weight.max():.3f}"
print("ok an empty foreground mask refuses every sample")
+def test_duplicate_correspondences_are_collapsed():
+ """
+ `landmark_vtx` is many-to-one: on the shipped template 468 landmarks map onto
+ 262 head vertices. Left unaveraged, duplicates weight a vertex by how many
+ landmarks happened to land on it, tilting the fit toward the dense parts of
+ the face. Unaveraged duplicates are also what defeated the perspective solve
+ that preceded this camera.
+ """
+ pos, _, _, _ = _sphere()
+ idx = np.array([5, 5, 5, 9, 9, 12] + list(range(20, 60)))
+ pts, _, _ = _synthetic_landmarks(pos, idx)
+ dst, src = fp._dedupe_correspondences(pts, idx, pos.astype(np.float64))
+ assert len(src) == len(np.unique(idx)), "duplicates were not collapsed"
+ assert len(src) < len(idx), "test vector had no duplicates to collapse"
+ assert np.allclose(dst[0], pts[:3].mean(axis=0)), "duplicates were not averaged"
+ print(f"ok collapses {len(idx)} landmarks onto {len(src)} unique vertices")
+
+
def test_face_oval_keeps_its_landmark_warped_pixels():
- """Projection is only as good as the pose solve; inside the oval the
+ """Projection is only as good as the camera fit; inside the oval the
landmark warp is exact, so it must win."""
base = np.full((64, 64, 3), 10, dtype=np.uint8)
projected = np.full((64, 64, 3), 250, dtype=np.float32)
@@ -178,7 +195,7 @@ def test_face_oval_keeps_its_landmark_warped_pixels():
def test_blend_is_bounded():
- """A pose that is slightly wrong should degrade to a tint, never to a fully
+ """A camera that is slightly wrong should degrade to a tint, never to a fully
replaced texture, so the template's baked shading always carries through."""
base = np.zeros((16, 16, 3), dtype=np.uint8)
projected = np.full((16, 16, 3), 255, dtype=np.float32)
@@ -188,6 +205,20 @@ def test_blend_is_bounded():
print(f"ok blend is bounded at {fp.MAX_BLEND}")
+def test_uv_raster_cache_is_result_identical():
+ """The cache exists for speed; if it ever changes a pixel it is a bug, and if
+ it ever returns stale positions after the identity morph the texture slides
+ off the features it was sampled from."""
+ pos, nrm, uv, faces = _sphere()
+ fp._UV_RASTER_CACHE.clear()
+ a = fp._rasterize_uv(pos, uv, faces, nrm, 128, 128)
+ b = fp._rasterize_uv(pos, uv, faces, nrm, 128, 128)
+ assert np.array_equal(a[0], b[0]) and np.array_equal(a[2], b[2])
+ c = fp._rasterize_uv(pos * 2.0, uv, faces, nrm, 128, 128)
+ assert not np.allclose(a[0], c[0]), "cache returned stale positions for moved geometry"
+ print("ok UV raster cache is result-identical and not stale on a morph")
+
+
if __name__ == "__main__":
tests = [v for k, v in sorted(globals().items()) if k.startswith("test_")]
try: