Algorithm Search⌘K

Algorithmadvanced

Closed-form matting

Also called Levin-Lischinski-Weiss matting, matting Laplacian.

Find a soft alpha matte from a few scribbles. Alpha is affine in the color in each small window, so F and B drop out and alpha solves one sparse linear system.

Time
O(W^3 H^3) worst · averageO(W^2 H^2) best
Space
O(W^2 H^2) extra
Where
H = the image height in pixels; W = the image width in pixels
Properties
deterministicexactglobal optimuminteractivesoft output
Origin
Anat Levin, Dani Lischinski, Yair Weiss, 2006

Closed-form matting is an algorithm that computes a soft alpha matte from a few strokes that the user paints on the foreground and on the background. It assumes that in each small window, alpha is an affine function of the color. With this model the unknown foreground and background colors drop out, and the matte minimizes a quadratic cost αTLα\alpha^T L \alpha, where LL is the matting Laplacian. With alpha fixed on the strokes, the minimum is the solution of one sparse linear system. This page covers the derivation, the solve and the properties of LL. The general problem, with the compositing equation and other methods, is on image matting.

In plain words

A photo of hair or smoke has pixels that are part foreground and part background. Matting finds, for each pixel, how much of it is foreground. That share is called alpha.

The user paints a few white strokes on the foreground and a few black strokes on the background. The method assumes that in each tiny patch of the image, alpha follows the color in a simple straight-line way. Within a patch, a brighter pixel is a bit more foreground, or a bit less, by a fixed rate.

These patches overlap, so the rule passes the painted values from patch to patch across the image. The best alpha for all patches at once comes from one large set of linear equations. No guess of the true foreground and background colors is needed.

The problem

The input is an image II with N=WHN = WH pixels and colors Ii∈RcI_i \in \mathbb R^c (c=1c = 1 for gray, c=3c = 3 for color), a set SS of scribbled pixels with values sis_i (1 for foreground, 0 for background), and a small ϵ>0\epsilon > 0. The output is a matte α∈RN\alpha \in \mathbb R^N with αi=si\alpha_i = s_i on SS.

The image model is the compositing equation Ii=αiFi+(1−αi)BiI_i = \alpha_i F_i + (1 - \alpha_i) B_i (Levin, Lischinski and Weiss 2006, equation 1). For a gray image where FF and BB are about constant on a small window ww, it gives

αi≈aIi+b,a=1F−B,b=−BF−B,i∈w.\alpha_i \approx a I_i + b, \qquad a = \frac{1}{F - B}, \quad b = -\frac{B}{F - B}, \qquad i \in w .

For color, the model is αi≈aTIi+b\alpha_i \approx a^T I_i + b (equation 9). The cost is (equations 3 and 10)

J(α,a,b)=∑k(∑i∈wk(αi−akTIi−bk)2+ϵ∥ak∥2),J(\alpha, a, b) = \sum_k \Bigl( \sum_{i \in w_k} \bigl(\alpha_i - a_k^T I_i - b_k\bigr)^2 + \epsilon \lVert a_k \rVert^2 \Bigr),

with one 3×33 \times 3 window wkw_k around each pixel kk. The term ϵ∥ak∥2\epsilon \lVert a_k \rVert^2 makes the problem well posed in flat windows and prefers smooth mattes.

The algorithm

Theorem 1 of the paper eliminates aa and bb: min⁡a,bJ(α,a,b)=αTLα\min_{a, b} J(\alpha, a, b) = \alpha^T L \alpha, with

Lij=∑k:i,j∈wk(δij−1∣wk∣(1+(Ii−μk)T(Σk+ϵ∣wk∣Id)−1(Ij−μk))),L_{ij} = \sum_{k : i, j \in w_k} \Bigl( \delta_{ij} - \frac{1}{|w_k|}\Bigl(1 + (I_i - \mu_k)^T \bigl(\Sigma_k + \tfrac{\epsilon}{|w_k|} \mathrm{Id}\bigr)^{-1} (I_j - \mu_k)\Bigr) \Bigr),

where μk\mu_k and Σk\Sigma_k are the mean and the covariance of the colors in wkw_k (equation 12; equation 5 is the gray case). The matte is (equation 13)

α=arg⁡min⁡ααTLαsubject toαi=si for i∈S.\alpha = \arg\min_\alpha \alpha^T L \alpha \quad \text{subject to} \quad \alpha_i = s_i \text{ for } i \in S .
  1. CLOSED-FORM-MATTING(I, S, s, ε)
  2. 1L ← the N × N zero matrix ▷ sparse in practice
  3. 2for each 3 × 3 window w_k inside the image do
  4. 3μ_k ← mean of I over w_k; Σ_k ← covariance of I over w_k
  5. 4M_k ← (Σ_k + ε / |w_k| · Id)⁻¹ ▷ a c × c inverse
  6. 5for each i, j in w_k do L_ij ← L_ij + δ_ij - (1 + (I_i - μ_k)ᵀ M_k (I_j - μ_k)) / |w_k|
  7. 6U ← the pixels not in S
  8. 7solve L_UU α_U = -L_US s
  9. 8α_S ← s; return α

Lines L6 to L8 set the gradient of αTLα\alpha^T L \alpha to zero on the free pixels, which solves equation 13 exactly. Many implementations use a soft form instead, with a large weight on the scribbles; as the weight grows, its solution tends to the hard one.

Example

Take a gray image of 3 rows, each with the values 0.1,0.2,0.5,0.9,0.90.1, 0.2, 0.5, 0.9, 0.9. This is a blurred edge between a background of B=0.1B = 0.1 and a foreground of F=0.9F = 0.9. The left column is scribbled as 00 and the right column as 11. The true matte is α=(I−0.1)/0.8=0,0.125,0.5,1,1\alpha = (I - 0.1)/0.8 = 0, 0.125, 0.5, 1, 1 in each row. It is an affine function of II in every window, so Theorem 3 of the paper says it is optimal for ϵ=0\epsilon = 0. The middle row of the result:

ϵ\epsilon col 0 col 1 col 2 col 3 col 4
10−610^{-6} 0 0.1250 0.5000 1.0000 1
0.10.1 0 0.2295 0.5120 0.8615 1

With a small ϵ\epsilon the method finds the true matte. With a large ϵ\epsilon the term ϵa2\epsilon a^2 pulls each window toward a flat alpha, and the matte gets smoother than the truth. The test file checks both rows.

Correctness

