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.
- Solves
- Image matting
- 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
- Model
- Real RAM
- Properties
- deterministicexactglobal optimuminteractivesoft output
- Evidence
- Proof sketchCode in 1 languages
- 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 , where 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 . 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 with pixels and colors ( for gray, for color), a set of scribbled pixels with values (1 for foreground, 0 for background), and a small . The output is a matte with on .
The image model is the compositing equation (Levin, Lischinski and Weiss 2006, equation 1). For a gray image where and are about constant on a small window , it gives
For color, the model is (equation 9). The cost is (equations 3 and 10)
with one window around each pixel . The term makes the problem well posed in flat windows and prefers smooth mattes.
The algorithm
Theorem 1 of the paper eliminates and : , with
where and are the mean and the covariance of the colors in (equation 12; equation 5 is the gray case). The matte is (equation 13)
CLOSED-FORM-MATTING(I, S, s, ε)- 1
L ← the N × N zero matrix ▷ sparse in practice - 2
for each 3 × 3 window w_k inside the image do - 3
μ_k ← mean of I over w_k; Σ_k ← covariance of I over w_k - 4
M_k ← (Σ_k + ε / |w_k| · Id)⁻¹ ▷ a c × c inverse - 5
for each i, j in w_k do L_ij ← L_ij + δ_ij - (1 + (I_i - μ_k)ᵀ M_k (I_j - μ_k)) / |w_k| - 6
U ← the pixels not in S - 7
solve L_UU α_U = -L_US s - 8
α_S ← s; return α
Lines L6 to L8 set the gradient of 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 . This is a blurred edge between a background of and a foreground of . The left column is scribbled as and the right column as . The true matte is in each row. It is an affine function of in every window, so Theorem 3 of the paper says it is optimal for . The middle row of the result:
| col 0 | col 1 | col 2 | col 3 | col 4 | |
|---|---|---|---|---|---|
| 0 | 0.1250 | 0.5000 | 1.0000 | 1 | |
| 0 | 0.2295 | 0.5120 | 0.8615 | 1 |
With a small the method finds the true matte. With a large the term 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 is a ridge regression, and its value is . Summing over the windows gives . This is Theorem 1 of the paper.
- Theorem (shape of ). is symmetric and positive semidefinite, and each row sums to . For its null space is exactly the constant vectors. The paper calls positive definite, but , so it is only semidefinite.
- Theorem (unique matte). For and at least one scribble, 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 , 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 , and the test file has such a case. In practice the result is clipped to .
Proof: Correctness of closed-form mattingfull
This proof covers lines L1 to L8 of the main page. The image has pixels, each with a vector ( for gray, for color). The windows are the windows that lie inside the image, so each has pixels. The image has at least 3 rows and 3 columns, so there is at least one window. The parameter is . For a window, is the mean of the , and is the covariance. The cost of Levin, Lischinski and Weiss (equations 3 and 10 of the CVPR paper) is
When , assume that each is nonsingular, so that line L4 is defined.
Lemma 1 (one window)
Fix a window with pixels, and let be the matrix with rows . Let . For each vector on the window,
Proof. For a fixed , the cost is a sum of squares in , and its minimizer is the mean , with . Put this back and write . The cost becomes
Since , the matrix is positive definite when , or when and is nonsingular. This is ridge regression, and its minimum is
The columns of sum to zero, so and . Also . So the minimum is , and the entry of that matrix is .
Theorem 1 (the matting Laplacian)
Let be the matrix built by lines L1 to L5. Then for each .
Proof. The pairs of different windows are independent, so the minimum of the sum is the sum of the minima. By Lemma 1, the minimum for window is with placed in the rows and columns of the window. Line L5 adds exactly these entries, so and the sum is .
This is Theorem 1 of the paper. For the entry is the formula of equation 5, and for it is equation 12.
Lemma 2 (shape of )
is symmetric, positive semidefinite, and .
Proof. Each is symmetric because is. By Lemma 1, is a minimum of sums of squares, so it is at least . For the row sums, , because .
So is never positive definite: the constant vector is in its null space. The paper calls "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 )
If , then only for constant .
Proof. For a semidefinite , if and only if . By Theorem 1, means that in each window some gives zero cost. Then , so , and on the whole window. Two windows whose centers are neighbors share 6 pixels, so has the same constant on both. The centers form a connected grid, so 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 is constant.
If , the null space also holds each color channel , because fits each window with zero cost. The test file checks this.
Theorem 2 (the solution of lines L6 to L8)
Let be the scribbled pixels with the values , and the other pixels. If and is not empty, then the problem
(equation 13 of the paper) has exactly one solution, and it is the vector of line L8, with from .
Proof. For on , extend it by on to . Then . If it is , then is constant by Lemma 3, and it is on , so . So is positive definite. With fixed, the cost is
a strictly convex function of . Its only minimizer is the zero of the gradient, , which line L7 solves.
Two consequences follow from linearity and . If all scribbles are , then . If each scribble value is replaced by , the matte becomes . So the foreground and the background are treated the same way.
Theorem 3 (exact recovery)
Let , and let the true matte be an affine function of in each window: for . If the scribbles agree with , then is a solution of the problem of Theorem 2.
Proof. The cost with these is , so by Theorem 1. Each feasible has by Lemma 2, and is feasible.
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 and are constant on each window and , since then .
The theorem uses the assumption of the setup that each is nonsingular when . With constant colors and , the colors of a window lie on one line, has rank 1, and exists only for . Even when exists for , 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 , so Theorem 2 gives one solution. As it approaches ; the test file checks this with for a gray and a color image.
What is not proved
There is no maximum principle. Unlike a graph Laplacian with positive weights, can have positive entries off the diagonal, so can leave . 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 . Each window has 9 pixels, so lines L2 to L5 cost time for a fixed . In a sparse format has at most 25 nonzeros per row, because two pixels share a window only when they are at most 2 apart in each direction.
- Dense solve, as in the code. The code stores as a dense matrix, which costs space and time to fill. Line L7 costs 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 time. This is a theorem for grid-like sparsity.
- Iterative solvers. Each conjugate gradient step costs , and the number of steps depends on the condition number of , which grows as shrinks.
The paper reports 20 seconds for a 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 and . 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 and gives , and a constant scribble value gives a constant matte.
- Spectral view. 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 gets denser. The paper solves with windows on a coarse image and moves the coefficients to the fine image.
Variants and improvements
- Foreground colors. After is known, and 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 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 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 . A large smooths the matte. An near makes ill conditioned in flat or one-line windows, where is singular. The paper uses in its spectral example.
- Scale of the colors. The meaning of depends on whether colors are in or in .
- Values outside . 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 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 , or a value set by the eigenvectors of . 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 inverse of cvla.py, and solves the hard constraints of lines L6 to L8. It also computes the cost by direct least squares in each window. The tests check the example above, the symmetry, the zero row sums and the semidefinite spectrum of , Theorem 1 against the direct least squares, the null space for , exact recovery of a synthetic matte, the minimality of the solution, the and symmetry, and a case where alpha leaves .
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
# 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 and . 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 and . 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
- 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)
- 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
- 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.
| 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 YQKAHR Edit this page History Report an error Markdown