Algorithmresearch
Example-based facial rigging
Also called example-based blendshape generation.
Generate a personalized blendshape rig from a few example expressions of an actor by optimizing the targets with a generic rig as prior.
- Solves
- Shape deformation
- Time
- O(I (T n (n + m) + n^3 + m n^2 K) + V^3 + n V^2) total
- Space
- O(T (n + m) + V^2 + n V) extra
- Where
- I = the number of alternations; K = the number of coordinate descent sweeps per weight step; T = the number of triangles; V = the number of vertices; m = the number of examples; n = the number of targets
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
Example-based facial rigging builds a blendshape rig for one actor from a generic rig and a few scans of the actor's face. A good face rig has dozens of targets, such as "jaw open" or "left smile", and modeling them by hand for each actor takes days. A scan of the actor making an expression is easy to get, but a scan is a mix of many targets at once, not a single target. Li, Weise and Pauly (2010) start from the deformation transfer of a generic rig onto the actor's neutral face, and then change the targets so that suitable blends of them reproduce the scans, while each target stays close to its generic counterpart.
In plain words
A generic face rig knows what "open the jaw" or "smile" does to a face, but not how this actor does it. You have a few scans of the actor making faces, and a rough guess of how much of each target is in each scan. First, copy each generic target onto the actor with deformation transfer. Then improve two things in turn. Change the targets so that the blends with the current weights look like the scans, but do not let a target drift far from what the generic one does. Then change the weights so that the blends of the new targets fit the scans better, with every weight between 0 and 1. Repeat a few times. The work is done on how each triangle stretches and turns, and at the end one linear solve turns that back into vertex positions.
The problem
The input is:
- a generic rig with the neutral face and the targets ;
- the neutral face of the actor;
- example expressions of the actor;
- a first guess of the blend weights of each example.
All meshes share one triangulation, which the method needs, for example after a template is fitted to each scan. The output is the actor targets and the weights of the examples.
For a triangle , the deformation gradient of a mesh relative to is the matrix that maps the edges of the triangle in to its edges in . Let be the unknowns, the examples, and the prior, where is the gradient of the generic target relative to . The method minimizes
subject to . The first term is the fit to the examples, and the second is the prior from the generic rig. With , each target changes its triangles like the generic target, which is deformation transfer for meshes with one triangulation.
The code in impl/python works on 2D triangle meshes and uses this energy only.
The paper works on 3D face meshes, and its energy has more detail than this one, for example in how the prior is weighted; this page keeps the structure of the method.
The algorithm
EXAMPLE-BASED-RIG(A₀ … Aₙ, B₀, S₁ … Sₘ, α⁰, β)- 1
H_i ← gradients of A_i relative to A₀, minus I; D ← H - 2
R_j ← gradients of S_j relative to B₀, minus I; α ← α⁰ - 3
repeat a fixed number of times: - 4
D ← argmin_D E(D, α) (one linear solve) - 5
α_j ← argmin over [0, 1]ⁿ of E(D, α), for each j - 6
record E(D, α) - 7
B_i ← the mesh whose gradients fit I + D_i in least squares, with one vertex fixed - 8
return B₁ … Bₙ and α
Line L4 separates into one small problem per entry of the 2 by 2 (or 3 by 3) matrices. For an entry of triangle , the vector solves
where is the by matrix of the weights. The matrix is the same for every entry, so the code solves it once with all entries as right hand sides.
Line L5 is a least squares problem with bounds, one per example, with the Gram matrix of the targets. The code solves it by cyclic coordinate descent: it sets each weight to its exact minimizer, clipped to , until no weight moves.
Line L7 is the Poisson step of deformation transfer: the vertex positions of minimize , which is a sparse Poisson type system whose matrix depends only on .
Example
The tests use a strip of six vertices and four triangles. The generic rig has a target "open", which stretches the top row up by 50 percent, and a target "smile", which shears the right side. The actor has a different neutral face and true targets that differ from the transferred generic ones. There are three examples, made with the true weights , and , and the first guesses are , and .
With and 30 alternations, falls from at the start to after the first step and to at the end. The largest vertex error of the targets is:
| target | deformation transfer | example-based rig |
|---|---|---|
| open | 0.286 | 0.026 |
| smile | 0.347 | 0.032 |
The weights become , and , close to the true ones.
Two check values. For one target, one example and one entry, line L4 gives ; with and , this is . For one target, line L5 gives the weight ; with , the entries , and give the weights 1, 0.3 and 0.
Correctness
The proofs are in proofs/correctness.md.
- Line L4 is exact. For , is positive definite, so the step is the unique minimizer of in for the fixed weights.
- Line L5 does not increase , and converges to the minimizer. Each coordinate update is an exact minimization of a convex function of one variable on , and coordinate descent on a convex quadratic with box constraints reaches the minimizer. The tests compare it with a brute force search over all faces of the box.
- never increases. Both steps minimize in one block of variables, so the sequence of values is nonincreasing, and it converges, because .
- The generic rig is a fixed point. If the actor is the generic face and the examples are exact blends of the generic targets with the given weights, then at the start, and the method returns the generic targets and the given weights.
- Line L7 is exact for exact gradients. If the gradients come from a mesh, the least squares solution is that mesh, up to the fixed vertex.
The method finds a local minimum of a nonconvex problem in , and the result depends on the first guess of the weights.
Proof: Each step of example-based facial rigging minimizes the energy in one block, so the energy never increasesfull
We use the notation of the page. Flatten each , and over all triangles and entries into vectors . Then , with . The arithmetic is exact.
The blendshape step
Theorem 1. For fixed weights, line L4 returns the unique minimizer of in .
Proof. is a sum over the entries of terms that each depend only on :
where , and .
Each term is a quadratic in with the Hessian , which is positive definite, because and .
So each term has a unique minimizer, where the gradient vanishes, that is, .
This is the system that blendshape_step solves, with one right hand side per entry.
The weight step
For one example, drop the index and write , with , and . is the sum of the of the examples plus a term that does not depend on , and the examples do not share weights, so minimizing in is minimizing each on .
Lemma 1. A coordinate update with sets to the minimizer of over with the other coordinates fixed, and if it moves from to , then decreases by at least .
Proof. As a function of , is with . Its minimizer on is , and since is a convex parabola, its minimizer on is the clipped value , which the code computes. At , the optimality on the interval gives for every . Then .
If , then , does not depend on , and the code leaves unchanged.
Theorem 2. The weights of line L5 are in , never increases during the sweeps, and every limit point of the sweeps minimizes on . If is positive definite, the sweeps converge to the unique minimizer.
Proof. The start is clipped to and every update is clipped, so the weights stay in the box. By Lemma 1, never increases. Let be the point after sweep , and let be the map of one sweep, which is continuous as a composition of affine maps and clipping. The sum over all updates of is at most , which is finite, so the moves go to 0, and . The box is compact, so a subsequence converges to some , and by continuity . A fixed point of is left unchanged by its first update, so is the minimizer of in ; then the second update sees the same point, and so on for every coordinate. So for every , minimizes in on , which means if , if , and otherwise. These are the KKT conditions of a convex function on a box, so is a minimizer. If , the minimizer is unique, every convergent subsequence has the same limit, and the whole sequence converges to it.
The code stops when no coordinate moves by more than , which is a fixed point of up to rounding.
The energy never increases
Theorem 3. The values of recorded at line L6 and after line L4 are nonincreasing, and they converge.
Proof. Line L4 replaces by the minimizer of , which is at most the value at the old , by Theorem 1. Line L5 starts the sweeps of each example at the current weights, and by Theorem 2 the sweeps do not increase , so they do not increase . A nonincreasing sequence of numbers with converges.
The fixed point
Theorem 4. Let , let each example be the exact blend with , and let be linearly independent. Then the method returns and , up to the fixed vertex.
Proof. The gradient of a triangle is linear in the deformed positions for a fixed rest mesh, so . At the start, and , so both terms of are 0. , so this point minimizes in , and by the uniqueness of Theorem 1, line L4 returns . With , , which is the minimum, and is the Gram matrix of independent vectors, so it is positive definite and the minimizer is unique. The sweeps start at , and by Lemma 1 no update moves a minimizer, so line L5 keeps . By induction, every alternation keeps , and line L7 gets the gradients , which are the gradients of relative to , so by Theorem 5 it returns .
The Poisson step
Theorem 5. On a connected mesh, if the target gradients are the gradients of a mesh , line L7 returns translated so that the fixed vertex is at its rest position.
Proof. The objective is at least 0, and it is 0 at for the translation that moves the fixed vertex to its rest position, because a translation does not change edges. It remains to show that this zero is unique. If and both give 0 with the same fixed vertex, then satisfies for every triangle, where is the inverse of the rest edge matrix, so . Neighboring triangles share vertices, so on a connected mesh is constant, and it is 0 at the fixed vertex.
For gradients that do not come from a mesh, line L7 returns the least squares fit, which is the deformation transfer step.
The check values
For and one entry, Theorem 1 gives . With and , , so . For and , Lemma 1 gives , which is 1, 0.3 and 0 for , and .
Complexity
The costs are in the real RAM model. One step of line L4 costs to form the right hand sides, to factor the matrix and to solve for all entries. One step of line L5 costs for the Gram matrix, for the right hand sides and for sweeps of coordinate descent. Line L7 factors one matrix of size once and solves for the targets. The code uses dense matrices, which gives for line L7; with a sparse factorization, as in practice, this is much less.
Properties
- Personal: the targets follow the actor's examples, not only the generic rig.
- Semantic: each target keeps the meaning of its generic counterpart, so the rig works with the same controls and the same animation data.
- Few examples: the prior fills in what the examples do not show, so a few scans are enough.
- Bounded weights: the weights of the examples stay in , as in a blendshape rig.
- Local: the method is an alternating minimization, so it finds a local minimum.
Variants and improvements
- Without the prior. With , the targets fit the examples only, and with fewer examples than targets the problem has many solutions. The prior is what makes few examples enough.
- More examples. With many examples, the fit term dominates and the targets approach the true targets of the actor.
- Weighted prior. Weight the prior per triangle, so that a target may change more in some regions than in others.
- Online adaptation. Later work on real-time face tracking adapts the rig to the user during tracking instead of in a separate step.
When to use it
Use example-based facial rigging when you have a good generic face rig and must make a rig for a new actor or character with the same targets, from a few scans or sculpts. If the new face is a different character with no examples at all, deformation transfer alone gives a first rig. If you must edit an existing rig to hit a pose, blendshape direct manipulation solves for the weights instead.
Pitfalls
- Correspondence. All meshes must share one triangulation. The scans must be fitted with a template first, and errors in that fit go into the targets.
- Bad first guesses. The weights of each example start from a guess, and the method finds a local minimum near it. A guess that names the wrong targets gives wrong targets.
- The value of . A large keeps the generic targets and ignores the examples; a small one overfits the examples, and with few examples the targets can become strange where no example constrains them. On the toy face of the example, gives a larger error on the open target than , 0.055 against 0.026.
- Scale ambiguity. Without the prior, a target scaled by with its weights divided by fits the same examples. The prior fixes the scale.
- Rigid motion. The examples must be aligned with the neutral face, because a head motion in a scan changes every gradient.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the graphics-and-signals animation and simulation pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small vectors, matrices, polar decomposition, quaternions and transforms.
This file is copied byte for byte into each impl/python folder that needs it.
It holds no method of a page: no curve, no skinning, no integrator step, no
collision test and no solver of a page. The method of each page lives in its
slug file.
Conventions (prompts/graphics-ext.md, "Mathematical conventions"):
- Vectors are tuples. Functions accept lists too and return tuples.
- Matrices are lists of rows, and a matrix acts on a column vector on the
left: x' = M x.
- Quaternions use the Hamilton convention, scalar first, q = (w, x, y, z)
with i j = k. A unit quaternion q rotates v by v' = q (0, v) q*.
- The log of a unit quaternion (cos phi, sin phi u) is (0, phi u), and the
rotation angle is 2 phi. q_exp is the inverse map.
- Angles are in radians.
"""
import math
# Below this angle on the sphere of R^4, slerp uses normalized linear
# interpolation (nlerp), which avoids the division by sin(W).
SLERP_SMALL_ANGLE = 1e-6
# ---------------------------------------------------------------- vectors
def add(a, b):
"""Return a + b."""
return tuple(x + y for x, y in zip(a, b))
def sub(a, b):
"""Return a - b."""
return tuple(x - y for x, y in zip(a, b))
def scale(a, s):
"""Return s a for a number s."""
return tuple(s * x for x in a)
def dot(a, b):
"""Return the dot product of a and b."""
return sum(x * y for x, y in zip(a, b))
def cross(a, b):
"""Return the cross product of two 3D vectors."""
return (
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
)
def cross2(a, b):
"""Return the scalar 2D cross product a_x b_y - a_y b_x."""
return a[0] * b[1] - a[1] * b[0]
def norm(a):
"""Return the Euclidean length of a."""
return math.sqrt(sum(x * x for x in a))
def normalize(a):
"""Return a / |a|. Raise ValueError for the zero vector."""
n = norm(a)
if n == 0.0:
raise ValueError("cannot normalize the zero vector")
return tuple(x / n for x in a)
def lerp(a, b, t):
"""Return (1 - t) a + t b."""
return tuple((1 - t) * x + t * y for x, y in zip(a, b))
# ---------------------------------------------------------------- matrices
def zeros(n, m=None):
"""Return the n by m zero matrix (n by n if m is None)."""
if m is None:
m = n
return [[0.0] * m for _ in range(n)]
def eye(n):
"""Return the n by n identity matrix."""
return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
def mul(a, b):
"""Return the matrix product a b."""
bt = list(zip(*b))
return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]
def matvec(a, x):
"""Return the vector a x as a tuple."""
return tuple(sum(p * q for p, q in zip(row, x)) for row in a)
def transpose(a):
"""Return the transpose of a."""
return [list(col) for col in zip(*a)]
def _lu(a):
"""Gaussian elimination with partial pivoting on a copy of a square a.
Return (lu, perm, sign), or None if a pivot is exactly zero.
"""
n = len(a)
lu = [list(map(float, row)) for row in a]
perm = list(range(n))
sign = 1.0
for k in range(n):
p = max(range(k, n), key=lambda i: abs(lu[i][k]))
if lu[p][k] == 0.0:
return None
if p != k:
lu[k], lu[p] = lu[p], lu[k]
perm[k], perm[p] = perm[p], perm[k]
sign = -sign
piv = lu[k][k]
for i in range(k + 1, n):
f = lu[i][k] / piv
lu[i][k] = f
if f != 0.0:
rk = lu[k]
ri = lu[i]
for j in range(k + 1, n):
ri[j] -= f * rk[j]
return lu, perm, sign
def det(a):
"""Return the determinant of a square matrix."""
n = len(a)
if n == 1:
return a[0][0]
if n == 2:
return a[0][0] * a[1][1] - a[0][1] * a[1][0]
if n == 3:
return (
a[0][0] * (a[1][1] * a[2][2] - a[1][2] * a[2][1])
- a[0][1] * (a[1][0] * a[2][2] - a[1][2] * a[2][0])
+ a[0][2] * (a[1][0] * a[2][1] - a[1][1] * a[2][0])
)
r = _lu(a)
if r is None:
return 0.0
lu, _, sign = r
d = sign
for i in range(n):
d *= lu[i][i]
return d
def _lu_solve(lu, perm, b):
n = len(lu)
y = [float(b[perm[i]]) for i in range(n)]
for i in range(n):
s = y[i]
row = lu[i]
for j in range(i):
s -= row[j] * y[j]
y[i] = s
for i in range(n - 1, -1, -1):
s = y[i]
row = lu[i]
for j in range(i + 1, n):
s -= row[j] * y[j]
y[i] = s / row[i]
return y
def solve(a, b):
"""Solve a x = b by Gaussian elimination with partial pivoting.
b is a vector (returns a list) or a matrix given as a list of rows
(returns a list of rows, one column of x per column of b).
Raise ValueError if a is singular.
"""
r = _lu(a)
if r is None:
raise ValueError("singular matrix")
lu, perm, _ = r
if len(b) > 0 and isinstance(b[0], (list, tuple)):
cols = [_lu_solve(lu, perm, col) for col in zip(*b)]
return [list(row) for row in zip(*cols)]
return _lu_solve(lu, perm, b)
def inv(a):
"""Return the inverse of a square matrix. Raise ValueError if singular."""
return solve(a, eye(len(a)))
# ---------------------------------------------------------------- polar decomposition
def rot2(theta):
"""Return the 2 by 2 rotation matrix by the angle theta."""
c, s = math.cos(theta), math.sin(theta)
return [[c, -s], [s, c]]
def _frob(a):
return math.sqrt(sum(x * x for row in a for x in row))
def _sym_eig3(s):
"""Eigenvalues and eigenvectors of a symmetric 3 by 3 matrix (cyclic Jacobi).
Return (values, vectors), where vectors[k] is the unit eigenvector of
values[k].
"""
a = [list(map(float, row)) for row in s]
v = eye(3)
for _ in range(50):
off = a[0][1] ** 2 + a[0][2] ** 2 + a[1][2] ** 2
if off <= 1e-30 * (sum(a[i][i] ** 2 for i in range(3)) + 1e-300):
break
for p, q in ((0, 1), (0, 2), (1, 2)):
if a[p][q] == 0.0:
continue
theta = (a[q][q] - a[p][p]) / (2.0 * a[p][q])
t = math.copysign(1.0, theta) / (abs(theta) + math.sqrt(theta * theta + 1.0))
c = 1.0 / math.sqrt(t * t + 1.0)
sn = t * c
for k in range(3):
akp, akq = a[k][p], a[k][q]
a[k][p] = c * akp - sn * akq
a[k][q] = sn * akp + c * akq
for k in range(3):
apk, aqk = a[p][k], a[q][k]
a[p][k] = c * apk - sn * aqk
a[q][k] = sn * apk + c * aqk
for k in range(3):
vkp, vkq = v[k][p], v[k][q]
v[k][p] = c * vkp - sn * vkq
v[k][q] = sn * vkp + c * vkq
values = [a[i][i] for i in range(3)]
vectors = [tuple(v[k][i] for k in range(3)) for i in range(3)]
return values, vectors
def polar(f, tol=1e-14, max_iter=100):
"""Return (R, S) with F = R S, det R = +1 and S symmetric.
2 by 2: closed form. R = rot2(theta) with theta = atan2(f10 - f01, f00 + f11),
the rotation that maximizes trace(R^T F), and S = R^T F.
3 by 3: the Newton iteration X <- (X + X^(-T)) / 2 of Higham (1986), with
the scaling gamma = (|X^(-1)|_F / |X|_F)^(1/2) while the relative change
is above 1e-2. It stops when the relative change in the Frobenius norm is
at most tol, or after max_iter steps. The iteration gives the orthogonal
polar factor U. If det U < 0 (det F < 0), R = U (I - 2 v v^T) for the unit
eigenvector v of the smallest eigenvalue of U^T F, so that det R = +1.
If det F > 0, S is symmetric positive definite. If det F < 0, S is
symmetric with one negative eigenvalue. Raise ValueError for a singular
3 by 3 F.
"""
n = len(f)
if n == 2:
theta = math.atan2(f[1][0] - f[0][1], f[0][0] + f[1][1])
r = rot2(theta)
s = mul(transpose(r), f)
s01 = 0.5 * (s[0][1] + s[1][0])
s[0][1] = s[1][0] = s01
return r, s
if n != 3:
raise ValueError("polar supports 2 by 2 and 3 by 3 matrices")
x = [list(map(float, row)) for row in f]
change = float("inf")
for _ in range(max_iter):
xi = inv(x)
if change > 1e-2:
g = math.sqrt(_frob(xi) / _frob(x))
else:
g = 1.0
xit = transpose(xi)
y = [[0.5 * (g * x[i][j] + xit[i][j] / g) for j in range(3)] for i in range(3)]
change = _frob([[y[i][j] - x[i][j] for j in range(3)] for i in range(3)]) / _frob(y)
x = y
if change <= tol:
break
u = x
s = mul(transpose(u), f)
s = [[0.5 * (s[i][j] + s[j][i]) for j in range(3)] for i in range(3)]
if det(u) < 0.0:
values, vectors = _sym_eig3(s)
k = min(range(3), key=lambda i: values[i])
v = vectors[k]
h = [[(1.0 if i == j else 0.0) - 2.0 * v[i] * v[j] for j in range(3)] for i in range(3)]
u = mul(u, h)
s = mul(h, s)
s = [[0.5 * (s[i][j] + s[j][i]) for j in range(3)] for i in range(3)]
return u, s
# ---------------------------------------------------------------- quaternions
def q_mul(p, q):
"""Return the Hamilton product p q."""
a1, b1, c1, d1 = p
a2, b2, c2, d2 = q
return (
a1 * a2 - b1 * b2 - c1 * c2 - d1 * d2,
a1 * b2 + b1 * a2 + c1 * d2 - d1 * c2,
a1 * c2 - b1 * d2 + c1 * a2 + d1 * b2,
a1 * d2 + b1 * c2 - c1 * b2 + d1 * a2,
)
def q_conj(q):
"""Return the conjugate (w, -x, -y, -z)."""
return (q[0], -q[1], -q[2], -q[3])
def q_dot(p, q):
"""Return the dot product of p and q as vectors of R^4."""
return p[0] * q[0] + p[1] * q[1] + p[2] * q[2] + p[3] * q[3]
def q_normalize(q):
"""Return q / |q|."""
n = math.sqrt(q_dot(q, q))
if n == 0.0:
raise ValueError("cannot normalize the zero quaternion")
return (q[0] / n, q[1] / n, q[2] / n, q[3] / n)
def q_from_axis_angle(axis, angle):
"""Return the unit quaternion of the rotation by angle about axis (any length)."""
u = normalize(axis)
s = math.sin(0.5 * angle)
return (math.cos(0.5 * angle), s * u[0], s * u[1], s * u[2])
def q_to_mat3(q):
"""Return the 3 by 3 rotation matrix of a unit quaternion."""
w, x, y, z = q
return [
[1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
[2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
[2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)],
]
def q_rotate(q, v):
"""Return the vector part of q (0, v) q* for a unit quaternion q."""
r = q_mul(q_mul(q, (0.0, v[0], v[1], v[2])), q_conj(q))
return (r[1], r[2], r[3])
def q_log(q):
"""Return the log of a nonzero quaternion as a 4-tuple (ln|q|, phi u).
For a unit quaternion (cos phi, sin phi u) this is (0, phi u), with
phi = atan2(|v|, w) in [0, pi]. For a real q the vector part is zero.
"""
n = math.sqrt(q_dot(q, q))
if n == 0.0:
raise ValueError("log of the zero quaternion")
vn = math.sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3])
lw = math.log(n)
if vn == 0.0:
return (lw, 0.0, 0.0, 0.0)
phi = math.atan2(vn, q[0])
f = phi / vn
return (lw, f * q[1], f * q[2], f * q[3])
def q_exp(q):
"""Return exp(q) = e^w (cos|v|, sin|v| v / |v|) for q = (w, v)."""
vn = math.sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3])
ew = math.exp(q[0])
if vn == 0.0:
return (ew, 0.0, 0.0, 0.0)
f = ew * math.sin(vn) / vn
return (ew * math.cos(vn), f * q[1], f * q[2], f * q[3])
def slerp(q0, q1, t):
"""Spherical linear interpolation of unit quaternions on the short arc.
If q0 . q1 < 0, q1 is replaced by -q1 (the same rotation). The angle W
comes from atan2(|q1 - q0|, |q1 + q0|). Below SLERP_SMALL_ANGLE the
normalized linear interpolation is returned. See
robotics/rigid-body-motion/spherical-linear-interpolation.
"""
if q_dot(q0, q1) < 0.0:
q1 = (-q1[0], -q1[1], -q1[2], -q1[3])
a = math.sqrt(sum((y - x) ** 2 for x, y in zip(q0, q1)))
b = math.sqrt(sum((y + x) ** 2 for x, y in zip(q0, q1)))
w = 2.0 * math.atan2(a, b)
if w < SLERP_SMALL_ANGLE:
return q_normalize(tuple((1 - t) * x + t * y for x, y in zip(q0, q1)))
s = math.sin(w)
c0 = math.sin((1 - t) * w) / s
c1 = math.sin(t * w) / s
return tuple(c0 * x + c1 * y for x, y in zip(q0, q1))
def q_from_mat3(r):
"""Return the unit quaternion, with w >= 0, of a 3 by 3 rotation matrix.
Shepperd's method: take the largest of the trace, r00, r11 and r22, and
divide by the component that it gives. See
robotics/rigid-body-motion/shepperd-method.
"""
t = r[0][0] + r[1][1] + r[2][2]
k = max(range(4), key=lambda i: (t, r[0][0], r[1][1], r[2][2])[i])
if k == 0:
w = math.sqrt(1.0 + t) / 2.0
f = 4.0 * w
q = (w, (r[2][1] - r[1][2]) / f, (r[0][2] - r[2][0]) / f, (r[1][0] - r[0][1]) / f)
elif k == 1:
x = math.sqrt(max(0.0, 1.0 + 2.0 * r[0][0] - t)) / 2.0
f = 4.0 * x
q = ((r[2][1] - r[1][2]) / f, x, (r[1][0] + r[0][1]) / f, (r[0][2] + r[2][0]) / f)
elif k == 2:
y = math.sqrt(max(0.0, 1.0 + 2.0 * r[1][1] - t)) / 2.0
f = 4.0 * y
q = ((r[0][2] - r[2][0]) / f, (r[1][0] + r[0][1]) / f, y, (r[2][1] + r[1][2]) / f)
else:
z = math.sqrt(max(0.0, 1.0 + 2.0 * r[2][2] - t)) / 2.0
f = 4.0 * z
q = ((r[1][0] - r[0][1]) / f, (r[0][2] + r[2][0]) / f, (r[2][1] + r[1][2]) / f, z)
if q[0] < 0.0:
q = (-q[0], -q[1], -q[2], -q[3])
return q
# ---------------------------------------------------------------- transforms
def make_T(r, t):
"""Return the homogeneous (d + 1) by (d + 1) matrix [[R, t], [0, 1]] for d = len(t)."""
d = len(t)
m = [[float(r[i][j]) for j in range(d)] + [float(t[i])] for i in range(d)]
m.append([0.0] * d + [1.0])
return m
def T_mul(a, b):
"""Return the product a b of two homogeneous transforms."""
return mul(a, b)
def T_inv(m):
"""Return the inverse of an affine homogeneous transform [[A, t], [0, 1]].
The result is [[A^(-1), -A^(-1) t], [0, 1]]; A may hold a scale.
"""
d = len(m) - 1
a = [row[:d] for row in m[:d]]
t = [m[i][d] for i in range(d)]
ai = inv(a)
ti = matvec(ai, t)
return make_T(ai, tuple(-x for x in ti))
def T_apply(m, p):
"""Apply a homogeneous transform to a point p and return a tuple."""
d = len(m) - 1
return tuple(sum(m[i][j] * p[j] for j in range(d)) + m[i][d] for i in range(d))
# ---------------------------------------------------------------- derivatives
def num_grad(f, x, h=1e-6):
"""Return the gradient of a scalar f at x by central differences of step h."""
x = list(x)
g = []
for i in range(len(x)):
xi = x[i]
x[i] = xi + h
fp = f(x)
x[i] = xi - h
fm = f(x)
x[i] = xi
g.append((fp - fm) / (2.0 * h))
return g
example_based_facial_rigging.py 180 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/example-based-facial-rigging/. The authors are listed in prov/3M9YWE.jsonl.
"""Example-based facial rigging (after Li, Weise and Pauly 2010), on 2D triangle meshes.
The input is a generic blendshape rig (a neutral A0 and targets A1..An), the
neutral B0 of an actor, m example expressions S1..Sm of the actor, and a
first guess of the blend weights of each example. All meshes share one
triangulation. The output is a blendshape rig of the actor: targets B1..Bn
and the weights of the examples.
The method works with deformation gradients. For triangle t, the gradient
of a mesh X relative to the actor neutral is the 2 by 2 matrix
F = [x_b - x_a, x_c - x_a] [b_b - b_a, b_c - b_a]^(-1). Let D_i = F(B_i) - I
for the unknown targets, R_j = F(S_j) - I for the examples, and H_i =
G_i - I for the gradients G_i of the generic target i relative to the
generic neutral. The energy is
E(D, alpha) = sum_j sum_t |sum_i alpha_ij D_i - R_j|_F^2
+ beta sum_i sum_t |D_i - H_i|_F^2.
The first term asks the rig to reproduce the examples. The second is the
prior: each actor target should change its triangles like the generic
target, which is deformation transfer when the two meshes share a
triangulation. The start is D = H, the deformation transfer of the generic
rig. The method alternates an exact least squares step in D and a bounded
least squares step in alpha, with 0 <= alpha <= 1, and at the end recovers
the vertex positions of each target by a Poisson (least squares) solve.
The paper works on 3D meshes, weights the prior per triangle, and has
further terms; this file keeps the structure of the method only.
"""
from anim import inv, solve, sub
def gradient(rest, deformed, tri):
"""Return the 2 by 2 deformation gradient of one triangle."""
a, b, c = tri
e1, e2 = sub(rest[b], rest[a]), sub(rest[c], rest[a])
f1, f2 = sub(deformed[b], deformed[a]), sub(deformed[c], deformed[a])
q = inv([[e1[0], e2[0]], [e1[1], e2[1]]])
return [[f1[r] * q[0][k] + f2[r] * q[1][k] for k in range(2)] for r in range(2)]
def flat_offsets(rest, deformed, tris):
"""Return the list over triangles of the 4 entries of F - I, flattened."""
out = []
for tri in tris:
g = gradient(rest, deformed, tri)
out.extend([g[0][0] - 1.0, g[0][1], g[1][0], g[1][1] - 1.0])
return out
def energy(d, alpha, r, h, beta):
"""Return E(D, alpha) for flattened D_i, R_j and H_i."""
e = 0.0
for j, rj in enumerate(r):
for p in range(len(rj)):
s = sum(alpha[j][i] * d[i][p] for i in range(len(d))) - rj[p]
e += s * s
for di, hi in zip(d, h):
e += beta * sum((x - y) ** 2 for x, y in zip(di, hi))
return e
def blendshape_step(alpha, r, h, beta):
"""Return the D that minimizes E for fixed alpha.
For each entry p, the vector (D_1[p], ..., D_n[p]) solves
(A^T A + beta I) z = A^T (R_1[p], ..., R_m[p]) + beta (H_1[p], ..., H_n[p]),
where A is the m by n matrix of the weights. The matrix is the same for
every entry, so it is solved once with all entries as right hand sides.
"""
n, m, size = len(h), len(r), len(h[0])
mat = [[sum(alpha[j][a] * alpha[j][b] for j in range(m)) + (beta if a == b else 0.0) for b in range(n)] for a in range(n)]
rhs = [[sum(alpha[j][a] * r[j][p] for j in range(m)) + beta * h[a][p] for p in range(size)] for a in range(n)]
z = solve(mat, rhs)
return [list(row) for row in z]
def bounded_lsq(gram, lin, start, tol=1e-14, max_iter=100000):
"""Minimize a^T G a - 2 b^T a over the box [0, 1]^n by cyclic coordinate descent.
Each coordinate is set to its exact minimizer, clipped to [0, 1]. The
objective never increases. The loop stops when no coordinate moves by
more than tol.
"""
a = [min(1.0, max(0.0, x)) for x in start]
n = len(a)
for _ in range(max_iter):
move = 0.0
for i in range(n):
if gram[i][i] <= 0.0:
continue
v = (lin[i] - sum(gram[i][k] * a[k] for k in range(n) if k != i)) / gram[i][i]
v = min(1.0, max(0.0, v))
move = max(move, abs(v - a[i]))
a[i] = v
if move <= tol:
break
return a
def weight_step(d, r, alpha):
"""Return the weights that minimize E for fixed D, each in [0, 1]."""
n = len(d)
gram = [[sum(x * y for x, y in zip(d[a], d[b])) for b in range(n)] for a in range(n)]
out = []
for j, rj in enumerate(r):
lin = [sum(x * y for x, y in zip(d[a], rj)) for a in range(n)]
out.append(bounded_lsq(gram, lin, alpha[j]))
return out
def poisson_reconstruct(rest, tris, grads, fixed=0):
"""Return the meshes whose triangle gradients fit grads in least squares.
grads[k] is the list over triangles of 2 by 2 matrices for mesh k. The
vertex fixed keeps its rest position. The normal matrix depends only on
the rest mesh, so it is built once for all meshes and both coordinates.
"""
nv = len(rest)
free = [v for v in range(nv) if v != fixed]
col = {v: i for i, v in enumerate(free)}
qs = []
for a, b, c in tris:
e1, e2 = sub(rest[b], rest[a]), sub(rest[c], rest[a])
qs.append(inv([[e1[0], e2[0]], [e1[1], e2[1]]]))
size = len(free)
ata = [[0.0] * size for _ in range(size)]
atb = [[0.0] * (2 * len(grads)) for _ in range(size)]
fp = rest[fixed]
for t, (a, b, c) in enumerate(tris):
q = qs[t]
for k in range(2):
coef = {b: q[0][k], c: q[1][k]}
coef[a] = coef.get(a, 0.0) - q[0][k] - q[1][k]
items = [(col[v], w) for v, w in coef.items() if v != fixed]
shift = coef.get(fixed, 0.0)
for i, wi in items:
for j, wj in items:
ata[i][j] += wi * wj
for g, gk in enumerate(grads):
for r in range(2):
val = gk[t][r][k] - shift * fp[r]
for i, wi in items:
atb[i][2 * g + r] += wi * val
x = solve(ata, atb)
meshes = []
for g in range(len(grads)):
meshes.append([tuple(fp) if v == fixed else (x[col[v]][2 * g], x[col[v]][2 * g + 1]) for v in range(nv)])
return meshes
def unflatten(dvec, ntri):
"""Return the list of 2 by 2 matrices I + D for one flattened D."""
return [[[1.0 + dvec[4 * t], dvec[4 * t + 1]], [dvec[4 * t + 2], 1.0 + dvec[4 * t + 3]]] for t in range(ntri)]
def facial_rig(generic, actor_neutral, examples, alpha0, tris, beta=0.1, iterations=20):
"""Return (targets, alpha, history).
generic is [A0, A1, ..., An], actor_neutral is B0, examples is
[S1, ..., Sm], and alpha0[j] is the first guess of the weights of
example j. history holds E after the start and after each step.
"""
a0 = generic[0]
h = [flat_offsets(a0, ai, tris) for ai in generic[1:]] # @line L1
r = [flat_offsets(actor_neutral, s, tris) for s in examples] # @line L2
d = [list(x) for x in h]
alpha = [[min(1.0, max(0.0, x)) for x in row] for row in alpha0]
history = [energy(d, alpha, r, h, beta)]
for _ in range(iterations): # @line L3
d = blendshape_step(alpha, r, h, beta) # @line L4
history.append(energy(d, alpha, r, h, beta))
alpha = weight_step(d, r, alpha) # @line L5
history.append(energy(d, alpha, r, h, beta)) # @line L6
grads = [unflatten(di, len(tris)) for di in d]
targets = poisson_reconstruct(actor_neutral, tris, grads) # @line L7
return targets, alpha, history # @line L8
test_example_based_facial_rigging.py 146 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/example-based-facial-rigging/. The authors are listed in prov/3M9YWE.jsonl.
"""Tests of example-based facial rigging.
If the actor is the generic face, the generic rig is a fixed point. The
energy never increases. The blendshape step is the minimizer in D, and the
weight step matches a brute force search over the faces of the box. The
Poisson step recovers a mesh from its own gradients. On a toy face, the
rig fits the actor much better than deformation transfer alone, and the
weights come close to the true ones. The check values of the page hold.
"""
import itertools
import random
from anim import solve
from example_based_facial_rigging import (
blendshape_step,
energy,
facial_rig,
flat_offsets,
gradient,
poisson_reconstruct,
unflatten,
weight_step,
)
V = [(0.0, 0.0), (1.0, 0.0), (2.0, 0.0), (0.0, 1.0), (1.0, 1.0), (2.0, 1.0)]
TRIS = [(0, 1, 4), (0, 4, 3), (1, 2, 5), (1, 5, 4)]
A1 = [(x, 1.5 * y) for x, y in V] # generic "open"
A2 = [(x + 0.2 * x * y, y) for x, y in V] # generic "smile"
B0 = [(1.2 * x + 0.1 * y, 0.9 * y + 0.05 * x * x) for x, y in V]
B1 = [(x, y + 0.7 * (y - 0.05 * x * x) / 0.9 * (1.0 + 0.1 * x)) for x, y in B0]
B2 = [(x + 0.3 * x * y, y - 0.05 * x) for x, y in B0]
TRUE_ALPHA = [(1.0, 0.0), (0.0, 1.0), (0.6, 0.5)]
GUESS = [(0.9, 0.1), (0.1, 0.8), (0.5, 0.5)]
def blend(base, targets, weights):
return [tuple(base[v][k] + sum(w * (t[v][k] - base[v][k]) for w, t in zip(weights, targets)) for k in range(2)) for v in range(len(base))]
EXAMPLES = [blend(B0, [B1, B2], a) for a in TRUE_ALPHA]
def dist(m, n):
return max(abs(p[k] - q[k]) for p, q in zip(m, n) for k in range(2))
def test_generic_rig_is_a_fixed_point_for_the_generic_actor():
examples = [blend(V, [A1, A2], a) for a in TRUE_ALPHA]
targets, alpha, hist = facial_rig([V, A1, A2], V, examples, TRUE_ALPHA, TRIS, beta=0.1, iterations=3)
assert dist(targets[0], A1) < 1e-10 and dist(targets[1], A2) < 1e-10
assert max(abs(a - b) for r, s in zip(alpha, TRUE_ALPHA) for a, b in zip(r, s)) < 1e-10
assert max(hist) < 1e-20
def test_energy_never_increases_and_weights_stay_in_the_box():
for beta in (1.0, 0.1, 0.01):
_, alpha, hist = facial_rig([V, A1, A2], B0, EXAMPLES, GUESS, TRIS, beta=beta, iterations=15)
assert all(hist[i + 1] <= hist[i] + 1e-12 for i in range(len(hist) - 1))
assert hist[-1] < 0.5 * hist[0]
assert all(0.0 <= a <= 1.0 for row in alpha for a in row)
def test_blendshape_step_is_the_minimizer():
rng = random.Random(3)
n, m, size, beta = 3, 4, 8, 0.2
alpha = [[rng.random() for _ in range(n)] for _ in range(m)]
r = [[rng.uniform(-1, 1) for _ in range(size)] for _ in range(m)]
h = [[rng.uniform(-1, 1) for _ in range(size)] for _ in range(n)]
d = blendshape_step(alpha, r, h, beta)
e = energy(d, alpha, r, h, beta)
for _ in range(50):
d2 = [[x + rng.uniform(-1e-3, 1e-3) for x in row] for row in d]
assert energy(d2, alpha, r, h, beta) > e
eps = 1e-6
for i in range(n):
for p in range(size):
dp = [row[:] for row in d]
dm = [row[:] for row in d]
dp[i][p] += eps
dm[i][p] -= eps
assert abs(energy(dp, alpha, r, h, beta) - energy(dm, alpha, r, h, beta)) / (2 * eps) < 1e-7
def brute_force_box(d, rj):
n = len(d)
def obj(a):
return sum((sum(a[i] * d[i][p] for i in range(n)) - rj[p]) ** 2 for p in range(len(rj)))
best = None
for faces in itertools.product((0.0, 1.0, None), repeat=n):
free = [i for i in range(n) if faces[i] is None]
a = [0.0 if f is None else f for f in faces]
if free:
res = [rj[p] - sum(a[i] * d[i][p] for i in range(n)) for p in range(len(rj))]
g = [[sum(d[i][p] * d[k][p] for p in range(len(rj))) for k in free] for i in free]
b = [sum(d[i][p] * res[p] for p in range(len(rj))) for i in free]
for i, v in zip(free, solve(g, b)):
a[i] = v
if all(-1e-12 <= x <= 1.0 + 1e-12 for x in a):
v = obj(a)
if best is None or v < best[0]:
best = (v, a)
return best
def test_weight_step_against_brute_force():
rng = random.Random(11)
for _ in range(30):
n, size = rng.choice((2, 3)), 8
d = [[rng.uniform(-1, 1) for _ in range(size)] for _ in range(n)]
r = [[rng.uniform(-1.5, 1.5) for _ in range(size)] for _ in range(2)]
alpha = weight_step(d, r, [[0.5] * n, [0.0] * n])
for aj, rj in zip(alpha, r):
want, _ = brute_force_box(d, rj)
got = sum((sum(aj[i] * d[i][p] for i in range(n)) - rj[p]) ** 2 for p in range(size))
assert abs(got - want) < 1e-10
assert all(0.0 <= a <= 1.0 for a in aj)
def test_poisson_recovers_a_mesh_from_its_gradients():
grads = [[gradient(B0, mesh, t) for t in TRIS] for mesh in (B1, B2)]
out = poisson_reconstruct(B0, TRIS, grads)
for mesh, rec in zip((B1, B2), out):
shift = (B0[0][0] - mesh[0][0], B0[0][1] - mesh[0][1])
assert dist([(x + shift[0], y + shift[1]) for x, y in mesh], rec) < 1e-12
def test_rig_beats_deformation_transfer_on_the_toy_face():
targets, alpha, _ = facial_rig([V, A1, A2], B0, EXAMPLES, GUESS, TRIS, beta=0.1, iterations=30)
transfer = poisson_reconstruct(B0, TRIS, [unflatten(flat_offsets(V, a, TRIS), len(TRIS)) for a in (A1, A2)])
for got, dt, want in zip(targets, transfer, (B1, B2)):
assert dist(got, want) < 0.05
assert dist(dt, want) > 0.25
assert max(abs(a - b) for r, s in zip(alpha, TRUE_ALPHA) for a, b in zip(r, s)) < 0.05
def test_check_values_of_the_page():
d = blendshape_step([[0.5]], [[0.4, 0.0, -0.2, 1.0]], [[0.2, 0.6, 0.0, -1.0]], 0.25)
want = [0.4 + 0.1, 0.0 + 0.3, -0.2 + 0.0, 1.0 - 0.5]
assert max(abs(a - b) for a, b in zip(d[0], want)) < 1e-12
w = weight_step([[1.0, 0.0, 0.0, 0.0]], [[2.0, 0, 0, 0], [0.3, 5, 0, 0], [-0.4, 0, 0, 0]], [[0.5]] * 3)
assert w == [[1.0], [0.3], [0.0]]
History
Blendshape rigs for faces were modeled by hand for a long time, often with the Facial Action Coding System as a guide for the targets. Sumner and Popović (2004) gave deformation transfer, which copies the targets of one face onto another, but the copies show how the source face moves, not how the new face moves. Li, Weise and Pauly (2010) added examples of the actor and optimized the targets in the space of deformation gradients, with the transferred generic rig as the prior. Later work on real-time face tracking adapted the rig to the user during tracking.
References
- Hao Li, Thibaut Weise and Mark Pauly, Example-based facial rigging, ACM Transactions on Graphics 29(4), SIGGRAPH 2010, article 32, the optimization of the actor targets in deformation gradients with the generic rig as a prior, the alternation with the blend weights of the examples, and the reconstruction of the vertex positions
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 3M9YWE Edit this page History Report an error Markdown