The full proof is in proofs/correctness.md. The facts that are proved:

  • Theorem (elimination). In each window, the minimum over (a,b)(a, b) is a ridge regression, and its value is αTLwα\alpha^T L_{w} \alpha. Summing over the windows gives min⁡a,bJ=αTLα\min_{a,b} J = \alpha^T L \alpha. This is Theorem 1 of the paper.
  • Theorem (shape of LL). LL is symmetric and positive semidefinite, and each row sums to 00. For ϵ>0\epsilon > 0 its null space is exactly the constant vectors. The paper calls LL positive definite, but L1=0L \mathbf 1 = 0, so it is only semidefinite.
  • Theorem (unique matte). For ϵ>0\epsilon > 0 and at least one scribble, LUUL_{UU} is positive definite, so line L7 has exactly one solution, and it is the minimizer of equation 13.
  • Theorem (exact recovery). If alpha is affine in the color in each window, the scribbles agree with it, and ϵ=0\epsilon = 0, then the true alpha is a minimizer. This is Theorem 3 of the paper. Its Theorem 2 shows that the affine model holds when the foreground and the background colors of each window each lie on a line in color space.

The method has no maximum principle. The matte can leave [0,1][0, 1], and the test file has such a case. In practice the result is clipped to [0,1][0, 1].

Proof: Correctness of closed-form mattingfull

This proof covers lines L1 to L8 of the main page. The image has NN pixels, each with a vector Ii∈RcI_i \in \mathbb R^c (c=1c = 1 for gray, c=3c = 3 for color). The windows wkw_k are the 3×33 \times 3 windows that lie inside the image, so each has m=∣wk∣=9m = |w_k| = 9 pixels. The image has at least 3 rows and 3 columns, so there is at least one window. The parameter is ϵ≥0\epsilon \ge 0. For a window, μk\mu_k is the mean of the IiI_i, and Σk=1m∑i∈wk(Ii−μk)(Ii−μk)T\Sigma_k = \frac1m \sum_{i \in w_k} (I_i - \mu_k)(I_i - \mu_k)^T is the covariance. The cost of Levin, Lischinski and Weiss (equations 3 and 10 of the CVPR paper) is

J(α,a,b)=∑k(∑i∈wk(αi−akTIi−bk)2+ϵ∥ak∥2).J(\alpha, a, b) = \sum_k \Bigl( \sum_{i \in w_k} (\alpha_i - a_k^T I_i - b_k)^2 + \epsilon \lVert a_k \rVert^2 \Bigr).

When ϵ=0\epsilon = 0, assume that each Σk\Sigma_k is nonsingular, so that line L4 is defined.

Lemma 1 (one window)

Fix a window ww with mm pixels, and let CC be the m×cm \times c matrix with rows ci=(Ii−μ)Tc_i = (I_i - \mu)^T. Let M=(Σ+ϵmId)−1M = (\Sigma + \frac{\epsilon}{m} \mathrm{Id})^{-1}. For each vector α\alpha on the window,

min⁡a,b(∑i∈w(αi−aTIi−b)2+ϵ∥a∥2)=αTLwα,(Lw)ij=δij−1m(1+ciTMcj).\min_{a, b} \Bigl( \sum_{i \in w} (\alpha_i - a^T I_i - b)^2 + \epsilon \lVert a \rVert^2 \Bigr) = \alpha^T L_w \alpha, \qquad (L_w)_{ij} = \delta_{ij} - \frac{1}{m}\bigl(1 + c_i^T M c_j\bigr).

Proof. For a fixed aa, the cost is a sum of squares in bb, and its minimizer is the mean b=αˉ−aTμb = \bar\alpha - a^T \mu, with αˉ=1m∑iαi\bar\alpha = \frac1m \sum_i \alpha_i. Put this back and write α~=α−αˉ1\tilde\alpha = \alpha - \bar\alpha \mathbf 1. The cost becomes

∥α~−Ca∥2+ϵ∥a∥2.\lVert \tilde\alpha - C a \rVert^2 + \epsilon \lVert a \rVert^2 .

Since CTC=mΣC^T C = m \Sigma, the matrix CTC+ϵ Id=mM−1C^T C + \epsilon\, \mathrm{Id} = m M^{-1} is positive definite when ϵ>0\epsilon > 0, or when ϵ=0\epsilon = 0 and Σ\Sigma is nonsingular. This is ridge regression, and its minimum is

α~Tα~−α~TC(CTC+ϵ Id)−1CTα~=α~Tα~−1m α~TCMCTα~.\tilde\alpha^T \tilde\alpha - \tilde\alpha^T C (C^T C + \epsilon\, \mathrm{Id})^{-1} C^T \tilde\alpha = \tilde\alpha^T \tilde\alpha - \tfrac1m\, \tilde\alpha^T C M C^T \tilde\alpha .

The columns of CC sum to zero, so CT1=0C^T \mathbf 1 = 0 and CTα~=CTαC^T \tilde\alpha = C^T \alpha. Also α~Tα~=αT(Id−1m11T)α\tilde\alpha^T \tilde\alpha = \alpha^T (\mathrm{Id} - \frac1m \mathbf 1 \mathbf 1^T) \alpha. So the minimum is αT(Id−1m(11T+CMCT))α\alpha^T \bigl(\mathrm{Id} - \frac1m (\mathbf 1 \mathbf 1^T + C M C^T)\bigr) \alpha, and the entry (i,j)(i, j) of that matrix is (Lw)ij(L_w)_{ij}. □\square

Theorem 1 (the matting Laplacian)

Let LL be the matrix built by lines L1 to L5. Then min⁡a,bJ(α,a,b)=αTLα\min_{a, b} J(\alpha, a, b) = \alpha^T L \alpha for each α\alpha.

Proof. The pairs (ak,bk)(a_k, b_k) of different windows are independent, so the minimum of the sum is the sum of the minima. By Lemma 1, the minimum for window kk is αTLwkα\alpha^T L_{w_k} \alpha with LwkL_{w_k} placed in the rows and columns of the window. Line L5 adds exactly these entries, so L=∑kLwkL = \sum_k L_{w_k} and the sum is αTLα\alpha^T L \alpha. □\square

This is Theorem 1 of the paper. For c=1c = 1 the entry is the formula of equation 5, and for c=3c = 3 it is equation 12.

Lemma 2 (shape of LL)

LL is symmetric, positive semidefinite, and L1=0L \mathbf 1 = 0.

Proof. Each LwL_{w} is symmetric because MM is. By Lemma 1, αTLα\alpha^T L \alpha is a minimum of sums of squares, so it is at least 00. For the row sums, Lw1=1−1m(m1+CMCT1)=0L_w \mathbf 1 = \mathbf 1 - \frac1m (m \mathbf 1 + C M C^T \mathbf 1) = 0, because CT1=0C^T \mathbf 1 = 0. □\square

