Algorithm Search⌘K

Algorithmcore

Beier-Neely morphing

Also called feature-based image metamorphosis, field morphing.

Morph between two images by warping each toward the other with weighted line-segment correspondences and cross-dissolving the warped images.

Time
Θ(n L) worst
Space
Θ(n) extra
Where
L = the number of line pairs; n = the number of pixels of a frame
Properties
deterministicexactofflineiterative

Beier-Neely morphing turns one image into another over a sequence of frames, so that matching features, such as the eyes and the mouth of two faces, move and change shape smoothly instead of fading. The animator draws pairs of matching line segments on the two images. Each frame interpolates the line segments, warps both images so that their lines move to the interpolated positions, and cross-dissolves the two warped images. The warp of each pixel is a weighted average of the maps that each line pair defines on its own, so the whole image moves, not only the pixels on the lines. Thaddeus Beier and Shawn Neely (1992) published the method, which they also call field morphing.

In plain words

Fading one picture into another shows two half-bright pictures on top of each other. A morph also moves the shapes. You draw short lines on the first picture, say along the nose and the eyebrows, and the matching lines on the second picture. Halfway through the morph, the lines are halfway between their two positions. Each picture is then bent so that its lines sit on the halfway lines, and the rest of the picture follows the nearest lines most. The two bent pictures are then mixed. At the start you see only the first picture, at the end only the second, and in between the features slide from one place to the other.

The problem

The input is two images I0I_0 and I1I_1 of the same size, LL pairs of line segments, (Pi0,Qi0)(P^0_i, Q^0_i) in I0I_0 and (Pi1,Qi1)(P^1_i, Q^1_i) in I1I_1, a time t∈[0,1]t \in [0, 1], and three weight parameters a>0a > 0, bb and pp. The output is the frame MtM_t of the morph, an image of the same size. The frame must equal I0I_0 at t=0t = 0 and I1I_1 at t=1t = 1, and the feature that a line marks must be on the interpolated line at time tt. The warp is a reverse map, as in image warping: for each pixel XX of the output, it computes the point X′X' of the input image to read, which leaves no holes in the output.

The algorithm

