Algorithmadvanced
Least-squares phase unwrapping
Also called Ghiglia-Romero phase unwrapping.
Find the phase whose gradient best fits the wrapped phase differences in least squares, by solving a Poisson equation with fast cosine transforms.
- Solves
- Phase unwrapping
- Time
- O(m n log(m n)) worst
- Space
- O(m n) extra
- Where
- m = the number of rows of the image; n = the number of columns of the image
- Model
- Real RAM
- Properties
- deterministicnot exactnot linear in dataiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Dennis C. Ghiglia, Louis A. Romero, 1994
Least squares phase unwrapping turns a wrapped phase image into a continuous one by asking for the image whose gradient is as close as possible, in the sum of squares, to the wrapped differences of neighbouring pixels. Ghiglia and Romero (1994) showed that the normal equations of this problem are the discrete Poisson equation with Neumann boundary conditions, and that the two-dimensional discrete cosine transform diagonalizes it. So the whole method is one DCT, one division per coefficient and one inverse DCT, with a fast DCT. It never fails and never needs a choice of path, unlike path-following methods such as the Goldstein branch cut algorithm. The price is accuracy: where the data have residues, the method spreads the error over a wide area, it underestimates steep slopes, and the result is in general not congruent to the data, that is it does not differ from the wrapped phase by multiples of . It solves one formulation of the phase unwrapping problem.
In plain words
A wrapped phase image only knows each value up to a whole number of turns. The differences between neighbouring pixels are reliable as long as the true phase changes by less than half a turn per pixel, so the method takes those differences, wrapped back into half a turn, as a field of slopes.
Then it looks for the smooth image whose slopes match that field best, measured by the sum of the squared errors. Finding it is the same as solving a Poisson equation, the equation of a stretched membrane, and a cosine transform solves that equation in one step. Where the slope field is not consistent, the error is spread out evenly and is not hidden behind cuts.
The problem
Input. A wrapped phase image on an grid. The wrapping operator is with the integer that puts the value in .
Data. The wrapped differences along rows and columns,
Output. The image that minimizes
a least squares problem with unknowns, defined up to an additive constant. The code returns the solution with zero mean.
Residues. The sum of around a square of pixels is with the charge . A nonzero charge is a residue, and it means that the slope field is not the gradient of any image. Without residues the problem has an exact solution; with them it does not.
The algorithm
LS-UNWRAP(ψ) ▷ m × n wrapped phase- 1
g^x, g^y ← wrapped differences of ψ along rows and columns - 2
ρ(i,j) ← g^x(i,j) - g^x(i,j-1) + g^y(i,j) - g^y(i-1,j) ▷ missing terms are 0 - 3
ρ̂ ← DCT-II(ρ) ▷ two-dimensional - 4
φ̂(k,l) ← ρ̂(k,l) / (2 cos(π k/m) + 2 cos(π l/n) - 4) for (k,l) ≠ (0,0) - 5
φ̂(0,0) ← 0 ▷ the free constant - 6
φ ← inverse DCT-II(φ̂) - 7
return φ
Line L2 is the divergence of the slope field; a term that would use a difference outside the grid is dropped, which is the Neumann boundary condition. The normal equations of are with the five point Laplacian in which a border pixel has only its neighbours inside the grid. The cosine functions are the eigenvectors of that Laplacian, with the eigenvalues in the denominator of line L4, so lines L3 to L6 solve the equation exactly. The eigenvalue is zero only for , the constant image, and line L5 fixes that free constant.
Example
Take the image . Line L1 gives the row differences and , and the column differences and . Around the square, : one residue of charge , so no image fits all four differences.
Line L2 gives , which sums to 0. The DCT of line L3 gives , and , with . The denominators of line L4 are , and . The inverse DCT gives, after subtracting the value at ,
Each of the four differences of is the wrapped difference minus in the direction around the loop: , and so on. The error of is shared equally by the four edges, and . The result is not congruent to : is not a multiple of .
Correctness
The method is exact as an algorithm for the least squares problem, and that problem is exact for data without residues. The proofs are in proofs/correctness.md.
- Normal equations. is a convex quadratic, and its gradient is zero exactly when with the Neumann Laplacian. The grid graph is connected, so the kernel of is the constants, holds automatically, and the solution is unique up to a constant.
- The DCT solves the equation. The cosine satisfies , and its values just outside the grid equal the values on the border, so the dropped terms change nothing. The two-dimensional Laplacian is the sum of the row and column ones, so lines L3 to L6 return the zero mean solution.
- Exact without residues. If no loop of has a nonzero sum, is the gradient of an image , obtained by summing along any path, and . So the output is up to a constant, and it is congruent to . If the true phase also changes by less than between neighbours (Itoh's condition), the output is the true phase up to a constant.
- With residues. The misfit has the same loop sums as , so every loop that encloses a nonzero total charge carries misfit, however far it is from the residues. The error is not confined near the residues. It spreads.
Proof: The least squares unwrapped phase solves the discrete Poisson equation with Neumann boundary conditions, the DCT solves that equation exactly, and the result is exact when the wrapped gradient has no residuesfull
Notation. The grid has rows and columns. maps an image to its forward differences on the horizontal edges and the vertical edges: for the edge that points right or down. The data are the wrapped differences (line L1). The method minimizes .
Lemma 1 (the normal equations are a Neumann Poisson equation). minimizes if and only if , where sums over the neighbours of that lie in the grid, and $\rho = $ line L2, with missing terms equal to zero.
Proof. is a convex quadratic, so minimizes it if and only if . For one edge , puts at and at . So is the sum of over edges that end at minus the sum over edges that start at , which is . In the same way . A pixel on the border has fewer neighbours; this is the discrete form of the Neumann condition , here with the boundary flux taken as zero.
Lemma 2 (solvability and uniqueness). The kernel of is the constant images, , and the solutions of are one image plus any constant.
Proof. , which is zero if and only if is equal on the two ends of every edge, that is constant, since the grid graph is connected. is in the range of , which is orthogonal to the kernel of , the constants; so . A symmetric matrix maps onto the orthogonal complement of its kernel, so a solution exists, and two solutions differ by an element of the kernel.
Lemma 3 (the DCT diagonalizes the Neumann Laplacian). Let for . Then the one-dimensional Neumann Laplacian on points, , satisfies . In two dimensions, , and the eigenvalue is zero only for .
Proof. Extend to all integers by the same formula. The identity with and gives for every . At the missing neighbour has , so the term is zero and dropping it changes nothing. At , , so again the missing term is zero. The two-dimensional Laplacian is the sum of the one-dimensional ones along rows and columns, which gives the second formula. for , so the sum is zero only when .
The vectors are orthogonal with and for (eigenvectors of a symmetric matrix for distinct eigenvalues, and a direct sum for the norms). So the DCT-II of line L3, , has the inverse of line L6 with the weights , and , as in the code.
Theorem 1 (lines L1 to L7 return a least squares solution). The output of lines L1 to L7 minimizes , and it is the minimizer with zero mean.
Proof. Write by the inverse DCT. By Lemma 2, . Line L4 sets with from Lemma 3, and line L5 sets . By Lemma 3 and linearity, , using . By Lemma 1, minimizes . The mean of is .
Theorem 2 (exact without residues). Suppose that every loop of sums to zero (no residues). Then , the output satisfies on every edge, and is congruent to up to a constant: for one real . If in addition the true phase satisfies on every edge (the Itoh condition), then .
Proof. Define as the sum of along any path of grid edges from the pixel to (with a minus sign for edges walked backwards). Any two such paths differ by a closed walk, and every closed walk on the grid graph is a sum of boundaries of squares, so the sum of along it is a sum of loop sums, which are zero. So is well defined, and . By Lemma 2 every minimizer, and the output by Theorem 1, is plus a constant. Each differs from by a multiple of , so is a multiple of at every pixel. Under the Itoh condition, , so and is also a minimizer with ; Lemma 2 gives equality up to a constant.
Theorem 3 (with residues the error spreads). Let be the misfit of the output. Then , and for every closed loop the sum of along equals the sum of along , which is times the total residue charge enclosed. In particular, if some residue is nonzero, then and : no image reproduces all the wrapped differences.
Proof. by the normal equations. The sum of along any closed loop is zero (it telescopes), so the loop sums of and agree. The boundary of a square with charge has the loop sum , so some edge on it has .
For the grid of one square with charge , at each corner says that the misfit entering the corner equals the misfit leaving it, so has the same value on the four edges in the loop direction, and the loop sum gives : the error of is shared equally. Then on each edge, which is not congruent to modulo . This is the worked example of the main page. In general is the orthogonal projection of onto the kernel of (the cycle space of the grid graph), because is the projection onto the range of . By Theorem 3, every closed loop that encloses a nonzero total charge has a nonzero loop sum of , so is nonzero on at least one edge of each such loop, however far it is from the residues. The misfit forced by a residue cannot stay on the four edges around it. This is why least squares unwrapping spreads local errors over a wide area.
Lemma 4 (invariance). If for integers , the output is unchanged.
Proof. , so and everything after line L1 are unchanged.
Theorem 4 (cost). With a fast DCT, lines L1 to L7 cost operations and space. The direct sums of the reference code cost .
Proof. Lines L1, L2, L4, L5 and L7 cost per pixel. A two-dimensional DCT is transforms of length and transforms of length ; a fast DCT of length costs , and a direct one . Every array has entries.
Complexity
In the real-RAM model, lines L1, L2, L4 and L5 cost . With a fast DCT, lines L3 and L6 cost , which dominates. The space is . The reference code computes the DCT by direct sums in time, which is enough for the small test grids. Grid sizes that are not powers of two are handled by fast DCT algorithms built on any fast Fourier transform.
Properties
- Exact solver of its model (theorem). Lines L3 to L6 solve the Neumann Poisson equation without iteration or truncation.
- Exact without residues (theorem), and then congruent to the data.
- Not congruent in general (theorem for the example, observed in general). With residues the unwrapped phase does not equal the wrapped phase plus multiples of . A congruence step that adds the wrapped difference back to restores congruence.
- Slope underestimation (measurement). Where noise or undersampling makes some wrapped differences take the wrong branch, the squared error pulls the slope toward zero. In the test, a ramp of 2.6 rad per pixel with Gaussian noise of standard deviation 0.7 rad has 22 residues on a grid, and the mean slope of the output is 1.08 rad per pixel.
- Invariant to the wrap count of the input. Adding with integers to the input does not change the output.
- Never fails. There is no path, no cut and no choice; the output is defined for every input.
- Linear in the slope field. The map from to is linear; all the nonlinearity is in the wrapping of line L1.
Variants and improvements
- Weighted least squares (Ghiglia and Romero 1994). Weights from a quality map, for example the coherence in SAR interferometry, lower the influence of bad differences. The weighted Laplacian is no longer diagonal in the DCT basis; it is solved by the conjugate gradient method preconditioned with the unweighted DCT solver of this page, or by a multigrid method. A zero weight cuts the edge, which brings back some of the path independence problems of branch cuts.
- FFT form. Mirroring the image to and using the FFT gives the same result; the DCT form avoids the mirror.
- Minimum norm. Replacing the square by with concentrates the misfit on fewer edges. For the problem is a minimum cost flow problem on the dual grid (Costantini 1998), and the result is congruent. The problem, which counts the edges that disagree with , is NP-hard (Chen and Zebker 2000).
- Congruence step. Add to the output to get an image congruent to the data, with the least squares solution as a guide for the multiples.
- Laplacian based unwrapping in MRI and quantitative susceptibility mapping computes from instead of from wrapped differences and solves the same Poisson equation.
When to use it
Use the unweighted method as a fast, robust first unwrapping when the data are smooth and nearly free of residues, as a preconditioner, or when a result is needed everywhere without holes. Use it with weights for noisy interferograms. When the exact multiples of matter, as in topographic SAR interferometry, use a congruent method: Goldstein branch cuts, minimum cost flow, or the least squares result followed by a congruence step.
Pitfalls
- Slopes that are too low. Many wrong branches shrink the unwrapped range. In the test the slope falls from 2.6 to 1.08 rad per pixel. Check the result against the wrapped data with .
- Comparing unwrapped values directly. The output has zero mean, not the absolute phase. Only differences inside the image are meaningful.
- Wrong boundary condition. The FFT without mirroring imposes periodic boundary conditions, which add a jump between opposite borders. Use the DCT-II or a mirrored FFT.
- Wrong denominator. The eigenvalues are , with and not (that would be the periodic case). A wrong factor gives a smooth but wrong result that is hard to see.
- Division by zero. The coefficient has a zero eigenvalue; set it to zero, never divide.
- Weights of zero in the unweighted solver. Masked pixels must be handled by the weighted method; setting their phase to zero adds false slopes at the mask edge.
Implementations
The Python code computes the DCT by direct sums, so it needs no helper for the transform. The tests compare the result with the normal equations solved by Gaussian elimination from the shared imgla helper, check the Poisson equation and the zero mean, exact recovery without residues, the invariance to integer wraps, the example with the error of on each edge, and the slope underestimation with residues.
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the imaging and inverse problems pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Dense linear algebra on lists of rows (float, complex or Fraction entries).
A matrix is a list of rows. A vector is a list of numbers. The inner product
is <u, v> = sum_i conj(u_i) v_i, linear in the second argument, so that the
adjoint A^H satisfies <A x, y> = <x, A^H y>.
"""
import math
def _flat(x):
"""Flatten a list of rows (an image) into one list; a vector is returned as is."""
if x and isinstance(x[0], (list, tuple)):
return [v for row in x for v in row]
return x
def zeros(m, n):
"""The m x n zero matrix."""
return [[0.0] * n for _ in range(m)]
def eye(n):
"""The n x n identity matrix."""
out = zeros(n, n)
for i in range(n):
out[i][i] = 1.0
return out
def transpose(a):
"""A^T."""
return [list(col) for col in zip(*a)]
def conj_transpose(a):
"""A^H, the conjugate transpose."""
return [[v.conjugate() for v in col] for col in zip(*a)]
def matmul(a, b):
"""The product A B."""
bt = list(zip(*b))
return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]
def matvec(a, x):
"""The product A x."""
return [sum(v * w for v, w in zip(row, x)) for row in a]
def rmatvec(a, y):
"""The product A^H y."""
n = len(a[0]) if a else 0
out = [0.0] * n
for row, yi in zip(a, y):
if yi == 0:
continue
for j, v in enumerate(row):
out[j] += v.conjugate() * yi
return out
def dot(u, v):
"""<u, v> = sum_i conj(u_i) v_i. Images (lists of rows) are flattened."""
return sum(a.conjugate() * b for a, b in zip(_flat(u), _flat(v)))
def norm2(x):
"""The Euclidean norm. Images (lists of rows) are flattened."""
return math.sqrt(sum(abs(v) ** 2 for v in _flat(x)))
def solve(a, b):
"""Solve A x = b by Gaussian elimination with partial pivoting.
b is a vector or a matrix (a list of rows). A must be square and
nonsingular; a zero pivot raises ValueError. Fractions stay exact.
"""
n = len(a)
vec = not (b and isinstance(b[0], (list, tuple)))
rhs = [[bi] for bi in b] if vec else [list(r) for r in b]
m = [list(row) + rhs[i] for i, row in enumerate(a)]
w = len(m[0])
for c in range(n):
p = max(range(c, n), key=lambda r: abs(m[r][c]))
if m[p][c] == 0:
raise ValueError("singular matrix")
m[c], m[p] = m[p], m[c]
piv = m[c][c]
for r in range(c + 1, n):
f = m[r][c] / piv
if f != 0:
mr, mc = m[r], m[c]
for j in range(c, w):
mr[j] -= f * mc[j]
x = [[0.0] * (w - n) for _ in range(n)]
for r in range(n - 1, -1, -1):
for j in range(w - n):
s = m[r][n + j] - sum(m[r][k] * x[k][j] for k in range(r + 1, n))
x[r][j] = s / m[r][r]
return [row[0] for row in x] if vec else x
def cholesky(a):
"""Lower triangular L with A = L L^H for a Hermitian positive definite A."""
n = len(a)
low = zeros(n, n)
for j in range(n):
d = a[j][j] - sum(abs(low[j][k]) ** 2 for k in range(j))
d = d.real if isinstance(d, complex) else d
if not d > 0:
raise ValueError("matrix is not positive definite")
ljj = math.sqrt(d)
low[j][j] = ljj
for i in range(j + 1, n):
s = a[i][j] - sum(low[i][k] * low[j][k].conjugate() for k in range(j))
low[i][j] = s / ljj
return low
def cho_solve(low, b):
"""Solve (L L^H) x = b, with L from cholesky."""
n = len(low)
z = [0.0] * n
for i in range(n):
z[i] = (b[i] - sum(low[i][k] * z[k] for k in range(i))) / low[i][i]
x = [0.0] * n
for i in range(n - 1, -1, -1):
s = z[i] - sum(low[k][i].conjugate() * x[k] for k in range(i + 1, n))
x[i] = s / low[i][i].conjugate()
return x
def _rot_params(app, aqq, apq):
"""c, s of the Jacobi rotation that zeroes the (p, q) entry of [[app, apq], [apq, aqq]]."""
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(1.0 + t * t)
return c, c * t
def sym_eig(a, tol=1e-15, max_sweeps=100):
"""Eigenvalues (ascending) and eigenvectors (as columns) of a real symmetric matrix.
Cyclic Jacobi method. Returns (w, Q) with A = Q diag(w) Q^T.
"""
n = len(a)
m = [[float(v) for v in row] for row in a]
q = eye(n)
for _ in range(max_sweeps):
off = sum(m[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
scale = sum(m[i][i] ** 2 for i in range(n)) + off
if off <= (tol * tol) * scale or off == 0.0:
break
for p in range(n - 1):
for r in range(p + 1, n):
apq = m[p][r]
if apq == 0.0:
continue
c, s = _rot_params(m[p][p], m[r][r], apq)
for k in range(n):
mkp, mkr = m[k][p], m[k][r]
m[k][p] = c * mkp - s * mkr
m[k][r] = s * mkp + c * mkr
mp, mr = m[p], m[r]
for k in range(n):
mpk, mrk = mp[k], mr[k]
mp[k] = c * mpk - s * mrk
mr[k] = s * mpk + c * mrk
m[p][r] = m[r][p] = 0.0
for k in range(n):
qkp, qkr = q[k][p], q[k][r]
q[k][p] = c * qkp - s * qkr
q[k][r] = s * qkp + c * qkr
order = sorted(range(n), key=lambda i: m[i][i])
w = [m[i][i] for i in order]
qs = [[q[k][i] for i in order] for k in range(n)]
return w, qs
def _complete(cols, m):
"""Replace zero columns of an m-row column list by unit vectors orthogonal to the others."""
for idx, col in enumerate(cols):
if any(v != 0.0 for v in col):
continue
for e in range(m):
cand = [0.0] * m
cand[e] = 1.0
for _ in range(2):
for jdx, other in enumerate(cols):
if jdx == idx or not any(v != 0.0 for v in other):
continue
h = sum(a * b for a, b in zip(other, cand))
cand = [a - h * b for a, b in zip(cand, other)]
nrm = math.sqrt(sum(v * v for v in cand))
if nrm > 0.5:
cols[idx] = [v / nrm for v in cand]
break
return cols
def svd(a, tol=1e-15, max_sweeps=100):
"""Thin SVD of a real m x n matrix by one-sided Jacobi (Hestenes).
Returns (U, S, V) with p = min(m, n): U is m x p, S a list of p values in
descending order, V is n x p, U^T U = I, V^T V = I and A = U diag(S) V^T.
"""
m, n = len(a), len(a[0])
if m < n:
v, s, u = svd(transpose(a), tol, max_sweeps)
return u, s, v
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 r in range(p + 1, n):
cp, cr = cols[p], cols[r]
alpha = sum(x * x for x in cp)
beta = sum(x * x for x in cr)
gamma = sum(x * y for x, y in zip(cp, cr))
if gamma == 0.0 or abs(gamma) <= tol * math.sqrt(alpha * beta):
continue
rotated = True
c, s = _rot_params(alpha, beta, gamma)
cols[p] = [c * x - s * y for x, y in zip(cp, cr)]
cols[r] = [s * x + c * y for x, y in zip(cp, cr)]
vp, vr = vcols[p], vcols[r]
vcols[p] = [c * x - s * y for x, y in zip(vp, vr)]
vcols[r] = [s * x + c * y for x, y in zip(vp, vr)]
if not rotated:
break
sig = [math.sqrt(sum(x * x for x in col)) for col in cols]
# A column below 1e-150 times the largest one is zero to working precision;
# its squares underflow, so its direction carries no information.
floor = max(sig) * 1e-150 if sig else 0.0
sig = [t if t > floor and t > 1e-150 else 0.0 for t in sig]
order = sorted(range(n), key=lambda j: -sig[j])
s_out = [sig[j] for j in order]
ucols = [[x / sig[j] for x in cols[j]] if sig[j] > 0.0 else [0.0] * m for j in order]
ucols = _complete(ucols, m)
u = [[ucols[j][i] for j in range(n)] for i in range(m)]
v = [[vcols[j][i] for j in order] for i in range(n)]
return u, s_out, v
def adjoint_gap(apply_a, apply_ah, x, y):
"""|<A x, y> - <x, A^H y>| / (||A x|| ||y||) for given functions A and A^H.
x and y may be vectors or images (lists of rows). If the denominator is
zero, the absolute gap is returned.
"""
ax = apply_a(x)
gap = abs(dot(ax, y) - dot(x, apply_ah(y)))
den = norm2(ax) * norm2(y)
return gap / den if den > 0.0 else gap
least_squares_phase_unwrapping.py 130 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/least-squares-phase-unwrapping/. The authors are listed in prov/FX5THR.jsonl.
"""Unweighted least squares phase unwrapping by the method of Ghiglia and Romero (1994).
The input is a wrapped phase image psi[i][j] (rows i = 0 .. m-1, columns
j = 0 .. n-1) with values in (-pi, pi]. The output phi minimizes
sum (phi[i][j+1] - phi[i][j] - dx[i][j])^2 + sum (phi[i+1][j] - phi[i][j] - dy[i][j])^2
over all real images, where dx and dy are the wrapped differences of psi. The
normal equations are the discrete Poisson equation with Neumann boundary
conditions, which the two-dimensional DCT-II diagonalizes. phi is defined up to
an additive constant; this code returns the solution with zero mean.
The DCT here is computed by direct sums, O(m n (m + n)). A fast DCT gives
O(m n log(m n)).
"""
import math
TWO_PI = 2.0 * math.pi
def wrap(x):
"""The wrapping operator W: the value of x - 2 pi k in (-pi, pi]."""
y = math.fmod(x + math.pi, TWO_PI)
if y <= 0.0:
y += TWO_PI
return y - math.pi
def wrapped_gradients(psi):
"""dx[i][j] = W(psi[i][j+1] - psi[i][j]) for j < n - 1, dy[i][j] = W(psi[i+1][j] - psi[i][j]) for i < m - 1."""
m, n = len(psi), len(psi[0])
dx = [[wrap(psi[i][j + 1] - psi[i][j]) for j in range(n - 1)] for i in range(m)]
dy = [[wrap(psi[i + 1][j] - psi[i][j]) for j in range(n)] for i in range(m - 1)]
return dx, dy
def divergence(dx, dy, m, n):
"""rho[i][j] = dx[i][j] - dx[i][j-1] + dy[i][j] - dy[i-1][j], with missing terms taken as zero."""
rho = [[0.0] * n for _ in range(m)]
for i in range(m):
for j in range(n):
v = 0.0
if j < n - 1:
v += dx[i][j]
if j > 0:
v -= dx[i][j - 1]
if i < m - 1:
v += dy[i][j]
if i > 0:
v -= dy[i - 1][j]
rho[i][j] = v
return rho
def _dct_matrix(n):
"""c[k][t] = cos(pi k (2 t + 1) / (2 n)), the DCT-II basis."""
return [[math.cos(math.pi * k * (2 * t + 1) / (2.0 * n)) for t in range(n)] for k in range(n)]
def dct2(x):
"""Two-dimensional DCT-II: X[k][l] = sum_{i, j} x[i][j] cos(pi k (2i+1) / 2m) cos(pi l (2j+1) / 2n)."""
m, n = len(x), len(x[0])
cm, cn = _dct_matrix(m), _dct_matrix(n)
rows = [[sum(x[i][j] * cn[l][j] for j in range(n)) for l in range(n)] for i in range(m)]
return [[sum(cm[k][i] * rows[i][l] for i in range(m)) for l in range(n)] for k in range(m)]
def idct2(xh):
"""The inverse of dct2: x[i][j] = (1 / (m n)) sum_{k, l} w_k w_l X[k][l] cos(..) cos(..), w_0 = 1, w_k = 2."""
m, n = len(xh), len(xh[0])
cm, cn = _dct_matrix(m), _dct_matrix(n)
wm = [1.0] + [2.0] * (m - 1)
wn = [1.0] + [2.0] * (n - 1)
cols = [[sum(wm[k] * cm[k][i] * xh[k][l] for k in range(m)) / m for l in range(n)] for i in range(m)]
return [[sum(wn[l] * cn[l][j] * cols[i][l] for l in range(n)) / n for j in range(n)] for i in range(m)]
def neumann_laplacian(phi):
"""The five point Laplacian with mirror (Neumann) boundary: the sum over the existing neighbours of phi[q] - phi[p]."""
m, n = len(phi), len(phi[0])
out = [[0.0] * n for _ in range(m)]
for i in range(m):
for j in range(n):
v = 0.0
for a, b in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)):
if 0 <= a < m and 0 <= b < n:
v += phi[a][b] - phi[i][j]
out[i][j] = v
return out
def unwrap_least_squares(psi):
"""Return the zero mean least squares unwrapped phase of the wrapped image psi."""
m, n = len(psi), len(psi[0])
dx, dy = wrapped_gradients(psi) # @line L1
rho = divergence(dx, dy, m, n) # @line L2
rh = dct2(rho) # @line L3
ph = [[0.0] * n for _ in range(m)]
for k in range(m):
for l in range(n):
if k == 0 and l == 0:
continue # @line L5
den = 2.0 * math.cos(math.pi * k / m) + 2.0 * math.cos(math.pi * l / n) - 4.0
ph[k][l] = rh[k][l] / den # @line L4
phi = idct2(ph) # @line L6
return phi # @line L7
def residues(psi):
"""Residue charges: r[i][j] = (loop sum of wrapped differences around the 2 x 2 square at (i, j)) / (2 pi)."""
m, n = len(psi), len(psi[0])
out = [[0] * (n - 1) for _ in range(m - 1)]
for i in range(m - 1):
for j in range(n - 1):
s = (wrap(psi[i][j + 1] - psi[i][j]) + wrap(psi[i + 1][j + 1] - psi[i][j + 1])
+ wrap(psi[i + 1][j] - psi[i + 1][j + 1]) + wrap(psi[i][j] - psi[i + 1][j]))
out[i][j] = round(s / TWO_PI)
return out
def least_squares_cost(phi, psi):
"""The objective: the squared misfit between the gradient of phi and the wrapped gradients of psi."""
dx, dy = wrapped_gradients(psi)
m, n = len(psi), len(psi[0])
c = sum((phi[i][j + 1] - phi[i][j] - dx[i][j]) ** 2 for i in range(m) for j in range(n - 1))
c += sum((phi[i + 1][j] - phi[i][j] - dy[i][j]) ** 2 for i in range(m - 1) for j in range(n))
return c
test_least_squares_phase_unwrapping.py 123 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/least-squares-phase-unwrapping/. The authors are listed in prov/FX5THR.jsonl.
import math
import random
from imgla import solve
from least_squares_phase_unwrapping import (dct2, divergence, idct2, least_squares_cost, neumann_laplacian, residues,
unwrap_least_squares, wrap, wrapped_gradients)
TWO_PI = 2.0 * math.pi
def _wrap_image(phi):
return [[wrap(v) for v in row] for row in phi]
def _minus_first(phi):
c = phi[0][0]
return [[v - c for v in row] for row in phi]
def test_wrap() -> None:
assert abs(wrap(3 * math.pi / 2) + math.pi / 2) < 1e-15
assert abs(wrap(math.pi) - math.pi) < 1e-15
assert abs(wrap(-math.pi) - math.pi) < 1e-15
assert abs(wrap(7.0) - (7.0 - TWO_PI)) < 1e-15
def test_dct_round_trip() -> None:
rng = random.Random(7301)
x = [[rng.uniform(-1, 1) for _ in range(5)] for _ in range(4)]
y = idct2(dct2(x))
assert max(abs(a - b) for ra, rb in zip(x, y) for a, b in zip(ra, rb)) < 1e-12
def test_matches_the_normal_equations_solved_directly() -> None:
# Reference: build D^T D phi = D^T g with one pinned pixel and solve it by
# Gaussian elimination (imgla.solve); compare up to the additive constant.
rng = random.Random(7302)
m, n = 5, 6
psi = [[rng.uniform(-math.pi, math.pi) for _ in range(n)] for _ in range(m)]
assert any(r != 0 for row in residues(psi) for r in row)
dx, dy = wrapped_gradients(psi)
size = m * n
a = [[0.0] * size for _ in range(size)]
b = [0.0] * size
edges = [(i * n + j, i * n + j + 1, dx[i][j]) for i in range(m) for j in range(n - 1)]
edges += [(i * n + j, (i + 1) * n + j, dy[i][j]) for i in range(m - 1) for j in range(n)]
for p, q, g in edges:
a[p][p] += 1.0
a[q][q] += 1.0
a[p][q] -= 1.0
a[q][p] -= 1.0
b[p] -= g
b[q] += g
a[0] = [1.0] + [0.0] * (size - 1)
b[0] = 0.0
ref = solve(a, b)
got = _minus_first(unwrap_least_squares(psi))
for i in range(m):
for j in range(n):
assert abs(got[i][j] - ref[i * n + j]) < 1e-9
assert abs(least_squares_cost(got, psi) - least_squares_cost([ref[i * n:(i + 1) * n] for i in range(m)], psi)) < 1e-9
def test_solves_the_neumann_poisson_equation() -> None:
rng = random.Random(7303)
psi = [[rng.uniform(-math.pi, math.pi) for _ in range(7)] for _ in range(6)]
dx, dy = wrapped_gradients(psi)
rho = divergence(dx, dy, 6, 7)
assert abs(sum(sum(row) for row in rho)) < 1e-12
phi = unwrap_least_squares(psi)
lap = neumann_laplacian(phi)
assert max(abs(a - b) for ra, rb in zip(lap, rho) for a, b in zip(ra, rb)) < 1e-10
assert abs(sum(sum(row) for row in phi)) < 1e-10
def test_exact_recovery_without_residues() -> None:
m, n = 8, 9
true = [[0.9 * j - 0.5 * i + 1.5 * math.sin(0.4 * i * j / 3.0) for j in range(n)] for i in range(m)]
psi = _wrap_image(true)
assert all(r == 0 for row in residues(psi) for r in row)
got = _minus_first(unwrap_least_squares(psi))
want = _minus_first(true)
assert max(abs(a - b) for ra, rb in zip(got, want) for a, b in zip(ra, rb)) < 1e-9
def test_integer_wraps_of_the_input_do_not_change_the_output() -> None:
rng = random.Random(7304)
psi = [[rng.uniform(-math.pi, math.pi) for _ in range(5)] for _ in range(5)]
shifted = [[v + TWO_PI * rng.randint(-3, 3) for v in row] for row in psi]
a, b = unwrap_least_squares(psi), unwrap_least_squares(shifted)
assert max(abs(x - y) for ra, rb in zip(a, b) for x, y in zip(ra, rb)) < 1e-9
def test_two_by_two_with_one_residue_spreads_the_error() -> None:
psi = [[0.0, 2.0], [-2.0, 2.5]]
assert residues(psi) == [[1]]
got = _minus_first(unwrap_least_squares(psi))
q = math.pi / 2
want = [[0.0, 2.0 - q], [-(2.0 - q), 2.0 - q + 0.5 - q]]
assert max(abs(a - b) for ra, rb in zip(got, want) for a, b in zip(ra, rb)) < 1e-12
# The result is not congruent to the data: phi - psi is not a multiple of 2 pi.
assert abs(wrap(got[0][1] - psi[0][1])) > 1.5
def test_residues_bias_the_slope_low() -> None:
# A steep ramp plus noise: some wrapped differences take the wrong branch,
# and the least squares solution spreads those errors, so its mean slope is
# lower than the true slope. Without noise it is exact.
rng = random.Random(7305)
m, n, slope = 10, 10, 2.6
clean = [[slope * j for j in range(n)] for i in range(m)]
noisy = [[slope * j + rng.gauss(0.0, 0.7) for j in range(n)] for i in range(m)]
def mean_slope(phi):
return sum(phi[i][n - 1] - phi[i][0] for i in range(m)) / (m * (n - 1))
assert abs(mean_slope(unwrap_least_squares(_wrap_image(clean))) - slope) < 1e-9
psi = _wrap_image(noisy)
assert sum(abs(r) for row in residues(psi) for r in row) > 10
assert mean_slope(unwrap_least_squares(psi)) < 0.9 * slope
History
Least squares estimates of a phase from measured differences were first used for wavefront sensors in adaptive optics, and Hunt (1979) gave the matrix formulation of the problem. Itoh (1982) analyzed when unwrapping by summing wrapped differences is exact. For wrapped data, Ghiglia and Romero (1994) used the wrapped differences as the slope field, solved the unweighted problem with fast cosine transforms, and solved the weighted problem with preconditioned conjugate gradients. The book of Ghiglia and Pritt (1998) collects these minimum-norm methods together with path-following methods.
References
- Dennis C. Ghiglia and Louis A. Romero, Robust two-dimensional weighted and unweighted phase unwrapping that uses fast transforms and iterative methods, Journal of the Optical Society of America A 11(1), 1994, 107, the unweighted least squares problem as a Poisson equation with Neumann boundary conditions solved by the DCT, and the weighted problem by preconditioned conjugate gradients (general locator)
- B. R. Hunt, Matrix formulation of the reconstruction of phase values from phase differences, Journal of the Optical Society of America 69(3), 1979, 393, the least squares estimate of a phase from its differences in matrix form (general locator)
- Kazuyoshi Itoh, Analysis of the phase unwrapping algorithm, Applied Optics 21(14), 1982, 2470, the condition that the true phase differences lie in (-pi, pi) (general locator)
- Mario Costantini, A novel phase unwrapping method based on network programming, IEEE Transactions on Geoscience and Remote Sensing 36(3), 1998, 813 to 821, the minimum L1 unwrapping as a minimum cost flow problem (general locator)
- Curtis W. Chen and Howard A. Zebker, Network approaches to two-dimensional phase unwrapping: intractability and two new algorithms, Journal of the Optical Society of America A 17(3), 2000, 401, the NP-hardness of minimum L0 phase unwrapping (general locator)
- Dennis C. Ghiglia and Mark D. Pritt, Two-Dimensional Phase Unwrapping: Theory, Algorithms, and Software, Wiley, 1998, the chapter on minimum-norm methods (unweighted and weighted least squares, transform and iterative solvers)
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 FX5THR Edit this page History Report an error Markdown