So LL is never positive definite: the constant vector is in its null space. The paper calls LL "positive definite" in its Section 4, but the paper itself notes that the rows sum to zero, so the right word is semidefinite.

Lemma 3 (null space for ϵ>0\epsilon > 0)

If ϵ>0\epsilon > 0, then Lα=0L \alpha = 0 only for constant α\alpha.

Proof. For a semidefinite LL, Lα=0L\alpha = 0 if and only if αTLα=0\alpha^T L \alpha = 0. By Theorem 1, αTLα=0\alpha^T L \alpha = 0 means that in each window some (ak,bk)(a_k, b_k) gives zero cost. Then ϵ∥ak∥2=0\epsilon \lVert a_k \rVert^2 = 0, so ak=0a_k = 0, and αi=bk\alpha_i = b_k on the whole window. Two windows whose centers are neighbors share 6 pixels, so α\alpha has the same constant on both. The centers form a connected grid, so α\alpha is one constant on the union of the windows. Each pixel lies in at least one window (the window whose center is the nearest interior pixel), so α\alpha is constant. □\square

If ϵ=0\epsilon = 0, the null space also holds each color channel IcI^c, because α=Ic\alpha = I^c fits each window with zero cost. The test file checks this.

Theorem 2 (the solution of lines L6 to L8)

Let SS be the scribbled pixels with the values ss, and UU the other pixels. If ϵ>0\epsilon > 0 and SS is not empty, then the problem

min⁡ααTLαsubject toαi=si for i∈S\min_\alpha \alpha^T L \alpha \quad \text{subject to} \quad \alpha_i = s_i \text{ for } i \in S

(equation 13 of the paper) has exactly one solution, and it is the vector of line L8, with αU\alpha_U from LUUαU=−LUSsL_{UU} \alpha_U = -L_{US} s.

Proof. For yy on UU, extend it by 00 on SS to yˉ\bar y. Then yTLUUy=yˉTLyˉ≥0y^T L_{UU} y = \bar y^T L \bar y \ge 0. If it is 00, then yˉ\bar y is constant by Lemma 3, and it is 00 on SS, so y=0y = 0. So LUUL_{UU} is positive definite. With αS=s\alpha_S = s fixed, the cost is

sTLSSs+2αUTLUSs+αUTLUUαU,s^T L_{SS} s + 2 \alpha_U^T L_{US} s + \alpha_U^T L_{UU} \alpha_U,

a strictly convex function of αU\alpha_U. Its only minimizer is the zero of the gradient, LUUαU+LUSs=0L_{UU} \alpha_U + L_{US} s = 0, which line L7 solves. □\square

Two consequences follow from linearity and L1=0L \mathbf 1 = 0. If all scribbles are 11, then α=1\alpha = \mathbf 1. If each scribble value sis_i is replaced by 1−si1 - s_i, the matte becomes 1−α\mathbf 1 - \alpha. So the foreground and the background are treated the same way.

Theorem 3 (exact recovery)

Let ϵ=0\epsilon = 0, and let the true matte α∗\alpha^* be an affine function of II in each window: αi∗=akTIi+bk\alpha^*_i = a_k^T I_i + b_k for i∈wki \in w_k. If the scribbles agree with α∗\alpha^*, then α∗\alpha^* is a solution of the problem of Theorem 2.

Proof. The cost J(α∗,a,b)J(\alpha^*, a, b) with these (ak,bk)(a_k, b_k) is 00, so α∗TLα∗=0\alpha^{*T} L \alpha^* = 0 by Theorem 1. Each feasible α\alpha has αTLα≥0\alpha^T L \alpha \ge 0 by Lemma 2, and α∗\alpha^* is feasible. □\square

This is Theorem 3 of the paper. Its Theorem 2 shows that the affine model holds when the foreground colors and the background colors of each window each lie on a line in color space (the color line model). For gray images it holds when FF and BB are constant on each window and F≠BF \ne B, since then α=(I−B)/(F−B)\alpha = (I - B)/(F - B).

The theorem uses the assumption of the setup that each Σk\Sigma_k is nonsingular when ϵ=0\epsilon = 0. With constant colors FF and BB, the colors of a window lie on one line, Σk\Sigma_k has rank 1, and LL exists only for ϵ>0\epsilon > 0. Even when LL exists for ϵ=0\epsilon = 0, the solution need not be unique: the null space holds the constants and the channels, and the scribbles must pin all of them. The code uses a small ϵ>0\epsilon > 0, so Theorem 2 gives one solution. As ϵ→0\epsilon \to 0 it approaches α∗\alpha^*; the test file checks this with ϵ=10−8\epsilon = 10^{-8} for a gray and a color image.

What is not proved

There is no maximum principle. Unlike a graph Laplacian with positive weights, LL can have positive entries off the diagonal, so α\alpha can leave [0,1][0, 1]. The test file shows such a case, and in practice the result is clipped. Nothing here says that the matte matches the true matte of a natural image where the color line model fails.

Complexity

The cost model is the real-RAM. Let N=WHN = WH. Each window has 9 pixels, so lines L2 to L5 cost O(Nc3+81N)=O(N)O(N c^3 + 81 N) = O(N) time for a fixed cc. In a sparse format LL has at most 25 nonzeros per row, because two pixels share a 3×33 \times 3 window only when they are at most 2 apart in each direction.

  • Dense solve, as in the code. The code stores LL as a dense matrix, which costs O(N2)O(N^2) space and O(N2)O(N^2) time to fill. Line L7 costs O(N3)=O(W3H3)O(N^3) = O(W^3 H^3) time by Gaussian elimination. These are the bounds in the front matter. They are theorems about the code.
  • Sparse direct solve. With nested dissection on a grid with a fixed neighborhood, the factorization costs O(N3/2)O(N^{3/2}) time. This is a theorem for grid-like sparsity.
  • Iterative solvers. Each conjugate gradient step costs O(N)O(N), and the number of steps depends on the condition number of LUUL_{UU}, which grows as ϵ\epsilon shrinks.

The paper reports 20 seconds for a 200×300200 \times 300 image with the direct sparse solver of MATLAB on a 2.8 GHz CPU, and a multigrid solver that takes a couple of seconds for very large images with a small loss in quality. These are benchmark results.