For a vector d=(dx,dy)d = (d_x, d_y), perp⁡(d)=(−dy,dx)\operatorname{perp}(d) = (-d_y, d_x) is dd turned by 90 degrees. WARP-POINT takes a destination point XX, the destination lines (Pi,Qi)(P_i, Q_i) and the source lines (Pi′,Qi′)(P'_i, Q'_i), and returns the source point X′X'.

  1. WARP-POINT(X, (Pᵢ, Qᵢ), (P'ᵢ, Q'ᵢ), a, b, p) ▷ destination X to source X'
  2. 1D ← 0; W ← 0
  3. 2for each line pair i do
  4. 3u ← (X - Pᵢ) · (Qᵢ - Pᵢ) / |Qᵢ - Pᵢ|²
  5. 4v ← (X - Pᵢ) · perp(Qᵢ - Pᵢ) / |Qᵢ - Pᵢ|
  6. 5Xᵢ' ← P'ᵢ + u (Q'ᵢ - P'ᵢ) + v perp(Q'ᵢ - P'ᵢ) / |Q'ᵢ - P'ᵢ|
  7. 6dist ← |X - Pᵢ| if u ≤ 0, |X - Qᵢ| if u ≥ 1, |v| otherwise
  8. 7w ← (|Qᵢ - Pᵢ|ᵖ / (a + dist))ᵇ
  9. 8D ← D + w (Xᵢ' - X); W ← W + w
  10. 9return X + D / W
  11. MORPH(I₀, I₁, L⁰, L¹, t)
  12. 10Lᵗ ← the lines with the endpoints (1 - t) L⁰ + t L¹
  13. 11for each pixel X do
  14. 12X₀ ← WARP-POINT(X, Lᵗ, L⁰); X₁ ← WARP-POINT(X, Lᵗ, L¹)
  15. 13Mₜ(X) ← (1 - t) I₀(X₀) + t I₁(X₁)
  16. 14return Mₜ

Line L3 gives the position of XX along the destination line, 0 at PiP_i and 1 at QiQ_i. Line L4 gives the signed distance of XX from the line, in pixels. Line L5 puts the point with the same coordinates next to the source line: the position along the line is a fraction of the line, but the distance across the line is kept in pixels. Line L6 is the distance from XX to the segment, and line L7 makes the weight large for long lines and for lines near XX. Line L9 averages the displacements. In line L13, Ik(Xk)I_k(X_k) is read with bilinear interpolation, because XkX_k is not a pixel center in general.

The parameters control the field. A small aa gives precise control: as a→0a \to 0, a pixel on a line follows that line exactly. The exponent bb sets how fast the weight falls with the distance; Beier and Neely found the range [0.5,2][0.5, 2] most useful. The exponent p∈[0,1]p \in [0, 1] sets how much more a long line counts than a short one; with p=0p = 0 all lines count the same.

Example

One line. Let the destination line be P=(0,0)P = (0, 0), Q=(10,0)Q = (10, 0), and the source line P′=(2,1)P' = (2, 1), Q′=(2,21)Q' = (2, 21), which is turned by 90 degrees and twice as long. For X=(5,3)X = (5, 3), line L3 gives u=50/100=0.5u = 50/100 = 0.5 and line L4 gives v=(5,3)⋅(0,10)/10=3v = (5, 3)\cdot(0, 10)/10 = 3. Line L5 gives X′=(2,1)+0.5 (0,20)+3 (−20,0)/20=(−1,11)X' = (2, 1) + 0.5\,(0, 20) + 3\,(-20, 0)/20 = (-1, 11). The point is 5 pixels along the destination line and 10 pixels along the source line, but it is 3 pixels from both lines. One line pair therefore gives a rotation, a translation and a scale along the line only.

Two lines. Take the destination lines from (0,0)(0, 0) to (10,0)(10, 0) and from (0,10)(0, 10) to (10,10)(10, 10). The matching source lines are the first line itself and the line from (0,12)(0, 12) to (10,12)(10, 12), which is moved up by 2. For X=(5,3)X = (5, 3), the first pair gives the displacement (0,0)(0, 0) at the distance 3, and the second gives (0,2)(0, 2) at the distance 7. With a=1a = 1, b=2b = 2 and p=0p = 0, the weights are 1/161/16 and 1/641/64, so X′=(5,3+2⋅1/645/64)=(5,3.4)X' = (5, 3 + 2 \cdot \frac{1/64}{5/64}) = (5, 3.4). With b=1b = 1, the weights are 1/41/4 and 1/81/8, and X′=(5,3.667)X' = (5, 3.667): a smaller bb lets the far line count more.

A moving bar. Let I0I_0 have a bright vertical bar at the column x=2x = 2 and I1I_1 the same bar at x=8x = 8, each marked by one vertical line along the bar. At t=0.5t = 0.5 the interpolated line is at x=5x = 5, both warps move their bar there, and M0.5M_{0.5} has one full-bright bar at x=5x = 5. A plain cross-dissolve at t=0.5t = 0.5 instead shows two half-bright bars, at x=2x = 2 and at x=8x = 8.

Correctness

At t=0t = 0, line L10 gives Lt=L0L^t = L^0, and the warp of I0I_0 from L0L^0 to itself is the identity: for each line, L5 rebuilds XX from its coordinates uu and vv, so every displacement in line L8 is 0. The weight of I1I_1 in line L13 is 0, so M0=I0M_0 = I_0; in the same way M1=I1M_1 = I_1.

For one line pair, lines L3 to L5 write XX in the orthogonal frame of the destination line, with the unit vector across the line, and rebuild it in the frame of the source line, with the coordinate along the line scaled by ∣Q′−P′∣/∣Q−P∣|Q' - P'|/|Q - P|. So the map is a rotation, a translation and a scale along the line, and it takes PP to P′P' and QQ to Q′Q'.

If all line pairs are related by the same rigid motion, each Xi′X'_i of line L5 is that motion applied to XX, and so is their weighted average. A point on the segment ii has dist=0\text{dist} = 0, so as a→0a \to 0 its weight grows without bound and the result tends to Xi′X'_i, the matching point on the source segment. The proof gives the details.

The method has no guarantee that the warp is one-to-one. With several lines, the averaged field can fold over itself, and a pixel of the source can then appear twice in the output.

Proof: The Beier-Neely warp reproduces its lines and rigid motions, and the morph starts and ends at the input imagesfull

We use the notation of the page. For a line (P,Q)(P, Q) with d=Q−P≠0d = Q - P \ne 0, let d^=d/∣d∣\hat d = d/|d| and n^=perp⁡(d^)\hat n = \operatorname{perp}(\hat d). The pair (d^,n^)(\hat d, \hat n) is an orthonormal basis of the plane with the same orientation as the standard basis, because perp⁡\operatorname{perp} is the rotation by 90 degrees.

One line pair

Lemma 1. For one line, lines L3 and L4 give u=(X−P)⋅d^/∣d∣u = (X - P)\cdot\hat d/|d| and v=(X−P)⋅n^v = (X - P)\cdot\hat n, and X=P+u d+v n^X = P + u\,d + v\,\hat n.

Proof. The first two equations are lines L3 and L4 with perp⁡(d)=∣d∣ n^\operatorname{perp}(d) = |d|\,\hat n. Since (d^,n^)(\hat d, \hat n) is orthonormal, X−P=((X−P)⋅d^) d^+((X−P)⋅n^) n^=u d+v n^X - P = ((X - P)\cdot\hat d)\,\hat d + ((X - P)\cdot\hat n)\,\hat n = u\,d + v\,\hat n. □\square

Lemma 2. For one line pair, with e=Q′−P′e = Q' - P', e^=e/∣e∣\hat e = e/|e| and m^=perp⁡(e^)\hat m = \operatorname{perp}(\hat e), line L5 is the map X′=P′+R S (X−P)X' = P' + R\,S\,(X - P), where RR is the rotation that takes d^\hat d to e^\hat e and SS scales the direction d^\hat d by ∣e∣/∣d∣|e|/|d| and fixes the direction n^\hat n. It takes PP to P′P' and QQ to Q′Q'.

Proof. Line L5 is X′=P′+u e+v m^=P′+(u∣d∣)∣e∣∣d∣e^+v m^X' = P' + u\,e + v\,\hat m = P' + (u|d|)\frac{|e|}{|d|}\hat e + v\,\hat m. By Lemma 1, u∣d∣u|d| and vv are the coordinates of X−PX - P in the basis (d^,n^)(\hat d, \hat n). SS multiplies the first coordinate by ∣e∣/∣d∣|e|/|d|, and RR maps d^\hat d to e^\hat e and, being a rotation, n^=perp⁡(d^)\hat n = \operatorname{perp}(\hat d) to perp⁡(e^)=m^\operatorname{perp}(\hat e) = \hat m. For X=PX = P, u=v=0u = v = 0 and X′=P′X' = P'; for X=QX = Q, u=1u = 1, v=0v = 0 and X′=P′+e=Q′X' = P' + e = Q'. □\square

Corollary. If the destination and source lines are the same, line L5 gives Xi′=XX'_i = X, by Lemma 1.

Several line pairs

Let wi>0w_i > 0 be the weights of line L7 and Xi′X'_i the points of line L5. When the sum of line L9 is reached, X′=X+∑iwi(Xi′−X)/∑iwi=∑iwiXi′/∑iwiX' = X + \sum_i w_i(X'_i - X)/\sum_i w_i = \sum_i w_iX'_i/\sum_i w_i, a convex combination of the Xi′X'_i.

Lemma 3. If there is a map gg with Xi′=g(X)X'_i = g(X) for every ii, then the warp returns g(X)g(X), whatever the weights.

Proof. A convex combination of equal points is that point. □\square

Theorem 1. If the same lines are used as destination and source, the warp is the identity. If every source line is the image of its destination line under one rigid motion g(X)=RX+cg(X) = RX + c, the warp is gg.

Proof. The first claim follows from the corollary and Lemma 3. For the second, ei=Rdie_i = Rd_i and ∣ei∣=∣di∣|e_i| = |d_i|, so S=IS = I in Lemma 2, and the rotation that takes d^i\hat d_i to e^i=Rd^i\hat e_i = R\hat d_i is RR. So Xi′=Pi′+R(X−Pi)=RPi+c+RX−RPi=g(X)X'_i = P'_i + R(X - P_i) = RP_i + c + RX - RP_i = g(X) for every ii, and Lemma 3 applies. □\square

Lemma 4. The value dist\text{dist} of line L6 is the distance from XX to the segment PiQiP_iQ_i.

Proof. The closest point of the line to XX is Pi+u diP_i + u\,d_i, at the distance ∣v∣|v|, by Lemma 1. If 0<u<10 < u < 1, this point is on the segment. If u≤0u \le 0, the distance to the points Pi+s diP_i + s\,d_i with s∈[0,1]s \in [0, 1] is (u−s)2∣di∣2+v2\sqrt{(u - s)^2|d_i|^2 + v^2}, which is smallest at s=0s = 0, so the distance is ∣X−Pi∣|X - P_i|; the case u≥1u \ge 1 is the same with s=1s = 1. □\square

Theorem 2. Let XX be a point of the segment PkQkP_kQ_k that is not on any other destination segment. As a→0a \to 0, the warp of XX tends to Xk′X'_k, the point at the same fraction uu of the source segment Pk′Qk′P'_kQ'_k. For a=0a = 0 the implementation returns Xk′X'_k.

Proof. By Lemma 4, distk=0\text{dist}_k = 0 and disti>0\text{dist}_i > 0 for i≠ki \ne k. For b>0b > 0, wk=(∣dk∣p/a)b→∞w_k = (|d_k|^p/a)^b \to \infty as a→0a \to 0, and the other weights stay bounded. So the convex combination tends to Xk′X'_k. On the segment v=0v = 0, so Xk′=Pk′+u ekX'_k = P'_k + u\,e_k by line L5. For a=0a = 0, the implementation returns Xk′X'_k as soon as it meets a line with a+dist=0a + \text{dist} = 0. □\square

The morph

Theorem 3. M0=I0M_0 = I_0 and M1=I1M_1 = I_1.

Proof. At t=0t = 0, line L10 gives L0L^0, so the warp of line L12 for I0I_0 has the same destination and source lines and returns X0=XX_0 = X by Theorem 1. Bilinear interpolation at a pixel center returns the pixel value, and line L13 has the weight 1 for I0I_0 and 0 for I1I_1. The case t=1t = 1 is the same with the roles of the images exchanged. □\square

Theorem 4. Swapping I0I_0 with I1I_1 and L0L^0 with L1L^1, and replacing tt by 1−t1 - t, gives the same frame.

Proof. The interpolated lines of line L10 are (1−(1−t))L1+(1−t)L0=(1−t)L0+tL1(1 - (1 - t))L^1 + (1 - t)L^0 = (1 - t)L^0 + tL^1, the same as before. So the two warps of line L12 are the same, and line L13 gives t I1(X1)+(1−t) I0(X0)t\,I_1(X_1) + (1 - t)\,I_0(X_0), the same value. □\square

No claim is made that the warp is one-to-one; with several lines it need not be.

Complexity

WARP-POINT costs Θ(L)\Theta(L), a fixed amount of arithmetic per line pair. A frame calls it twice per pixel, so it costs Θ(nL)\Theta(nL) for nn pixels, plus Θ(n)\Theta(n) for the bilinear reads and the dissolve. The output frame needs Θ(n)\Theta(n) memory. Beier and Neely report that the cost is proportional to the product of the number of lines and the number of pixels, and that a frame of 720 by 486 pixels with 100 lines took about 2 minutes on an SGI 4D25. Each pixel is independent of the others, so the method runs well in parallel, as on a GPU.

Properties

  • Ends are exact. The first frame is I0I_0 and the last frame is I1I_1.
  • Global control. Every line affects every pixel, with a weight that falls with the distance. There is no mesh and no triangulation.
  • Not one-to-one. The field can fold or tear, mainly where lines are close and point in different directions.
  • Reverse mapping. Every output pixel gets a value, so there are no holes.
  • Linear in tt only for the lines. The endpoints move linearly, but a pixel between lines need not move on a straight path or at a constant speed.
  • Symmetric. Both images are warped to the same intermediate lines, so swapping the images and replacing tt by 1−t1 - t gives the same frame.

Variants and improvements

  • Interpolating center, orientation and length. Interpolating the endpoints of a line that turns shortens it in the middle of the morph. Interpolating the center, the angle and the length of each line keeps the length and turns the line, as Beier and Neely suggest.
  • Mesh warping. A grid of control points on each image, interpolated with splines, gives a warp that is cheaper per pixel and easier to keep one-to-one, but the grid is harder to draw.
  • Triangulated warps. A Delaunay triangulation of matching feature points gives a piecewise affine warp, one affine map per triangle, which is fast on graphics hardware.
  • Scattered data interpolation. Radial basis functions or thin plate splines on matching points give a smooth global field, like the field of the lines.
  • Separate timing. The warp and the dissolve can use different curves of tt, for example an ease curve for the motion and a later dissolve, or a different time for each region of the image.
  • Shape interpolation. For the outlines of shapes, as-rigid-as-possible shape interpolation interpolates a triangulation of the shape and avoids the shrinking of linear paths.

When to use it

Use Beier-Neely morphing to turn one photograph or drawing into another when the features can be marked by a few lines, such as faces, animals or objects of similar shape. It is easy for an artist to control, because each line says where one feature goes. For a warp that must be one-to-one, or for many correspondences, mesh or triangle warps are safer and faster. For the shape of an object in an animation, with no image, use a shape interpolation method instead.

Pitfalls

  • Ghosts. If the lines do not mark a feature well, parts of both images show in the same frame at different places. Add lines near the ghosts.
  • Folds. Lines that are close together and point in different directions make the field fold over, which shows features twice. Keep lines apart or make bb larger.
  • Too few lines. One line pair can only rotate, translate and stretch along the line. A uniform scale or a shear needs several lines.
  • A tiny aa. With aa near 0, the weight of a line is very large next to it, and the field can change abruptly close to the lines.
  • Different image content. The dissolve mixes colors, so features that exist in only one image fade in or out, whatever the lines do.
  • Edges of the image. The warp can ask for source points outside the image. Clamp them, as the implementation does, or pad the image.

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.

beier_neely_morphing.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/beier-neely-morphing/. The authors are listed in prov/QXNMEN.jsonl.
"""Feature-based image metamorphosis (Beier and Neely 1992).

Points are (x, y) tuples, with x the column and y the row of a pixel. An
image is a list of rows of numbers. A line is a pair (P, Q) of points. The
warp is a reverse map: for each pixel X of the destination image, it finds the
point X' of the source image to sample. Line i of the destination is
(P_i, Q_i) and the matching line of the source is (P'_i, Q'_i). For one line,

    u = (X - P) . (Q - P) / |Q - P|^2,
    v = (X - P) . perp(Q - P) / |Q - P|,
    X' = P' + u (Q' - P') + v perp(Q' - P') / |Q' - P'|,

where perp(x, y) = (-y, x). For several lines, the displacements X'_i - X are
averaged with the weights (length^p / (a + dist))^b, where dist is the
distance from X to the segment P_i Q_i. A morph at the time t interpolates
the line endpoints, warps both images to the interpolated lines and
cross-dissolves the two warped images.
"""

import math


def perp(v):
    """Return v turned by 90 degrees, with the same length."""
    return (-v[1], v[0])


def _sub(a, b):
    return (a[0] - b[0], a[1] - b[1])


def _dot(a, b):
    return a[0] * b[0] + a[1] * b[1]


def warp_point(x, dst_lines, src_lines, a=1e-3, b=1.0, p=0.0):
    """Return the source point X' for the destination point x.

    dst_lines and src_lines are lists of matching lines (P, Q). a > 0
    keeps the weights finite; with a = 0 a point on a line maps exactly
    to the matching point of the source line.
    """
    if len(dst_lines) != len(src_lines) or not dst_lines:
        raise ValueError("need the same positive number of destination and source lines")
    dx = dy = 0.0  # @line L1
    wsum = 0.0
    for (p0, q0), (p1, q1) in zip(dst_lines, src_lines):  # @line L2
        d = _sub(q0, p0)
        dd = _dot(d, d)
        if dd == 0.0:
            raise ValueError("a destination line has zero length")
        e = _sub(q1, p1)
        ee = math.sqrt(_dot(e, e))
        if ee == 0.0:
            raise ValueError("a source line has zero length")
        xp = _sub(x, p0)
        length = math.sqrt(dd)
        u = _dot(xp, d) / dd  # @line L3
        v = _dot(xp, perp(d)) / length  # @line L4
        pe = perp(e)
        xs = (p1[0] + u * e[0] + v * pe[0] / ee, p1[1] + u * e[1] + v * pe[1] / ee)  # @line L5
        if u <= 0.0:  # @line L6
            dist = math.sqrt(_dot(xp, xp))
        elif u >= 1.0:
            xq = _sub(x, q0)
            dist = math.sqrt(_dot(xq, xq))
        else:
            dist = abs(v)
        if a + dist == 0.0:
            return xs
        w = (length**p / (a + dist)) ** b  # @line L7
        dx += w * (xs[0] - x[0])  # @line L8
        dy += w * (xs[1] - x[1])
        wsum += w
    return (x[0] + dx / wsum, x[1] + dy / wsum)  # @line L9


def sample_bilinear(img, x, y):
    """Bilinear sample of img at (x, y), with the coordinates clamped to the image."""
    h, w = len(img), len(img[0])
    x = min(max(x, 0.0), w - 1.0)
    y = min(max(y, 0.0), h - 1.0)
    x0, y0 = min(int(x), w - 2) if w > 1 else 0, min(int(y), h - 2) if h > 1 else 0
    fx, fy = x - x0, y - y0
    x1, y1 = min(x0 + 1, w - 1), min(y0 + 1, h - 1)
    top = (1 - fx) * img[y0][x0] + fx * img[y0][x1]
    bottom = (1 - fx) * img[y1][x0] + fx * img[y1][x1]
    return (1 - fy) * top + fy * bottom


def warp_image(src, src_lines, dst_lines, a=1e-3, b=1.0, p=0.0):
    """Return the image of the size of src whose lines dst_lines show the features of src_lines in src."""
    h, w = len(src), len(src[0])
    out = []
    for yy in range(h):
        row = []
        for xx in range(w):
            sx, sy = warp_point((float(xx), float(yy)), dst_lines, src_lines, a, b, p)
            row.append(sample_bilinear(src, sx, sy))
        out.append(row)
    return out


def interpolate_lines(lines0, lines1, t):
    """Return the lines with the endpoints (1 - t) L0 + t L1."""
    out = []
    for (p0, q0), (p1, q1) in zip(lines0, lines1):
        out.append(
            (
                ((1 - t) * p0[0] + t * p1[0], (1 - t) * p0[1] + t * p1[1]),
                ((1 - t) * q0[0] + t * q1[0], (1 - t) * q0[1] + t * q1[1]),
            )
        )
    return out


def morph(img0, img1, lines0, lines1, t, a=1e-3, b=1.0, p=0.0):
    """Return the frame of the morph from img0 to img1 at the time t in [0, 1]."""
    if len(img0) != len(img1) or len(img0[0]) != len(img1[0]):
        raise ValueError("the two images must have the same size")
    lines_t = interpolate_lines(lines0, lines1, t)  # @line L10
    h, w = len(img0), len(img0[0])
    out = []
    for yy in range(h):  # @line L11
        row = []
        for xx in range(w):
            x = (float(xx), float(yy))
            s0 = warp_point(x, lines_t, lines0, a, b, p)  # @line L12
            s1 = warp_point(x, lines_t, lines1, a, b, p)
            c0 = sample_bilinear(img0, s0[0], s0[1])
            c1 = sample_bilinear(img1, s1[0], s1[1])
            row.append((1 - t) * c0 + t * c1)  # @line L13
        out.append(row)
    return out  # @line L14
test_beier_neely_morphing.py 172 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/beier-neely-morphing/. The authors are listed in prov/QXNMEN.jsonl.
import math
import random

import pytest

from beier_neely_morphing import (
    interpolate_lines,
    morph,
    sample_bilinear,
    warp_image,
    warp_point,
)


def close(p, q, tol):
    return math.hypot(p[0] - q[0], p[1] - q[1]) < tol


def random_point(rng, lo=0.0, hi=20.0):
    return (rng.uniform(lo, hi), rng.uniform(lo, hi))


def random_image(rng, h, w):
    return [[rng.random() for _ in range(w)] for _ in range(h)]


def one_line_reference(x, p, q, p2, q2):
    # Reference: rotate by the angle between the lines, scale along the line by the ratio
    # of the lengths, keep the distance across the line, as a matrix product.
    d, e = (q[0] - p[0], q[1] - p[1]), (q2[0] - p2[0], q2[1] - p2[1])
    ld, le = math.hypot(*d), math.hypot(*e)
    dh = (d[0] / ld, d[1] / ld)
    nh = (-dh[1], dh[0])
    rel = (x[0] - p[0], x[1] - p[1])
    along = (rel[0] * dh[0] + rel[1] * dh[1]) * le / ld
    across = rel[0] * nh[0] + rel[1] * nh[1]
    ang = math.atan2(e[1], e[0]) - math.atan2(d[1], d[0])
    c, s = math.cos(ang), math.sin(ang)
    local = (along * dh[0] + across * nh[0], along * dh[1] + across * nh[1])
    return (p2[0] + c * local[0] - s * local[1], p2[1] + s * local[0] + c * local[1])


def test_one_line_is_rotation_translation_and_stretch_along_the_line(rng=random.Random(1)):
    for _ in range(50):
        p, q, p2, q2 = (random_point(rng) for _ in range(4))
        for _ in range(5):
            x = random_point(rng, -10, 30)
            assert close(warp_point(x, [(p, q)], [(p2, q2)]), one_line_reference(x, p, q, p2, q2), 1e-9)


def test_same_lines_give_the_identity(rng=random.Random(2)):
    lines = [(random_point(rng), random_point(rng)) for _ in range(4)]
    for _ in range(50):
        x = random_point(rng)
        assert close(warp_point(x, lines, lines), x, 1e-10)


def test_common_rigid_motion_is_reproduced(rng=random.Random(3)):
    ang, tx, ty = 0.8, 3.0, -2.0
    c, s = math.cos(ang), math.sin(ang)

    def m(z):
        return (c * z[0] - s * z[1] + tx, s * z[0] + c * z[1] + ty)

    dst = [(random_point(rng), random_point(rng)) for _ in range(5)]
    src = [(m(pp), m(qq)) for pp, qq in dst]
    for _ in range(50):
        x = random_point(rng)
        assert close(warp_point(x, dst, src, a=0.5, b=1.5, p=0.5), m(x), 1e-9)


def test_weights_against_a_direct_sum(rng=random.Random(4)):
    dst = [(random_point(rng), random_point(rng)) for _ in range(3)]
    src = [(random_point(rng), random_point(rng)) for _ in range(3)]
    a, b, p = 0.7, 1.3, 0.6
    for _ in range(30):
        x = random_point(rng)
        num, den = [0.0, 0.0], 0.0
        for (p0, q0), (p1, q1) in zip(dst, src):
            xi = warp_point(x, [(p0, q0)], [(p1, q1)])
            # Distance to the segment by dense sampling of the segment.
            dist = min(math.hypot(x[0] - (p0[0] + k / 4000 * (q0[0] - p0[0])), x[1] - (p0[1] + k / 4000 * (q0[1] - p0[1]))) for k in range(4001))
            w = (math.hypot(q0[0] - p0[0], q0[1] - p0[1]) ** p / (a + dist)) ** b
            num[0] += w * (xi[0] - x[0])
            num[1] += w * (xi[1] - x[1])
            den += w
        ref = (x[0] + num[0] / den, x[1] + num[1] / den)
        assert close(warp_point(x, dst, src, a, b, p), ref, 1e-3)


def test_a_zero_gives_exact_control_on_the_lines(rng=random.Random(5)):
    dst = [(random_point(rng), random_point(rng)) for _ in range(3)]
    src = [(random_point(rng), random_point(rng)) for _ in range(3)]
    for (p0, q0), (p1, q1) in zip(dst, src):
        for f in (0.0, 0.25, 0.6, 1.0):
            x = (p0[0] + f * (q0[0] - p0[0]), p0[1] + f * (q0[1] - p0[1]))
            target = (p1[0] + f * (q1[0] - p1[0]), p1[1] + f * (q1[1] - p1[1]))
            got = warp_point(x, dst, src, a=0.0, b=1.0, p=0.0)
            # x is on the line up to roundoff, so the weight of its line is huge.
            assert close(got, target, 1e-6)


def test_bilinear_sampler(rng=random.Random(6)):
    img = random_image(rng, 5, 7)
    for yy in range(5):
        for xx in range(7):
            assert sample_bilinear(img, xx, yy) == pytest.approx(img[yy][xx], abs=1e-15)
    x, y = 2.25, 3.5
    ref = 0.5 * (0.75 * img[3][2] + 0.25 * img[3][3]) + 0.5 * (0.75 * img[4][2] + 0.25 * img[4][3])
    assert sample_bilinear(img, x, y) == pytest.approx(ref)
    assert sample_bilinear(img, -3.0, 10.0) == pytest.approx(img[4][0])


def test_integer_translation_shifts_the_image(rng=random.Random(7)):
    img = random_image(rng, 10, 12)
    src = [((2.0, 3.0), (8.0, 4.0)), ((1.0, 7.0), (5.0, 9.0))]
    dst = [((pp[0] + 2, pp[1] + 1), (qq[0] + 2, qq[1] + 1)) for pp, qq in src]
    out = warp_image(img, src, dst)
    for yy in range(1, 10):
        for xx in range(2, 12):
            assert out[yy][xx] == pytest.approx(img[yy - 1][xx - 2], abs=1e-9)


def test_morph_ends_are_the_input_images(rng=random.Random(8)):
    img0, img1 = random_image(rng, 9, 11), random_image(rng, 9, 11)
    lines0 = [((2.0, 2.0), (8.0, 3.0)), ((3.0, 7.0), (6.0, 5.0))]
    lines1 = [((1.0, 3.0), (9.0, 2.0)), ((4.0, 8.0), (7.0, 4.0))]
    for t, img in ((0.0, img0), (1.0, img1)):
        out = morph(img0, img1, lines0, lines1, t)
        for r_out, r_img in zip(out, img):
            for u, v in zip(r_out, r_img):
                assert abs(u - v) < 1e-9


def test_morph_of_an_image_with_itself_is_constant(rng=random.Random(9)):
    img = random_image(rng, 8, 8)
    lines = [((1.0, 1.0), (6.0, 2.0)), ((2.0, 6.0), (6.0, 6.0))]
    out = morph(img, img, lines, lines, 0.37)
    for r_out, r_img in zip(out, img):
        for u, v in zip(r_out, r_img):
            assert abs(u - v) < 1e-9


def test_midway_feature_is_between_the_two_positions():
    # A bright column at x = 2 in img0 and at x = 8 in img1, marked by a vertical line in each.
    h, w = 9, 11
    img0 = [[1.0 if xx == 2 else 0.0 for xx in range(w)] for _ in range(h)]
    img1 = [[1.0 if xx == 8 else 0.0 for xx in range(w)] for _ in range(h)]
    lines0 = [((2.0, 0.0), (2.0, 8.0))]
    lines1 = [((8.0, 0.0), (8.0, 8.0))]
    mid = morph(img0, img1, lines0, lines1, 0.5)
    for row in mid:
        assert row[5] == pytest.approx(1.0, abs=1e-9)
        assert max(abs(v) for i, v in enumerate(row) if i != 5) < 1e-9
    # A plain cross-dissolve shows two half-bright ghosts instead.
    dissolve = [[0.5 * u + 0.5 * v for u, v in zip(r0, r1)] for r0, r1 in zip(img0, img1)]
    assert dissolve[0][2] == 0.5 and dissolve[0][8] == 0.5 and dissolve[0][5] == 0.0


def test_interpolate_lines():
    lines = interpolate_lines([((0.0, 0.0), (2.0, 0.0))], [((4.0, 2.0), (4.0, 6.0))], 0.25)
    assert lines[0][0] == pytest.approx((1.0, 0.5))
    assert lines[0][1] == pytest.approx((2.5, 1.5))


def test_bad_input():
    with pytest.raises(ValueError):
        warp_point((0.0, 0.0), [((0.0, 0.0), (0.0, 0.0))], [((0.0, 0.0), (1.0, 0.0))])
    with pytest.raises(ValueError):
        warp_point((0.0, 0.0), [], [])

History

Beier and Neely developed the method at Pacific Data Images and published it at SIGGRAPH 92. It became widely known through the morphing of faces in the music video for "Black or White" (1991). Earlier morphs, such as the effects in the film Willow (1988), used mesh warping, with a grid of control points on each image. The field of line segments made the correspondence easier to specify, at a higher cost per pixel.

References

  1. Thaddeus Beier and Shawn Neely, Feature-based image metamorphosis, SIGGRAPH 92, Computer Graphics 26(2), 35-42, 1992, Section 3.2 (one line pair, equations 1 to 3), Section 3.3 (several line pairs and the weights), Section 3.4 (the morph), Section 3.5 (the cost) and Section 4 (ghosts and other problems)
  2. Rick Parent, Computer Animation, Algorithms and Techniques, 3rd edition, Morgan Kaufmann, 2012, Chapter 4, Section 4.5 (morphing in 2D, with the feature-based method)

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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • History with a source
  • at least three sources
  • a scene preset for the example