Algorithmadvanced
Deformation transfer
Also called Sumner-Popovic deformation transfer.
Copy the deformation of a source mesh onto a different target mesh by transferring per-triangle deformation gradients and solving a least-squares system.
- Solves
- Shape deformation
- Time
- O(p + (n + t)^2) frameO(p + (n + t)^3) setup
- Space
- O((n + t)^2) extra
- Where
- n = the number of target vertices; p = the number of triangle pairs in the correspondence; t = the number of target triangles
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
Deformation transfer copies a deformation from one mesh to another. The input is a source mesh in its rest shape, the same source mesh deformed, for example into a smile or a bent knee, and a different target mesh in its rest shape. The output is the target deformed in the same way. Sumner and Popović (2004) gave the method. It describes the change of each source triangle by a 3 by 3 matrix, the deformation gradient of that triangle, and then finds the target vertices whose triangles change by the same matrices, as closely as possible in the least squares sense. Facial rigs use it to copy the targets of a generic blendshape model onto a new face, and it is the first step of example-based facial rigging.
In plain words
Take one small triangle of the source and look at how the deformation changed it: it may turn, stretch or shear. Write that change as a matrix. Do this for every triangle of the source. Then go to the target and say which target triangles belong to which source triangles, for example the corner of the mouth to the corner of the mouth. Now each target triangle should change by the matrix of its source triangle. Each triangle alone could do that, but the triangles share vertices, so they cannot all do it exactly. So we look for the vertex positions that make the changes of the target triangles as close as possible to the wanted matrices. That is one linear least squares problem. The target keeps its own shape and proportions, and only the change is copied.
The problem
The source has rest vertices and deformed vertices , on the same triangles. The target has rest vertices , , and triangles. A correspondence is a list of pairs of a target triangle and a source triangle . It can be many to many: a target triangle may appear in several pairs, and a source triangle too. The output is the deformed target .
A triangle alone does not fix an affine map of space, because the direction normal to it is free. The method adds a fourth vertex
which is equation (1) of the paper. The square root makes the length of proportional to the size of the triangle, so the normal direction scales with the triangle. The frame of the triangle is the matrix , with these three columns. The deformation of a source triangle is , the unique linear map that takes the rest frame to the deformed frame.
For the target, the deformed vertices and the deformed fourth vertices are the unknowns. The deformed frame of a target triangle is linear in them, so the problem is
The energy does not change when all unknowns move by the same vector, so one vertex is fixed to remove the translation.
The algorithm
DEFORMATION-TRANSFER(source rest v, source deformed ṽ, target rest u, pairs, fixed vertex f at position x_f)- 1
for each source triangle S: S_S ← Ṽ_S V_S⁻¹ ▷ frames with the fourth vertex of equation (1) - 2
for each target triangle T: Q_T ← U_T⁻¹ ▷ depends only on the target rest mesh - 3
for each pair (T, S) and each column k: add the row Σ_r Q_T[r][k] (x_r - x_a) = column k of S_S - 4
remove the unknown of vertex f, and move its terms with x_f to the right side - 5
solve AᵀA X = AᵀB ▷ one matrix, three right sides for x, y and z - 6
read ũᵢ from X for every vertex, with ũ_f = x_f - 7
return ũ
In line L3, is the first vertex of , and is the unknown of the second vertex, the third vertex or the fourth vertex, for . The row is the same for the three coordinates, and the right side has one entry per coordinate, the column of . So the matrix has one row per pair and column, and one column per unknown point: the target vertices and the fourth vertices, less the fixed one.
Lines L2 to L5 build and solve the normal equations.
The matrix depends only on the target rest mesh and the correspondence, not on the source deformation.
The paper uses this: it factors once, and for each new source pose it only builds the right side and solves with the factors.
The code in impl/python uses the dense solver of the shared helper and factors again on each call, which is simple and fast enough for small meshes.
Example
Take one source triangle , deformed by a shear to . Its normal is with length 1, so , and is the identity. The deformed frame has the columns , and , so
The target is a longer triangle . Its cross product is , so . With one pair and the first vertex fixed at the origin, the energy is zero when . The columns of are , and . So the target becomes , and the fourth vertex stays at . The top vertex moved by the same shear as in the source, and the long side kept its length 2. The tests check these numbers.
Correctness
The proofs are in proofs/correctness.md. They hold in exact arithmetic, for a connected target mesh without degenerate triangles, in which every target triangle is in at least one pair.
- One solution. With one vertex fixed, has full column rank, so is positive definite and line L5 has exactly one solution, the unique minimizer of the energy.
- No deformation, no change. If the source is not deformed, every is the identity, the target rest mesh has zero energy, and so it is the result.
- A uniform similarity is exact. If the source moves by with a rotation and , the fourth vertex moves by the same map, every , and the target moves by the same map. For a general affine map the fourth vertex does not follow the map, so the result is close to it but not exact.
- Self transfer. If the target is the source with the identity correspondence, the deformed source has zero energy, so the method gives it back.
The tests check all of these, and also that the solution has a zero gradient and beats random perturbations, and that a repeated correspondence gives the same result.
Proof: Deformation transfer has one solution, keeps the rest shape, copies a similarity exactly and gives back the source under self transferfull
We use the notation of the page. The target mesh is connected, no triangle is degenerate, every target triangle is in at least one pair, and vertex is fixed at . For a target triangle with the unknown points and the unknown fourth point , write . The energy is with . The arithmetic is exact.
The rows of line L3 are the energy
Column of is . The square of the Frobenius norm is the sum over the columns of the squared lengths of the column differences, and the squared length is the sum over the three coordinates. So , where has one row per pair and column , with the coefficients of line L3, has one row per unknown point and one column per coordinate, and holds the columns of . Moving the known point to the right side, as in line L4, does not change the value of .
One solution
Lemma 1. With vertex removed, has full column rank.
Proof. Let for one coordinate column , with . Then , where is the frame built from as is built from , but in one coordinate, so it is a row vector. Since is invertible, for every triangle in a pair, which is every triangle. So , and in every triangle. The mesh is connected, so all vertex values are equal, and they equal . Then every fourth value is too, so .
Theorem 1. Line L5 has exactly one solution, and it is the unique minimizer of with .
Proof. By Lemma 1, is symmetric positive definite. is a convex quadratic in with the Hessian , so it is strictly convex, and its only stationary point is the solution of .
So in each of the cases below it is enough to show a point with and : since , that point is the minimizer, and by Theorem 1 it is the output.
The rest shape and self transfer
Theorem 2. If , the output is the target rest mesh.
Proof. Every . Take and the rest fourth vertex of , so and . Then , and by the choice of the fixed position.
Theorem 3. If the target is the source, the pairs are , and , the output is .
Proof. Take and the fourth vertex of the deformed source triangle. Then , so , and .
A similarity is copied exactly
Lemma 2. Let with , a rotation and . Then the fourth vertex of is .
Proof. For a rotation, , so . With , the new cross product is , its length is , and the square root of the length is . So the new fourth vertex is .
Theorem 4. If for all , and , the output is for all .
Proof. By Lemma 2, , so every . Take and . Then , because the translation cancels in the differences, so for every pair and .
For a general affine , the cross product of and is , which in general is not parallel to , for example for a shear. So the deformed fourth vertex does not follow , differs from in its third column, and the result is in general not .
Duplicated pairs
If every pair appears twice, is multiplied by 2, and the minimizer does not change.
The check value
For the shear of the page, and has the columns , and . For the target, has the columns , and , and has the columns , and . With the first vertex fixed at the origin, the point and gives , so it is the output.
Complexity
The costs are in the real RAM model. Line L1 costs per source triangle, and line L3 costs per pair. The system has unknown points and rows, each with at most four nonzero entries. The dense solve of the code costs . With a sparse Cholesky or LU factorization, as in the paper, the cost of the factorization depends on the fill, and for meshes it is close to linear in practice. For each new source pose, only the right side changes, so the cost per frame is the cost of lines L1 and L3 plus two triangular solves with the kept factors.
Properties
- Linear: for a fixed target and correspondence, the result depends linearly on the source matrices .
- Translation is lost: the energy sees only differences of vertices, so the position comes from the fixed vertex or another constraint.
- The target keeps its own proportions, because only the change of each triangle is copied, not its shape.
- The correspondence can be many to many and does not need the two meshes to have the same vertex count or connectivity.
- Each coordinate , and is a separate solve with the same matrix.
Variants and improvements
- The correspondence step. The paper also finds the triangle correspondence, from a few marker points given by the user, by deforming the source onto the target with an energy of smoothness, identity and closest points, and then pairing triangles whose centroids are close. The code in
impl/pythontakes the correspondence as input. - Gradient domain editing. The same idea, prescribing the per-triangle change and solving for vertices, is the base of Poisson-type mesh editing and of Laplacian surface editing.
- Rotations only. A related family of energies fits only a rotation per element, as in as-rigid-as-possible deformation. That is a different method: it keeps the target rigid where it can, and does not copy stretch or shear.
- Facial rigs. Copying every target of a generic blendshape rig onto a new face gives a first rig for that face. Example-based facial rigging starts from that rig and then corrects it with scans of the actor.
- Motion. Applying the method to every frame of an animation copies the animation, frame by frame. It copies shape changes, not the motion of a skeleton, which is the job of motion retargeting.
When to use it
Use deformation transfer when the source and the target are different meshes of a similar kind, such as two faces or two animals, and the deformation of the source is given as meshes. It is the right tool for copying blendshape targets or simulated shape changes to a new character. If the two meshes have the same connectivity, the correspondence is the identity and the method is a short linear solve. If the deformation comes from a skeleton, it is often simpler to copy the skeleton motion and skin the target.
Pitfalls
- Degenerate triangles. A triangle with zero area has no fourth vertex and no inverse frame. Remove such triangles first, or give them a small area.
- Triangles without a pair. A target triangle in no pair has no term in the energy, and if a vertex is only in such triangles, is singular. Give every triangle at least one pair.
- No fixed vertex. Without a fixed vertex or another constraint, is singular, because a translation of all unknowns costs nothing.
- A poor correspondence. Pairs between triangles of different regions copy the wrong change. Check the correspondence by eye on a few strong deformations.
- Large rotations of the target. The source matrices are given in the frame of the source. If the target is posed in a different orientation, align the two meshes first, or the copied changes turn the target the wrong way.
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
deformation_transfer.py 106 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/deformation-transfer/. The authors are listed in prov/CM6PX4.jsonl.
"""Deformation transfer for triangle meshes (Sumner and Popovic 2004).
Each triangle (v1, v2, v3) gets a fourth vertex
v4 = v1 + (v2 - v1) x (v3 - v1) / sqrt(|(v2 - v1) x (v3 - v1)|),
and the frame V = [v2 - v1, v3 - v1, v4 - v1] (columns). The deformation of
a source triangle is the matrix S = V~ V^(-1). For the target, the frames of
the unknown deformed triangles are linear in the unknown vertices (the n
mesh vertices and one fourth vertex per triangle), so the transfer is the
least squares problem
min sum over pairs (t, s) of |V~_t V_t^(-1) - S_s|_F^2,
with one vertex fixed to remove the global translation. The normal matrix
depends only on the target rest mesh; it is factored once and used for the
x, y and z coordinates.
"""
import math
from anim import cross, inv, matvec, mul, norm, solve, sub, transpose
def fourth_vertex(v1, v2, v3):
"""Return v1 + c / sqrt(|c|) with c = (v2 - v1) x (v3 - v1)."""
c = cross(sub(v2, v1), sub(v3, v1))
s = math.sqrt(norm(c))
if s == 0.0:
raise ValueError("degenerate triangle")
return tuple(a + b / s for a, b in zip(v1, c))
def frame(v1, v2, v3):
"""Return the 3 by 3 matrix with the columns v2 - v1, v3 - v1 and v4 - v1."""
v4 = fourth_vertex(v1, v2, v3)
cols = [sub(v2, v1), sub(v3, v1), sub(v4, v1)]
return transpose(cols)
def source_deformations(src_rest, src_def, tris):
"""Return S_s = V~_s V_s^(-1) for every source triangle."""
out = []
for a, b, c in tris: # @line L1
v = frame(src_rest[a], src_rest[b], src_rest[c])
vt = frame(src_def[a], src_def[b], src_def[c])
out.append(mul(vt, inv(v)))
return out
def transfer(tgt_rest, tgt_tris, pairs, s_mats, fixed):
"""Return (vertices, fourth vertices) of the deformed target.
pairs is a list of (target triangle, source triangle) indices; the
correspondence may be many to many. fixed is (vertex index, position).
"""
n = len(tgt_rest)
q = [inv(frame(tgt_rest[a], tgt_rest[b], tgt_rest[c])) for a, b, c in tgt_tris] # @line L2
rows, rhs = [], []
for t, s in pairs: # @line L3
a, b, c = tgt_tris[t]
qt = q[t]
for k in range(3):
coef = {b: qt[0][k], c: qt[1][k], n + t: qt[2][k]}
coef[a] = coef.get(a, 0.0) - (qt[0][k] + qt[1][k] + qt[2][k])
rows.append(coef)
rhs.append(tuple(s_mats[s][r][k] for r in range(3)))
fi, fp = fixed
unknowns = [u for u in range(n + len(tgt_tris)) if u != fi] # @line L4
col = {u: i for i, u in enumerate(unknowns)}
size = len(unknowns)
ata = [[0.0] * size for _ in range(size)]
atb = [[0.0] * 3 for _ in range(size)]
for coef, r in zip(rows, rhs):
r = [r[d] - coef.get(fi, 0.0) * fp[d] for d in range(3)]
items = [(col[u], w) for u, w in coef.items() if u != fi]
for i, wi in items:
for j, wj in items:
ata[i][j] += wi * wj
for d in range(3):
atb[i][d] += wi * r[d]
x = solve(ata, atb) # @line L5
out = []
for v in range(n): # @line L6
out.append(tuple(fp) if v == fi else tuple(x[col[v]]))
fourth = [tuple(x[col[n + t]]) for t in range(len(tgt_tris))]
return out, fourth # @line L7
def energy(tgt_rest, tgt_tris, pairs, s_mats, verts, fourth):
"""Return the transfer energy for target vertices and free fourth vertices."""
e = 0.0
for t, s in pairs:
a, b, c = tgt_tris[t]
qt = inv(frame(tgt_rest[a], tgt_rest[b], tgt_rest[c]))
vt = transpose([sub(verts[b], verts[a]), sub(verts[c], verts[a]), sub(fourth[t], verts[a])])
m = mul(vt, qt)
e += sum((m[i][j] - s_mats[s][i][j]) ** 2 for i in range(3) for j in range(3))
return e
def apply_affine(m, t, p):
"""Return m p + t."""
return tuple(x + y for x, y in zip(matvec(m, p), t))
test_deformation_transfer.py 135 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/deformation-transfer/. The authors are listed in prov/CM6PX4.jsonl.
"""Tests of deformation transfer.
The identity deformation gives the target rest mesh. A similarity motion of
the source moves the target by the same similarity. Transfer onto the source
itself gives the deformed source. The solution has a zero gradient of the
energy and beats random perturbations. The fourth vertex moves exactly under
a similarity. The check value of the page holds.
"""
import math
import random
import anim
from deformation_transfer import (
apply_affine,
energy,
fourth_vertex,
source_deformations,
transfer,
)
def grid(f):
verts = [(float(x), float(y), f(x, y)) for y in range(3) for x in range(3)]
tris = []
for y in range(2):
for x in range(2):
a = 3 * y + x
tris.append((a, a + 1, a + 4))
tris.append((a, a + 4, a + 3))
return verts, tris
SRC, TRIS = grid(lambda x, y: 0.2 * x * y)
TGT, _ = grid(lambda x, y: 0.3 * math.sin(x) - 0.1 * y * y)
TGT = [(1.5 * x, 0.8 * y, z) for x, y, z in TGT]
PAIRS = [(t, t) for t in range(len(TRIS))]
def bend(verts):
out = []
c, s = math.cos(0.6), math.sin(0.6)
for x, y, z in verts:
if x > 1.0:
dx = x - 1.0
out.append((1.0 + c * dx - s * z, y, s * dx + c * z))
else:
out.append((x, y, z))
return out
def rot(rng):
q = anim.q_normalize([rng.gauss(0, 1) for _ in range(4)])
return anim.q_to_mat3(q)
def close(a, b, tol):
return all(abs(x - y) <= tol for p, q in zip(a, b) for x, y in zip(p, q))
def test_identity_gives_the_target_rest_mesh():
s = source_deformations(SRC, SRC, TRIS)
out, _ = transfer(TGT, TRIS, PAIRS, s, (0, TGT[0]))
assert close(out, TGT, 1e-9)
def test_similarity_transfers_exactly():
rng = random.Random(1)
r = rot(rng)
m = [[1.7 * x for x in row] for row in r]
t = (0.3, -1.0, 2.0)
s = source_deformations(SRC, [apply_affine(m, t, p) for p in SRC], TRIS)
out, _ = transfer(TGT, TRIS, PAIRS, s, (4, apply_affine(m, t, TGT[4])))
assert close(out, [apply_affine(m, t, p) for p in TGT], 1e-9)
def test_fourth_vertex_follows_a_similarity():
rng = random.Random(2)
r = rot(rng)
m = [[0.6 * x for x in row] for row in r]
t = (1.0, 2.0, 3.0)
a, b, c = SRC[0], SRC[1], SRC[4]
moved = fourth_vertex(apply_affine(m, t, a), apply_affine(m, t, b), apply_affine(m, t, c))
assert close([moved], [apply_affine(m, t, fourth_vertex(a, b, c))], 1e-12)
def test_self_transfer_gives_the_deformed_source():
d = bend(SRC)
s = source_deformations(SRC, d, TRIS)
out, _ = transfer(SRC, TRIS, PAIRS, s, (0, d[0]))
assert close(out, d, 1e-9)
def test_solution_is_a_minimum():
d = bend(SRC)
s = source_deformations(SRC, d, TRIS)
out, fourth = transfer(TGT, TRIS, PAIRS, s, (0, TGT[0]))
e0 = energy(TGT, TRIS, PAIRS, s, out, fourth)
flat = [c for p in out[1:] + fourth for c in p]
def f(x):
vs = [out[0]] + [tuple(x[3 * i : 3 * i + 3]) for i in range(len(out) - 1)]
k = 3 * (len(out) - 1)
fo = [tuple(x[k + 3 * i : k + 3 * i + 3]) for i in range(len(fourth))]
return energy(TGT, TRIS, PAIRS, s, vs, fo)
g = anim.num_grad(f, flat)
assert max(abs(x) for x in g) < 1e-6
rng = random.Random(3)
for _ in range(30):
assert f([x + rng.gauss(0, 0.01) for x in flat]) >= e0
def test_many_to_many_duplicates_do_not_change_the_result():
d = bend(SRC)
s = source_deformations(SRC, d, TRIS)
a, _ = transfer(TGT, TRIS, PAIRS, s, (0, TGT[0]))
b, _ = transfer(TGT, TRIS, PAIRS + PAIRS, s, (0, TGT[0]))
assert close(a, b, 1e-9)
def test_check_value_of_the_page():
src = [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0)]
dst = [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.5, 1.0, 0.0)]
s = source_deformations(src, dst, [(0, 1, 2)])
want = [[1.0, 0.5, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
assert all(abs(s[0][i][j] - want[i][j]) < 1e-12 for i in range(3) for j in range(3))
tgt = [(0.0, 0.0, 0.0), (2.0, 0.0, 0.0), (0.0, 1.0, 0.0)]
v4 = fourth_vertex(*tgt)
assert abs(v4[2] - math.sqrt(2.0)) < 1e-12
out, fourth = transfer(tgt, [(0, 1, 2)], [(0, 0)], s, (0, tgt[0]))
assert close(out, [(0.0, 0.0, 0.0), (2.0, 0.0, 0.0), (0.5, 1.0, 0.0)], 1e-12)
assert close(fourth, [(0.0, 0.0, math.sqrt(2.0))], 1e-12)
History
Sumner and Popović presented deformation transfer at SIGGRAPH 2004. They introduced the fourth vertex of equation (1) to make the change of a triangle an affine map of space, the many to many correspondence of triangles, and the formulation in the vertex positions with a factorization that depends only on the target. The method came out of the same period as the gradient domain and Laplacian methods of mesh editing, which also prescribe local changes and solve a sparse linear system for the vertices.
References
- Robert W. Sumner and Jovan Popovic, Deformation transfer for triangle meshes, ACM Transactions on Graphics 23(3), SIGGRAPH 2004, 399-405, section 3, equation (1), for the fourth vertex and the per-triangle transformations; section 4 for the formulation in the vertex positions, the factorization that depends only on the target, and the solution up to a translation
Where this leads
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 CM6PX4 Edit this page History Report an error Markdown