Properties

  • Global optimum. The cost is quadratic and convex, so the solve gives the exact minimizer, not a local one.
  • No estimate of FF and BB. The colors are eliminated, so the method does not need a model of the color distributions, unlike Bayesian matting.
  • Few scribbles. The overlapping windows spread the scribbles over the image, so a few strokes can be enough. A full trimap also works.
  • Symmetry. Swapping the scribble values 00 and 11 gives 1−α1 - \alpha, and a constant scribble value gives a constant matte.
  • Spectral view. L=D−WL = D - W is a graph Laplacian with the matting affinity, which can be negative. Its eigenvectors with small eigenvalues look like soft segments, and the paper uses them to guide where the user should scribble (Section 4).
  • Window size. Wider windows help when the colors are complex, but LL gets denser. The paper solves with 3×33 \times 3 windows on a coarse image and moves the coefficients to the fine image.

Variants and improvements

  • Foreground colors. After α\alpha is known, FF and BB can be found from another quadratic problem, for compositing on a new background. The paper discusses this in Section 5.
  • Spectral matting. Levin, Rav-Acha and Lischinski (2008) build mattes from the small eigenvectors of LL without scribbles, as a set of matting components.
  • Guided filter. He, Sun and Tang (2010) use the same local linear model as an edge-preserving filter, and point out its link to the matting Laplacian. See guided filter.
  • Learned and sampled methods. Later methods combine LL with color sampling or with learned priors. Deep networks now lead the matting benchmarks.
  • Random walk matting. Grady and others used a graph Laplacian with Gaussian weights, as in the random walker. The matting Laplacian replaces those weights with the local linear model.

When to use it

Use it to pull a soft matte for hair, fur, smoke or motion blur, when the user can paint a few strokes or give a trimap and the colors in small windows are simple. It is a good baseline and a good final step after a hard segmentation such as GrabCut. For a hard object mask, use a segmentation method. For complex or overlapping color distributions, a learned method may do better.

Pitfalls

  • Choice of ϵ\epsilon. A large ϵ\epsilon smooths the matte. An ϵ\epsilon near 00 makes LL ill conditioned in flat or one-line windows, where Σk\Sigma_k is singular. The paper uses ϵ=0.0001\epsilon = 0.0001 in its spectral example.
  • Scale of the colors. The meaning of ϵ\epsilon depends on whether colors are in [0,1][0, 1] or in [0,255][0, 255].
  • Values outside [0,1][0, 1]. Clip the result.
  • Border windows. The windows here lie inside the image. Each pixel is still in at least one window, but border pixels are in fewer windows, so they are less constrained.
  • Memory. A dense LL is far too large for real images. Use a sparse matrix and a sparse or iterative solver.
  • No scribble on a part of the image. With few scribbles, an area far from both can get an alpha near 0.50.5, or a value set by the eigenvectors of LL. Check the result and add strokes there.

Implementations

The Python code in impl/python/closed_form_matting.py builds the dense matting Laplacian for gray or color images (lines L1 to L5), using the 3×33 \times 3 inverse of cvla.py, and solves the hard constraints of lines L6 to L8. It also computes the cost JJ by direct least squares in each window. The tests check the example above, the symmetry, the zero row sums and the semidefinite spectrum of LL, Theorem 1 against the direct least squares, the null space for ϵ=0\epsilon = 0, exact recovery of a synthetic matte, the minimality of the solution, the 00 and 11 symmetry, and a case where alpha leaves [0,1][0, 1].

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.

closed_form_matting.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/closed-form-matting/. The authors are listed in prov/YQKAHR.jsonl.

"""Closed-form matting of Levin, Lischinski and Weiss (CVPR 2006).

Pixel p = v * w + u is (u, v). img[v][u] is a gray value (a number) or a
color (a list of 3 numbers). The matting Laplacian L sums, over every 3 x 3
window w_k that lies inside the image,

    L_ij += delta_ij - (1 + (I_i - mu_k)^T (Sigma_k + eps / |w_k| Id)^-1 (I_j - mu_k)) / |w_k|

for the pixels i, j of the window, with the mean mu_k and the covariance
Sigma_k (divided by |w_k|) of the window. The matte minimizes alpha^T L alpha
with alpha fixed on the scribbled pixels. L is dense here, so the code suits
small images only.
"""

from cvla import inv, solve, zeros

WINDOW_RADIUS = 1


def pixel_vectors(img):
    """The pixels in the order p = v * w + u, each as a list of channels."""
    out = []
    for row in img:
        for x in row:
            out.append([float(c) for c in x] if isinstance(x, (list, tuple)) else [float(x)])
    return out


def windows(h, w, r=WINDOW_RADIUS):
    """The pixel lists of all (2r+1) x (2r+1) windows inside the image."""
    out = []
    for v in range(r, h - r):
        for u in range(r, w - r):
            out.append([(v + dv) * w + (u + du) for dv in range(-r, r + 1) for du in range(-r, r + 1)])
    return out


def window_stats(vec, win):
    """The mean vector and the covariance matrix (divided by |w|) of a window."""
    c = len(vec[0])
    m = len(win)
    mu = [sum(vec[i][a] for i in win) / m for a in range(c)]
    cov = [[sum((vec[i][a] - mu[a]) * (vec[i][b] - mu[b]) for i in win) / m for b in range(c)] for a in range(c)]
    return mu, cov


def matting_laplacian(img, eps):
    """The dense N x N matting Laplacian of equations 5 (gray) and 12 (color)."""
    h, w = len(img), len(img[0])
    vec = pixel_vectors(img)
    c = len(vec[0])
    n = h * w
    lap = zeros(n, n)  # @line L1
    for win in windows(h, w):  # @line L2
        m = len(win)
        mu, cov = window_stats(vec, win)  # @line L3
        reg = [[cov[a][b] + (eps / m if a == b else 0.0) for b in range(c)] for a in range(c)]
        minv = inv(reg)  # @line L4
        cen = [[vec[i][a] - mu[a] for a in range(c)] for i in win]
        proj = [[sum(minv[a][b] * x[b] for b in range(c)) for a in range(c)] for x in cen]
        for ii, i in enumerate(win):
            for jj, j in enumerate(win):
                q = sum(cen[ii][a] * proj[jj][a] for a in range(c))
                lap[i][j] += (1.0 if i == j else 0.0) - (1.0 + q) / m  # @line L5
    return lap


def solve_matte(lap, scribbles):
    """Minimize alpha^T L alpha subject to alpha_i = s_i for i in scribbles (equation 13)."""
    n = len(lap)
    alpha = [0.0] * n
    free = [p for p in range(n) if p not in scribbles]  # @line L6
    for p, s in scribbles.items():
        alpha[p] = float(s)
    if free:
        luu = [[lap[i][j] for j in free] for i in free]
        rhs = [-sum(lap[i][p] * s for p, s in scribbles.items()) for i in free]
        xu = solve(luu, rhs)  # @line L7
        for r, p in enumerate(free):
            alpha[p] = xu[r]
    return alpha  # @line L8


def closed_form_matting(img, scribbles, eps=1e-4):
    """The alpha matte of img from scribbles {pixel: 0 or 1 (or any value)}."""
    return solve_matte(matting_laplacian(img, eps), scribbles)


def quadratic_form(lap, x):
    return sum(x[i] * sum(lap[i][j] * x[j] for j in range(len(x))) for i in range(len(x)))


def cost_j(img, alpha, eps):
    """min over (a_k, b_k) of the cost J(alpha, a, b) of equations 3 and 10,
    computed window by window from the normal equations of the least squares."""
    h, w = len(img), len(img[0])
    vec = pixel_vectors(img)
    c = len(vec[0])
    total = 0.0
    for win in windows(h, w):
        rows = [vec[i] + [1.0] for i in win]
        ata = [[sum(r[a] * r[b] for r in rows) + (eps if a == b and a < c else 0.0)
                for b in range(c + 1)] for a in range(c + 1)]
        atb = [sum(r[a] * alpha[i] for r, i in zip(rows, win)) for a in range(c + 1)]
        coef = solve(ata, atb)
        res = sum((alpha[i] - sum(coef[a] * r[a] for a in range(c + 1))) ** 2 for r, i in zip(rows, win))
        total += res + eps * sum(coef[a] ** 2 for a in range(c))
    return total


def composite(alpha, fg, bg):
    """I_i = alpha_i F_i + (1 - alpha_i) B_i for flat lists of numbers or of colors."""
    out = []
    for a, f, b in zip(alpha, fg, bg):
        if isinstance(f, (list, tuple)):
            out.append([a * x + (1 - a) * y for x, y in zip(f, b)])
        else:
            out.append(a * f + (1 - a) * b)
    return out
cvla.py 494 lines
# SPDX-License-Identifier: MIT
# Shared helper of the computer vision pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small dense linear algebra for the computer vision pages.

A matrix is a list of rows. A vector is a flat list. The functions do not
change their arguments. Entries are floats, but zeros, eye, transpose, add,
sub, scale, mul, matvec, dot, cross, skew, solve, inv and det also work with
fractions.Fraction entries and then give exact results.

Tolerances:
- solve, inv and det raise ValueError only on an exact zero pivot. A matrix
  that is close to singular gives large entries; check the condition yourself.
- sym_eig and svd stop a Jacobi sweep when every off-diagonal term is below
  1e-15 times the size of its pair (at most 100 sweeps).
- polyroots_real keeps a root z when |Im z| <= imag_tol * max(1, |z|), with
  imag_tol = 1e-6 by default. Roots of multiplicity k are found with an error
  of about 1e-16^(1/k) relative, so a double root keeps an imaginary part near
  1e-8.

This module holds no algorithm of a computer vision page.
"""

from __future__ import annotations

import cmath
import math
from typing import List, Sequence, Tuple

Matrix = List[List[float]]
Vector = List[float]

_JACOBI_EPS = 1e-15
_MAX_SWEEPS = 100


# ---------------------------------------------------------------- basics

def zeros(m: int, n: int) -> Matrix:
    """The m x n zero matrix."""
    return [[0.0] * n for _ in range(m)]


def eye(n: int) -> Matrix:
    """The n x n identity matrix."""
    return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]


def _is_matrix(a) -> bool:
    return len(a) > 0 and isinstance(a[0], (list, tuple))


def transpose(a: Sequence[Sequence[float]]) -> Matrix:
    """The transpose of a matrix."""
    return [list(col) for col in zip(*a)]


def add(a, b):
    """a + b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x + y for x, y in zip(a, b)]


def sub(a, b):
    """a - b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x - y for x, y in zip(a, b)]


def scale(a, c):
    """c times a, for a vector or a matrix a and a number c."""
    if _is_matrix(a):
        return [[c * x for x in row] for row in a]
    return [c * x for x in a]


def mul(a: Sequence[Sequence[float]], b: Sequence[Sequence[float]]) -> Matrix:
    """The matrix product a b."""
    if len(a[0]) != len(b):
        raise ValueError("mul: shapes do not match")
    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: Sequence[Sequence[float]], x: Sequence[float]) -> Vector:
    """The product a x of a matrix and a vector."""
    if len(a[0]) != len(x):
        raise ValueError("matvec: shapes do not match")
    return [sum(p * q for p, q in zip(row, x)) for row in a]


def dot(x: Sequence[float], y: Sequence[float]) -> float:
    """The inner product of two vectors."""
    return sum(p * q for p, q in zip(x, y))


def norm(a) -> float:
    """The Euclidean norm of a vector, or the Frobenius norm of a matrix."""
    if _is_matrix(a):
        return math.sqrt(sum(float(x) * float(x) for row in a for x in row))
    return math.sqrt(sum(float(x) * float(x) for x in a))


def cross(a: Sequence[float], b: Sequence[float]) -> Vector:
    """The cross product a x b of two 3-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 skew(a: Sequence[float]) -> Matrix:
    """The skew matrix [a]_x, with skew(a) b = cross(a, b)."""
    z = a[0] - a[0]
    return [[z, -a[2], a[1]],
            [a[2], z, -a[0]],
            [-a[1], a[0], z]]


# ---------------------------------------------------- Gaussian elimination

def _eliminate(a: Matrix, b: Matrix) -> Tuple[Matrix, Matrix, int]:
    """Reduce [a | b] to upper triangular form with partial pivoting.

    Works in place on copies made by the caller. Returns a, b and the sign
    of the row permutation.
    """
    n = len(a)
    sign = 1
    for k in range(n):
        p = max(range(k, n), key=lambda i: abs(a[i][k]))
        if a[p][k] == 0:
            raise ValueError("singular matrix")
        if p != k:
            a[k], a[p] = a[p], a[k]
            b[k], b[p] = b[p], b[k]
            sign = -sign
        piv = a[k][k]
        for i in range(k + 1, n):
            f = a[i][k] / piv
            if f == 0:
                continue
            ai, ak = a[i], a[k]
            for j in range(k, n):
                ai[j] = ai[j] - f * ak[j]
            bi, bk = b[i], b[k]
            for j in range(len(bi)):
                bi[j] = bi[j] - f * bk[j]
    return a, b, sign


def solve(a: Sequence[Sequence[float]], b):
    """Solve a x = b for a square a, by Gaussian elimination with partial
    pivoting. b is a vector or a matrix (several right-hand sides); the
    result has the same form. Raises ValueError on an exact zero pivot."""
    n = len(a)
    if any(len(row) != n for row in a):
        raise ValueError("solve: matrix is not square")
    vec = not _is_matrix(b)
    rhs = [[x] for x in b] if vec else [list(row) for row in b]
    if len(rhs) != n:
        raise ValueError("solve: shapes do not match")
    u, c, _ = _eliminate([list(row) for row in a], rhs)
    m = len(c[0]) if n else 0
    x = [[0.0] * m for _ in range(n)]
    for i in range(n - 1, -1, -1):
        for j in range(m):
            s = c[i][j]
            for k in range(i + 1, n):
                s = s - u[i][k] * x[k][j]
            x[i][j] = s / u[i][i]
    return [row[0] for row in x] if vec else x


def inv(a: Sequence[Sequence[float]]) -> Matrix:
    """The inverse of a square matrix. Raises ValueError if it is singular."""
    n = len(a)
    one = a[0][0] - a[0][0] + 1 if n else 1.0
    ident = [[one if i == j else one - one for j in range(n)] for i in range(n)]
    return solve(a, ident)


def det(a: Sequence[Sequence[float]]) -> float:
    """The determinant of a square matrix, by Gaussian elimination."""
    n = len(a)
    if any(len(row) != n for row in a):
        raise ValueError("det: matrix is not square")
    if n == 0:
        return 1.0
    try:
        u, _, sign = _eliminate([list(row) for row in a], [[] for _ in range(n)])
    except ValueError:
        return a[0][0] - a[0][0]
    d = u[0][0] - u[0][0] + sign
    for i in range(n):
        d = d * u[i][i]
    return d


# ------------------------------------------------------- Jacobi methods

def sym_eig(a: Sequence[Sequence[float]]) -> Tuple[Vector, Matrix]:
    """Eigenvalues and eigenvectors of a real symmetric matrix by the cyclic
    Jacobi method. Returns (w, V): w ascending, and column j of V is a unit
    eigenvector for w[j], so a = V diag(w) V^T. Only the upper triangle of
    a is read (the lower triangle is taken as its mirror)."""
    n = len(a)
    s = [[float(a[min(i, j)][max(i, j)]) for j in range(n)] for i in range(n)]
    v = eye(n)
    for _ in range(_MAX_SWEEPS):
        rotated = False
        for p in range(n - 1):
            for q in range(p + 1, n):
                apq = s[p][q]
                if apq == 0.0:
                    continue
                app, aqq = s[p][p], s[q][q]
                if abs(apq) <= _JACOBI_EPS * math.sqrt(abs(app * aqq)) or \
                        abs(apq) < 1e-300:
                    s[p][q] = s[q][p] = 0.0
                    continue
                rotated = True
                theta = (aqq - app) / (2.0 * apq)
                t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1.0))
                c = 1.0 / math.sqrt(t * t + 1.0)
                sn = t * c
                for k in range(n):
                    skp, skq = s[k][p], s[k][q]
                    s[k][p] = c * skp - sn * skq
                    s[k][q] = sn * skp + c * skq
                for k in range(n):
                    spk, sqk = s[p][k], s[q][k]
                    s[p][k] = c * spk - sn * sqk
                    s[q][k] = sn * spk + c * sqk
                s[p][q] = s[q][p] = 0.0
                for k in range(n):
                    vkp, vkq = v[k][p], v[k][q]
                    v[k][p] = c * vkp - sn * vkq
                    v[k][q] = sn * vkp + c * vkq
        if not rotated:
            break
    order = sorted(range(n), key=lambda i: s[i][i])
    w = [s[i][i] for i in order]
    vs = [[v[k][i] for i in order] for k in range(n)]
    return w, vs


def _complete_basis(cols: List[Vector], m: int, need: List[int]) -> None:
    """Replace the columns with index in need by unit vectors orthogonal to
    all other columns (Gram-Schmidt on the standard basis)."""
    keep = [c for i, c in enumerate(cols) if i not in need]
    for i in need:
        best, best_norm = None, -1.0
        for e in range(m):
            x = [0.0] * m
            x[e] = 1.0
            for _ in range(2):
                for c in keep:
                    d = dot(c, x)
                    x = [xi - d * ci for xi, ci in zip(x, c)]
            nx = norm(x)
            if nx > best_norm:
                best, best_norm = x, nx
        u = [xi / best_norm for xi in best]
        cols[i] = u
        keep.append(u)


def _svd_tall(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Vector, Matrix]:
    m, n = len(a), len(a[0])
    cols = [[float(a[i][j]) for i in range(m)] for j in range(n)]
    vcols = [[1.0 if i == j else 0.0 for i in range(n)] for j in range(n)]
    for _ in range(_MAX_SWEEPS):
        rotated = False
        for p in range(n - 1):
            for q in range(p + 1, n):
                cp, cq = cols[p], cols[q]
                alpha = sum(x * x for x in cp)
                beta = sum(x * x for x in cq)
                gamma = sum(x * y for x, y in zip(cp, cq))
                if gamma == 0.0 or abs(gamma) <= _JACOBI_EPS * math.sqrt(alpha * beta):
                    continue
                rotated = True
                zeta = (beta - alpha) / (2.0 * gamma)
                t = (1.0 if zeta >= 0 else -1.0) / (abs(zeta) + math.sqrt(1.0 + zeta * zeta))
                c = 1.0 / math.sqrt(1.0 + t * t)
                s = c * t
                cols[p] = [c * x - s * y for x, y in zip(cp, cq)]
                cols[q] = [s * x + c * y for x, y in zip(cp, cq)]
                vp, vq = vcols[p], vcols[q]
                vcols[p] = [c * x - s * y for x, y in zip(vp, vq)]
                vcols[q] = [s * x + c * y for x, y in zip(vp, vq)]
        if not rotated:
            break
    sv = [norm(c) for c in cols]
    order = sorted(range(n), key=lambda i: -sv[i])
    sv = [sv[i] for i in order]
    cols = [cols[i] for i in order]
    vcols = [vcols[i] for i in order]
    smax = sv[0] if sv else 0.0
    ucols: List[Vector] = []
    need: List[int] = []
    for i, c in enumerate(cols):
        if sv[i] > 1e-13 * smax and sv[i] > 1e-300:
            ucols.append([x / sv[i] for x in c])
        else:
            ucols.append([0.0] * m)
            need.append(i)
    if need:
        _complete_basis(ucols, m, need)
    return transpose(ucols), sv, transpose(vcols)


def svd(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Vector, Matrix]:
    """Thin singular value decomposition by the one-sided Jacobi method.

    For an m x n matrix a with k = min(m, n), returns (U, S, V) with U of
    size m x k, S a list of k values in descending order and V of size
    n x k, such that a = U diag(S) V^T. U and V have orthonormal columns.
    For m >= n, V is square (n x n)."""
    m, n = len(a), len(a[0])
    if m >= n:
        return _svd_tall(a)
    u, s, v = _svd_tall(transpose(a))
    return v, s, u


def nullvec(a: Sequence[Sequence[float]]) -> Vector:
    """A unit vector x that minimizes ||a x||: the right singular vector of
    the smallest singular value. If a has fewer rows than columns, zero rows
    are added first, so the result is in the null space. The sign is not
    fixed."""
    m, n = len(a), len(a[0])
    rows = [list(map(float, r)) for r in a] + [[0.0] * n for _ in range(n - m)]
    _, _, v = _svd_tall(rows)
    return [v[i][n - 1] for i in range(n)]


# ---------------------------------------------- orthogonal factorizations

def qr(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Matrix]:
    """QR factorization by Householder reflections. For an m x n matrix a,
    returns Q (m x m, orthogonal) and R (m x n, upper triangular) with
    a = Q R. The signs are chosen so that the diagonal of R is >= 0."""
    m, n = len(a), len(a[0])
    r = [[float(x) for x in row] for row in a]
    q = eye(m)
    for k in range(min(m - 1, n)):
        x = [r[i][k] for i in range(k, m)]
        nx = norm(x)
        if nx == 0.0:
            continue
        alpha = -nx if x[0] >= 0 else nx
        v = list(x)
        v[0] -= alpha
        nv = norm(v)
        if nv == 0.0:
            continue
        v = [vi / nv for vi in v]
        for j in range(n):
            d = sum(v[i - k] * r[i][j] for i in range(k, m))
            if d != 0.0:
                for i in range(k, m):
                    r[i][j] -= 2.0 * v[i - k] * d
        for i in range(m):
            d = sum(q[i][l] * v[l - k] for l in range(k, m))
            if d != 0.0:
                for l in range(k, m):
                    q[i][l] -= 2.0 * d * v[l - k]
    for k in range(min(m, n)):
        if r[k][k] < 0:
            r[k] = [-x for x in r[k]]
            for i in range(m):
                q[i][k] = -q[i][k]
    for i in range(m):
        for j in range(min(i, n)):
            r[i][j] = 0.0
    return q, r


def rq(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Matrix]:
    """RQ factorization of a square matrix: returns R (upper triangular,
    with a diagonal >= 0) and Q (orthogonal) with a = R Q. It is computed
    from the QR factorization of the transpose of the row-reversed matrix."""
    n = len(a)
    if any(len(row) != n for row in a):
        raise ValueError("rq: matrix is not square")
    flipped = transpose([list(row) for row in reversed(a)])
    q1, r1 = qr(flipped)
    rt = transpose(r1)
    r = [list(reversed(row)) for row in reversed(rt)]
    q = [list(row) for row in reversed(transpose(q1))]
    return r, q


def cholesky(a: Sequence[Sequence[float]]) -> Matrix:
    """The lower triangular L with a = L L^T, for a symmetric positive
    definite a. Raises ValueError if a pivot is not positive."""
    n = len(a)
    low = zeros(n, n)
    for j in range(n):
        d = a[j][j] - sum(low[j][k] * low[j][k] for k in range(j))
        if d <= 0:
            raise ValueError("cholesky: matrix is not positive definite")
        low[j][j] = math.sqrt(d)
        for i in range(j + 1, n):
            low[i][j] = (a[i][j] - sum(low[i][k] * low[j][k] for k in range(j))) / low[j][j]
    return low


# ---------------------------------------------------------- polynomials

def _horner(c: Sequence[complex], x):
    p = 0.0
    for ci in c:
        p = p * x + ci
    return p


def polyroots_real(coeffs: Sequence[float], imag_tol: float = 1e-6) -> Vector:
    """Real roots of the polynomial with the given coefficients, highest
    power first. All complex roots are found by the Durand-Kerner method.
    A root z is kept as real when |Im z| <= imag_tol * max(1, |z|); its real
    part is then polished by Newton steps on the real polynomial. Returns
    the real roots in ascending order, with repeats for multiple roots."""
    c = [float(x) for x in coeffs]
    while c and c[0] == 0.0:
        c.pop(0)
    n = len(c) - 1
    if n < 1:
        return []
    c = [x / c[0] for x in c]
    rho = max([abs(c[i]) ** (1.0 / i) for i in range(1, n + 1)] + [0.0])
    if rho == 0.0:
        return [0.0] * n
    z = [rho * cmath.exp(1j * (2.0 * math.pi * k / n + 0.4)) for k in range(n)]
    for _ in range(2000):
        moved = 0.0
        for k in range(n):
            den = 1.0 + 0j
            for j in range(n):
                if j != k:
                    den *= z[k] - z[j]
            if den == 0:
                den = 1e-12 * rho
            step = _horner(c, z[k]) / den
            z[k] -= step
            moved = max(moved, abs(step) / max(1.0, abs(z[k])))
        if moved <= 1e-15:
            break
    deriv = [c[i] * (n - i) for i in range(n)]
    roots = []
    for zk in z:
        if abs(zk.imag) > imag_tol * max(1.0, abs(zk)):
            continue
        x = zk.real
        px = _horner(c, x)
        for _ in range(8):
            dp = _horner(deriv, x)
            if dp == 0.0 or px == 0.0:
                break
            xn = x - px / dp
            pn = _horner(c, xn)
            if abs(pn) >= abs(px):
                break
            x, px = xn, pn
        roots.append(x)
    return sorted(roots)


# ------------------------------------------------------------ self-test

def self_test() -> None:
    """Check svd, sym_eig and polyroots_real. Raises AssertionError."""
    import random
    rng = random.Random(7)
    for _ in range(3):
        a = [[rng.uniform(-1, 1) for _ in range(5)] for _ in range(5)]
        u, s, v = svd(a)
        rec = mul(mul(u, [[s[i] if i == j else 0.0 for j in range(5)] for i in range(5)]), transpose(v))
        assert norm(sub(rec, a)) <= 1e-10
        assert all(s[i] >= s[i + 1] for i in range(4))
        sym = add(a, transpose(a))
        w, vv = sym_eig(sym)
        rec = mul(mul(vv, [[w[i] if i == j else 0.0 for j in range(5)] for i in range(5)]), transpose(vv))
        assert norm(sub(rec, sym)) <= 1e-10
        assert all(w[i] <= w[i + 1] for i in range(4))
    r = polyroots_real([1.0, -6.0, 11.0, -6.0])
    assert len(r) == 3
    assert all(abs(x - y) <= 1e-10 for x, y in zip(r, [1.0, 2.0, 3.0]))


if __name__ == "__main__":
    self_test()
test_closed_form_matting.py 111 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/closed-form-matting/. The authors are listed in prov/YQKAHR.jsonl.

import random

from closed_form_matting import (
    closed_form_matting,
    composite,
    cost_j,
    matting_laplacian,
    quadratic_form,
    solve_matte,
)
from cvla import sym_eig


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


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


def test_example_blurred_edge():
    row = [0.1, 0.2, 0.5, 0.9, 0.9]
    img = [row[:] for _ in range(3)]
    scribbles = {}
    for v in range(3):
        scribbles[v * 5] = 0.0
        scribbles[v * 5 + 4] = 1.0
    alpha = closed_form_matting(img, scribbles, 1e-6)
    assert [round(x, 4) for x in alpha[5:10]] == [0.0, 0.125, 0.5, 1.0, 1.0]
    alpha = closed_form_matting(img, scribbles, 0.1)
    assert [round(x, 4) for x in alpha[5:10]] == [0.0, 0.2295, 0.512, 0.8615, 1.0]


def test_laplacian_is_symmetric_with_zero_row_sums_and_psd():
    rng = random.Random(4)
    for img in (gray_image(rng, 4, 4), color_image(rng, 4, 4)):
        lap = matting_laplacian(img, 1e-3)
        n = len(lap)
        for i in range(n):
            assert abs(sum(lap[i])) < 1e-12
            for j in range(n):
                assert abs(lap[i][j] - lap[j][i]) < 1e-12
        w, _ = sym_eig(lap)
        assert w[0] > -1e-10
        assert abs(w[0]) < 1e-10
        assert w[1] > 1e-8


def test_theorem_1_quadratic_form_equals_min_over_a_b():
    rng = random.Random(7)
    for img in (gray_image(rng, 4, 5), color_image(rng, 4, 4)):
        for eps in (1e-3, 0.1):
            lap = matting_laplacian(img, eps)
            for _ in range(5):
                alpha = [rng.uniform(-0.5, 1.5) for _ in range(len(lap))]
                assert abs(quadratic_form(lap, alpha) - cost_j(img, alpha, eps)) < 1e-9


def test_eps_zero_null_space_holds_the_channels():
    rng = random.Random(9)
    img = color_image(rng, 4, 4)
    lap = matting_laplacian(img, 0.0)
    flat = [x for row in img for x in row]
    for ch in range(3):
        y = [p[ch] for p in flat]
        r = [sum(lap[i][j] * y[j] for j in range(16)) for i in range(16)]
        assert max(abs(t) for t in r) < 1e-9


def test_theorem_3_recovers_the_true_matte():
    rng = random.Random(12)
    h, w = 4, 5
    n = h * w
    alpha = [rng.random() for _ in range(n)]
    for fg, bg in ((0.85, 0.15), ([0.9, 0.2, 0.1], [0.1, 0.3, 0.8])):
        flat = composite(alpha, [fg] * n, [bg] * n)
        img = [flat[v * w:(v + 1) * w] for v in range(h)]
        scribbles = {0: alpha[0], 7: alpha[7], 19: alpha[19]}
        got = closed_form_matting(img, scribbles, 1e-8)
        assert max(abs(x - y) for x, y in zip(got, alpha)) < 1e-5


def test_solution_minimizes_and_complements():
    rng = random.Random(21)
    img = color_image(rng, 4, 4)
    lap = matting_laplacian(img, 1e-2)
    scribbles = {0: 0.0, 3: 0.0, 12: 1.0, 15: 1.0}
    alpha = solve_matte(lap, scribbles)
    best = quadratic_form(lap, alpha)
    for _ in range(100):
        y = [a if p in scribbles else a + rng.uniform(-0.1, 0.1) for p, a in enumerate(alpha)]
        assert quadratic_form(lap, y) >= best - 1e-12
    flipped = solve_matte(lap, {p: 1.0 - s for p, s in scribbles.items()})
    assert all(abs(a + b - 1.0) < 1e-9 for a, b in zip(alpha, flipped))
    ones = solve_matte(lap, {p: 1.0 for p in scribbles})
    assert all(abs(a - 1.0) < 1e-9 for a in ones)


def test_alpha_can_leave_the_unit_interval():
    rng = random.Random(1)
    found = False
    for _ in range(10):
        img = gray_image(rng, 4, 5)
        alpha = closed_form_matting(img, {0: 0.0, 4: 0.0, 15: 1.0, 19: 1.0}, 1e-3)
        if min(alpha) < -1e-6 or max(alpha) > 1 + 1e-6:
            found = True
    assert found

History

Blue screen matting goes back to film work, and Smith and Blinn (1996) showed that the matting equation is underdetermined without extra assumptions. Bayesian matting (Chuang and others, 2001) and Poisson matting (2004) needed a trimap and estimated FF and BB. Levin, Lischinski and Weiss used the idea of their colorization method (2004), a quadratic cost spread by overlapping windows, and found the local linear model that removes FF and BB. The CVPR paper appeared in 2006, and the journal version in 2008. The matting Laplacian became a standard tool: it was used for dehazing, for spectral matting, as a term in many later matting methods, and it led to the guided filter.

References

  1. Anat Levin, Dani Lischinski and Yair Weiss, A closed form solution to natural image matting, CVPR 2006, vol. 1, 61-68, Section 2 (cost 3, Theorem 1, Laplacian 5), Section 2.1 (color model 9 to 12, Theorem 2), Section 3 (constraints 13, Theorem 3), Section 4 (spectral analysis), Section 5 (results and solvers)
  2. Anat Levin, Dani Lischinski and Yair Weiss, A closed-form solution to natural image matting, IEEE TPAMI 30(2), 228-242, 2008, The journal version, with more analysis and experiments
  3. Richard Szeliski, Computer Vision: Algorithms and Applications, 1st edition, Springer, 2011, Section 10.4, on image matting

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.average
  • a full proof of time.best
  • 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
  • a scene preset for the example