Algorithmadvanced
Richardson-Lucy with total variation regularization
Also called RLTV.
Richardson-Lucy for Poisson data with a total variation penalty added one step late: divide each update by 1 - lam div(grad x/|grad x|) to damp noise and keep edges.
- Solves
- Image deblurring
- Time
- Θ(K n m) worst · average · best
- Space
- Θ(n) extra
- Where
- K = the number of iterations; m = the number of nonzero PSF entries; n = the number of pixels
- Model
- Real RAM
- Properties
- deterministiciterativenot linearnot monotone objectivenonnegativepoisson noise model
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Nicolas Dey, Laure Blanc Feraud, Christophe Zimmer, Pascal Roux, Zvi Kam, Jean Christophe Olivo Marin, Josiane Zerubia, 2006
Richardson-Lucy with total variation regularization (RLTV) is a deblurring method for photon-count images. It takes the multiplicative update of Richardson-Lucy, which is the EM algorithm for Poisson data, and divides it by a factor that comes from the total variation of the estimate:
Plain Richardson-Lucy fits the noise when it runs long, and the estimate breaks up into bright specks. The extra factor is larger than 1 at a local maximum of the estimate and smaller than 1 at a local minimum, so isolated peaks and pits are pulled toward their neighbors, while large flat regions and straight edges are left mostly alone. Dey and coauthors (2006) proposed it for 3D confocal microscopy. The step is the one-step-late form of maximum a posteriori estimation with a total variation prior: a positive fixed point minimizes the Poisson negative log-likelihood plus times the total variation. Unlike plain Richardson-Lucy it has no monotonicity theorem.
In plain words
You have a dim, blurred microscope image made of counted photons, and you know the blur. Richardson-Lucy improves a guess by blurring it, comparing it with the data, and multiplying each pixel by how much light is still missing there. If you repeat this many times, the guess starts to copy the random grain of the photon counts, and it turns into sharp specks. RLTV adds one more rule to each round. A pixel that stands above all its neighbors is made a little smaller, and a pixel that sits in a hole is made a little larger. A pixel in a smooth area or on a long straight edge is barely changed. One number sets how strong this rule is. Too weak, and the specks come back. Too strong, and the image turns into flat patches and the rounds can start to swing back and forth.
The problem
The unknown is a nonnegative image with pixels (2D or 3D). The data are counts , independent across pixels, with a known PSF , (see point spread function and Poisson distribution). The blur is periodic convolution with the PSF centered at index ; its adjoint is correlation, . The goal is the minimizer over of
the negative log-likelihood plus times the total variation. Here is the forward difference, , and the small makes the total variation differentiable. In Bayesian terms is the negative log-posterior for the prior , so its minimizer is a MAP estimate.
The algorithm
RLTV(y, h, lambda, K, x0, eps) ▷ x0 > 0, default the constant mean of y- 1
x ← x0 - 2
repeat K times - 3
c ← h~ * (y / (h * x)) ▷ Richardson-Lucy correction, two convolutions - 4
kappa ← div(grad x / |grad x|_eps) ▷ curvature of the level lines, in [-4, 4] - 5
d ← 1 - lambda · kappa ▷ stop with an error if some d ≤ 0 - 6
x ← x · c / d ▷ pixel by pixel - 7
return x
Line L3 is the Richardson-Lucy correction; a ratio with counts as . Line L4 uses forward differences for and backward differences for , so that is the negative adjoint of . Line L5 is the one-step-late term: the derivative of the total variation is taken at the current estimate. With the method is Richardson-Lucy.
Example
The effect of L4 to L6 is easiest to see with a delta PSF, where . Take a periodic image of ones with one pixel of value 2 at the center, , and . Then , and the step only divides by . The curvature is, to four places:
| pixel | |||
|---|---|---|---|
| center (value 2) | 1.3414 | 1.4910 | |
| above and left of it | 1.0000 | 0.9000 | 1.1111 |
| below and right of it | 0.7071 | 0.9293 | 1.0761 |
| all others | 0 | 1 | 1 |
The peak is pulled down and its neighbors go up. The asymmetry between the neighbors comes from the one-sided differences. The next step has , which pulls the estimate back toward the data, and the two forces fight. In this case the iteration does not settle: a measurement over 500 steps shows a period-2 checkerboard around the center for , and , and it converges only for with .
With a real blur the method works as intended. A measurement on one seed: a image with background 20 and a square of value 80, a Gaussian PSF with pixel, Poisson counts, the constant mean and . The error of the raw data is 165.7.
| RL () | RLTV, | RLTV, | RLTV, | |
|---|---|---|---|---|
| 10 | 143.2 | 135.0 | 121.9 | 119.2 |
| 20 | 160.8 | 138.6 | 110.2 | 111.0 |
| 40 | 196.9 | 147.7 | 103.1 | 104.5 |
| 80 | 259.5 | 159.1 | 100.7 | 102.8 |
| 200 | 391.5 | 172.0 | 101.5 | 108.1 |
Plain Richardson-Lucy is best near 10 steps and then fits the noise (semi-convergence). With the error keeps falling to about 100 and stays there. In the same runs, decreased in every step for , as the EM theorem says, but not for any of the three positive values.
Correctness
The full proof is in proofs/correctness.md. With and as in lines L3 and L4:
- Gradients. for the Poisson term (because ), and the gradient of the smoothed total variation is .
- A scaled gradient step. pixel by pixel.
- Fixed points. A positive with is a fixed point if and only if . is convex, so such a point is a global minimizer of over .
- Positivity. in 2D ( dimension in general). So for (in 3D, ) the denominator is at least , and a positive start stays nonnegative without clipping.
- Reduction. For the step is the EM step of Richardson-Lucy, which never increases the likelihood term and keeps the total flux.
The proof does not show that decreases or that the iterates converge for , and the measurements above show that neither holds in general.
Proof: The RLTV step is a scaled gradient step, its positive fixed points minimize the regularized Poisson objective, and it keeps the estimate nonnegative for lam < 1/4full
Setting. Images have pixels on a periodic grid. The blur is periodic convolution with and , and the adjoint is correlation, with . The data are counts. For with define
with forward differences and , and the backward difference operator, so that . Write
Lines L3 to L6 compute , entry by entry, with and .
Claim 1 (gradients). and .
Proof. , and at every pixel. For , the derivative of in is , so by the chain rule .
Claim 2 (a scaled gradient step). If at every pixel, then
Proof. By Claim 1, . So .
This is the one-step-late form of Green (1990): the derivative of the prior is taken at the current estimate and placed in the denominator of the EM step.
Claim 3 (fixed points). Let at every pixel with . Then if and only if , and then is a global minimizer of over the set .
Proof. The scale in Claim 2 is positive, so exactly when . is convex, because is convex and is linear in . is convex, because is a norm of composed with an affine map. So is convex, and a point where its gradient is zero is a global minimizer on the convex domain where is defined.
Claim 4 (the denominator is positive for lam < 1/4). Every entry of lies in . So for , at every pixel and every .
Proof. Let . Then and , because . The entry is a sum of four terms of modulus at most .
In dimensions the same argument gives , so ; for 3D stacks, .
Claim 5 (nonnegativity). If , where , and , then . A pixel with stays .
Proof. is a sum of nonnegative terms, so . The factors , and are nonnegative.
With Claim 4, the iteration started from a positive image never leaves the nonnegative orthant when , without any clipping. For larger the denominator can become zero or negative at a local minimum of , where ; the code raises an error then.
Claim 6 (lam = 0 is Richardson-Lucy). For , , the EM step for Poisson data with . Then (the EM monotonicity theorem), and .
Proof. The first part is the EM update with column sums . For the sum, .
What is not claimed. For the step is not an EM step, and Claim 2 does not give a descent: the scaled gradient step has no step size control. need not decrease, and the iterates need not converge. A measurement in the page shows both effects.
Complexity
In the real-RAM model one iteration costs two convolutions for L3 and for L4 to L6. A direct convolution with nonzero PSF entries costs ; with the FFT and the OTF computed once, . So iterations cost or . The extra space is for the ratio, the correction and the two gradient images. The total variation term adds about the cost of a few vector operations per step, so RLTV costs about the same per iteration as Richardson-Lucy. It usually needs more iterations, since the regularized result is the limit and not an early-stopped iterate.
Properties
- Nonnegative: for in 2D and a positive start, every iterate is nonnegative (Claim 4 of the proof).
- Nonlinear in , and the noise model is Poisson, as for Richardson-Lucy.
- The total flux is not kept exactly for ; in the first example it rises from 26 to about 27.5.
- A pixel that becomes stays , as in Richardson-Lucy.
- The result depends on and . Total variation favors piecewise constant images: edges stay sharp, but smooth ramps turn into steps (staircasing) and small low-contrast details are lost.
Variants and improvements
- 3D stacks. The original use: the same step with 3D differences, often with a different spacing along the optical axis. The positivity bound becomes .
- Other priors in the one-step-late form. Any differentiable prior gives ; Green (1990) introduced this form for emission tomography (see the one-step-late algorithm). Tikhonov and entropy priors are common choices.
- Convergent splittings. To minimize the same with a guarantee, use a primal-dual or splitting method, such as split Bregman or ADMM, with the total variation handled by a proximal step such as Chambolle's projection. These cost more per iteration but do not oscillate.
- Damped steps. Replace by with chosen by a line search on ; by Claim 2 the direction is a scaled descent direction, so a small enough lowers .
When to use it
Use RLTV for fluorescence microscopy, confocal stacks and other photon-limited images when the object is made of regions with sharp borders, the PSF is known and the noise is close to Poisson. It is a small change to an existing Richardson-Lucy code, which makes it popular in practice. Pick well below , relative to the scale of the counts, and watch the result for oscillation. When the object has smooth gradients, such as a diffuse cell body, total variation causes staircasing, and a smoother prior or plain Richardson-Lucy with early stopping may be better. When a guaranteed minimizer of is needed, use a convergent splitting method.
Pitfalls
- The step is not EM for . can rise from one step to the next, and the iterates can oscillate, as in the first example. A large makes this worse.
- If at a pixel, the step gives a negative or infinite value. For in 2D this cannot happen.
- A very small makes jump between for tiny changes of the estimate in flat regions, which amplifies the oscillation. A larger is safer (a heuristic; in the first example only converged).
- Total variation depends on the image scale: that works for counts near 100 is far too strong for counts near 1, because the Poisson term scales with the counts and the total variation term with their differences.
- The periodic boundary links opposite borders. Pad the image, or use another boundary rule, when the object touches the border.
- The quality depends on the PSF model. A PSF that ignores the depth-dependent aberration of the Gibson-Lanni model gives artifacts deep in the sample, whatever is.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the imaging and inverse problems pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small images and signals for the imaging and inverse problems pages.
Conventions:
- A signal is a list of numbers. An image is a list of rows, img[i][j], with
row i from the top and column j from the left.
- An n x n image covers the square [-1, 1]^2. The center of pixel (i, j) is
x_j = -1 + (2 j + 1) / n and y_i = 1 - (2 i + 1) / n, so y goes up.
- DFT: X_k = sum_j x_j exp(-2 pi i j k / n), unnormalized; the inverse has
the factor 1 / n. Index k stands for frequency k for k < n / 2 and k - n
otherwise. fftshift moves the zero frequency to position n // 2.
- Periodic convolution kernels are stored with their center at index 0
(wrapped around), so a delta kernel gives the identity and no shift.
"""
import cmath
import math
# ------------------------------------------------------------------ images
def new_image(n1, n2, value=0.0):
"""An n1 x n2 image (n1 rows, n2 columns) filled with value."""
return [[value] * n2 for _ in range(n1)]
def img_add(a, b):
"""The pixelwise sum a + b."""
return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
def img_scale(a, c):
"""The image c a."""
return [[c * x for x in row] for row in a]
def img_dot(a, b):
"""<a, b> = sum conj(a_ij) b_ij."""
return sum(x.conjugate() * y for ra, rb in zip(a, b) for x, y in zip(ra, rb))
def img_norm(a):
"""The Euclidean (Frobenius) norm of an image."""
return math.sqrt(sum(abs(x) ** 2 for row in a for x in row))
def flatten(img):
"""Row-major vector of an image."""
return [x for row in img for x in row]
def unflatten(v, n1, n2):
"""The n1 x n2 image of a row-major vector."""
return [list(v[i * n2:(i + 1) * n2]) for i in range(n1)]
# ------------------------------------------------------------------ DFT
def _is_pow2(n):
return n > 0 and n & (n - 1) == 0
def _fft_pow2(x):
"""Iterative radix-2 FFT, unnormalized forward transform."""
n = len(x)
a = [complex(v) for v in x]
j = 0
for i in range(1, n):
bit = n >> 1
while j & bit:
j ^= bit
bit >>= 1
j |= bit
if i < j:
a[i], a[j] = a[j], a[i]
size = 2
while size <= n:
half = size // 2
tw = [cmath.exp(-2j * math.pi * k / size) for k in range(half)]
for start in range(0, n, size):
for k in range(half):
u = a[start + k]
v = a[start + k + half] * tw[k]
a[start + k] = u + v
a[start + k + half] = u - v
size *= 2
return a
def dft(x):
"""X_k = sum_j x_j exp(-2 pi i j k / n). Radix-2 FFT when n is a power of 2."""
n = len(x)
if n == 0:
return []
if _is_pow2(n):
return _fft_pow2(x)
w = [cmath.exp(-2j * math.pi * t / n) for t in range(n)]
return [sum(x[j] * w[(j * k) % n] for j in range(n)) for k in range(n)]
def idft(xf):
"""x_j = (1/n) sum_k X_k exp(2 pi i j k / n)."""
n = len(xf)
if n == 0:
return []
y = dft([complex(v).conjugate() for v in xf])
return [v.conjugate() / n for v in y]
def _rows_then_cols(img, f):
rows = [f(row) for row in img]
cols = [f(list(col)) for col in zip(*rows)]
return [list(r) for r in zip(*cols)]
def dft2(img):
"""2D DFT: X_kl = sum_jq x_jq exp(-2 pi i (j k / n1 + q l / n2))."""
return _rows_then_cols(img, dft)
def idft2(img):
"""Inverse 2D DFT, with the factor 1 / (n1 n2)."""
return _rows_then_cols(img, idft)
def _shift1(x, s):
return list(x[s:]) + list(x[:s])
def fftshift(x):
"""Move the zero frequency to position n // 2 (1D, or both axes of an image)."""
if x and isinstance(x[0], (list, tuple)):
rows = [fftshift(r) for r in x]
return _shift1(rows, (len(rows) + 1) // 2)
return _shift1(x, (len(x) + 1) // 2)
def ifftshift(x):
"""The inverse of fftshift (1D, or both axes of an image)."""
if x and isinstance(x[0], (list, tuple)):
rows = [ifftshift(r) for r in x]
return _shift1(rows, len(rows) // 2)
return _shift1(x, len(x) // 2)
def circ_conv(x, h):
"""Periodic convolution y_i = sum_j h_j x_{(i - j) mod n}, kernel centered at index 0."""
n = len(x)
nz = [(j, hj) for j, hj in enumerate(h) if hj != 0]
return [sum(hj * x[(i - j) % n] for j, hj in nz) for i in range(n)]
def circ_conv2(img, h):
"""Periodic 2D convolution with the kernel h centered at index (0, 0)."""
n1, n2 = len(img), len(img[0])
nz = [(p, q, h[p][q]) for p in range(len(h)) for q in range(len(h[0])) if h[p][q] != 0]
out = new_image(n1, n2)
for i in range(n1):
for j in range(n2):
out[i][j] = sum(v * img[(i - p) % n1][(j - q) % n2] for p, q, v in nz)
return out
# ------------------------------------------------------------------ phantoms
def pixel_centers(n):
"""(xs, ys): xs[j] = -1 + (2 j + 1) / n and ys[i] = 1 - (2 i + 1) / n."""
xs = [-1.0 + (2 * j + 1) / n for j in range(n)]
ys = [1.0 - (2 * i + 1) / n for i in range(n)]
return xs, ys
# Rows: rho, A, B, x0, y0, phi (degrees). A is the semi-axis along the
# direction phi (counterclockwise from the x axis), B the other semi-axis.
# Geometry and densities of Shepp and Logan (1974), as reproduced in Kak and
# Slaney, Principles of Computerized Tomographic Imaging, Table 3.1. The value
# at the center (0, 0) is 2 - 0.98 = 1.02.
SHEPP_LOGAN = [
(2.0, 0.92, 0.69, 0.0, 0.0, 90.0),
(-0.98, 0.874, 0.6624, 0.0, -0.0184, 90.0),
(-0.02, 0.31, 0.11, 0.22, 0.0, 72.0),
(-0.02, 0.41, 0.16, -0.22, 0.0, 108.0),
(0.01, 0.25, 0.21, 0.0, 0.35, 90.0),
(0.01, 0.046, 0.046, 0.0, 0.1, 0.0),
(0.01, 0.046, 0.046, 0.0, -0.1, 0.0),
(0.01, 0.046, 0.023, -0.08, -0.605, 0.0),
(0.01, 0.023, 0.023, 0.0, -0.605, 0.0),
(0.01, 0.046, 0.023, 0.06, -0.605, 90.0),
]
# The same ellipses with the gray levels of Toft (1996), which give more
# contrast. The value at the center is 1 - 0.8 = 0.2.
MODIFIED_SHEPP_LOGAN = [
(rho, a, b, x0, y0, phi)
for rho, (_, a, b, x0, y0, phi) in zip(
(1.0, -0.8, -0.2, -0.2, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1), SHEPP_LOGAN
)
]
def ellipse_value(x, y, table):
"""The phantom value at the point (x, y): the sum of rho over the ellipses that hold it."""
total = 0.0
for rho, a, b, x0, y0, phi in table:
c, s = math.cos(math.radians(phi)), math.sin(math.radians(phi))
dx, dy = x - x0, y - y0
u = dx * c + dy * s
v = -dx * s + dy * c
if (u / a) ** 2 + (v / b) ** 2 <= 1.0:
total += rho
return total
def ellipse_phantom(n, table):
"""The n x n image of an ellipse table, sampled at the pixel centers."""
xs, ys = pixel_centers(n)
return [[ellipse_value(x, y, table) for x in xs] for y in ys]
def disk_phantom(n, radius):
"""1 at pixel centers with x^2 + y^2 <= radius^2, 0 elsewhere."""
xs, ys = pixel_centers(n)
r2 = radius * radius
return [[1.0 if x * x + y * y <= r2 else 0.0 for x in xs] for y in ys]
def spikes_1d(n, positions, amplitudes):
"""A signal of length n with the given amplitudes at the given positions."""
out = [0.0] * n
for p, a in zip(positions, amplitudes):
out[p] += a
return out
# ------------------------------------------------------------------ projector
def parallel_beam_matrix(n, angles, nbins):
"""Pixel-driven discrete Radon transform of an n x n image on [-1, 1]^2.
Each pixel center (x, y) projects to s = x cos(theta) + y sin(theta). Its
value times the pixel area over the bin width is split linearly between
the two nearest bin centers. The bins cover [-sqrt(2), sqrt(2)]. Row
a * nbins + b holds angle a and bin b; column i * n + j holds pixel (i, j).
Returns the sparse rows, each a list of (column, weight) pairs.
Pixel-driven projection has a ripple: with a bin width close to the pixel
size, a disk projection is off by up to about 10 percent in some bins. A
bin of about twice the pixel size (nbins = 23 for n = 32) keeps it near
1 percent.
"""
xs, ys = pixel_centers(n)
smax = math.sqrt(2.0)
width = 2.0 * smax / nbins
scale = (2.0 / n) ** 2 / width
rows = []
for theta in angles:
c, s = math.cos(theta), math.sin(theta)
acc = [dict() for _ in range(nbins)]
for i, y in enumerate(ys):
for j, x in enumerate(xs):
t = (x * c + y * s + smax) / width - 0.5
b0 = math.floor(t)
frac = t - b0
col = i * n + j
for b, w in ((b0, 1.0 - frac), (b0 + 1, frac)):
if 0 <= b < nbins and w > 0.0:
acc[b][col] = acc[b].get(col, 0.0) + w * scale
rows.extend(sorted(d.items()) for d in acc)
return rows
def sp_matvec(rows, x):
"""y = A x for sparse rows of (column, weight) pairs."""
return [sum(w * x[c] for c, w in row) for row in rows]
def sp_rmatvec(rows, y, ncols):
"""x = A^H y for sparse rows of (column, weight) pairs and ncols columns."""
out = [0.0] * ncols
for row, yi in zip(rows, y):
if yi == 0:
continue
for c, w in row:
out[c] += w.conjugate() * yi
return out
# ------------------------------------------------------------------ noise
def gauss_noise(rng, shape, sigma):
"""Independent N(0, sigma^2) values: a list for an int shape, an image for (n1, n2)."""
if isinstance(shape, int):
return [rng.gauss(0.0, sigma) for _ in range(shape)]
n1, n2 = shape
return [[rng.gauss(0.0, sigma) for _ in range(n2)] for _ in range(n1)]
def _poisson_small(rng, lam):
"""Knuth's product method, exact for a mean lam <= 30."""
limit = math.exp(-lam)
k, p = 0, rng.random()
while p > limit:
k += 1
p *= rng.random()
return k
def poisson_sample(rng, lam):
"""An exact Poisson(lam) sample: a sum of Knuth samples with means at most 30."""
if lam < 0:
raise ValueError("negative mean")
total = 0
while lam > 30.0:
total += _poisson_small(rng, 30.0)
lam -= 30.0
if lam > 0.0:
total += _poisson_small(rng, lam)
return total
richardson_lucy_total_variation.py 107 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/richardson-lucy-total-variation/. The authors are listed in prov/DC5KCE.jsonl.
"""Richardson-Lucy with total variation regularization (RLTV), after Dey et al. (2006).
Images are lists of rows. The blur is periodic 2D convolution with a PSF h of
the image size, stored with its center at (0, 0), h >= 0 and sum h = 1. The
update is
x <- x / (1 - lam div(grad x / |grad x|_eps)) * (h~ * (y / (h * x)))
with forward differences for grad, the negative adjoint (backward
differences) for div, a periodic border and |g|_eps = sqrt(g1^2 + g2^2 + eps^2).
"""
import math
from imgkit import circ_conv2
def mirror(h):
"""The PSF h(-r) on the same periodic grid."""
n1, n2 = len(h), len(h[0])
return [[h[(-i) % n1][(-j) % n2] for j in range(n2)] for i in range(n1)]
def grad(x):
"""Forward differences with a periodic border: (x[i+1][j] - x[i][j], x[i][j+1] - x[i][j])."""
n1, n2 = len(x), len(x[0])
g1 = [[x[(i + 1) % n1][j] - x[i][j] for j in range(n2)] for i in range(n1)]
g2 = [[x[i][(j + 1) % n2] - x[i][j] for j in range(n2)] for i in range(n1)]
return g1, g2
def div(p1, p2):
"""Backward differences, the negative adjoint of grad: <grad x, p> = -<x, div p>."""
n1, n2 = len(p1), len(p1[0])
return [[p1[i][j] - p1[(i - 1) % n1][j] + p2[i][j] - p2[i][(j - 1) % n2] for j in range(n2)] for i in range(n1)]
def tv_curvature(x, eps):
"""div(grad x / |grad x|_eps). Every entry lies in [-4, 4]."""
g1, g2 = grad(x)
n1, n2 = len(x), len(x[0])
p1 = [[0.0] * n2 for _ in range(n1)]
p2 = [[0.0] * n2 for _ in range(n1)]
for i in range(n1):
for j in range(n2):
m = math.sqrt(g1[i][j] ** 2 + g2[i][j] ** 2 + eps * eps)
p1[i][j] = g1[i][j] / m
p2[i][j] = g2[i][j] / m
return div(p1, p2)
def tv(x, eps):
"""The smoothed total variation sum sqrt(g1^2 + g2^2 + eps^2)."""
g1, g2 = grad(x)
return sum(math.sqrt(a * a + b * b + eps * eps) for ra, rb in zip(g1, g2) for a, b in zip(ra, rb))
def neg_log_likelihood(x, y, h):
"""sum (h * x - y log(h * x)), the Poisson negative log-likelihood up to a constant."""
b = circ_conv2(x, h)
total = 0.0
for rb, ry in zip(b, y):
for bi, yi in zip(rb, ry):
total += bi - (yi * math.log(bi) if yi > 0 else 0.0)
return total
def objective(x, y, h, lam, eps):
"""The functional that RLTV is built from: the Poisson term plus lam times TV."""
return neg_log_likelihood(x, y, h) + lam * tv(x, eps)
def rl_correction(x, y, h, ht=None):
"""c = h~ * (y / (h * x)), the Richardson-Lucy correction factor."""
if ht is None:
ht = mirror(h)
b = circ_conv2(x, h)
r = [[(yi / bi if yi > 0 else 0.0) for bi, yi in zip(rb, ry)] for rb, ry in zip(b, y)]
return circ_conv2(r, ht)
def rltv(y, h, lam, iters, x0=None, eps=1e-3, callback=None):
"""Run iters RLTV steps from x0 (default: the constant mean of y). lam = 0 gives Richardson-Lucy."""
n1, n2 = len(y), len(y[0])
if x0 is None:
mean = sum(map(sum, y)) / (n1 * n2)
x0 = [[mean] * n2 for _ in range(n1)]
ht = mirror(h)
x = [list(row) for row in x0] # @line L1
for k in range(iters): # @line L2
c = rl_correction(x, y, h, ht) # @line L3
kappa = tv_curvature(x, eps) # @line L4
new = []
for i in range(n1):
row = []
for j in range(n2):
d = 1.0 - lam * kappa[i][j] # @line L5
if d <= 0.0:
raise ValueError("1 - lam div(grad x / |grad x|) <= 0; lower lam")
row.append(x[i][j] * c[i][j] / d) # @line L6
new.append(row)
x = new
if callback is not None:
callback(k + 1, x)
return x # @line L7
test_richardson_lucy_total_variation.py 177 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/richardson-lucy-total-variation/. The authors are listed in prov/DC5KCE.jsonl.
import math
import random
import pytest
from imgkit import circ_conv2, img_norm, poisson_sample
from richardson_lucy_total_variation import (
div,
grad,
neg_log_likelihood,
objective,
rl_correction,
rltv,
tv,
tv_curvature,
)
def gaussian_psf(n, sigma):
h = [[0.0] * n for _ in range(n)]
for di in range(-2, 3):
for dj in range(-2, 3):
h[di % n][dj % n] = math.exp(-(di * di + dj * dj) / (2 * sigma * sigma))
s = sum(map(sum, h))
return [[v / s for v in row] for row in h]
def rand_img(rng, n1, n2, lo=0.5, hi=3.0):
return [[rng.uniform(lo, hi) for _ in range(n2)] for _ in range(n1)]
def inner(a, b):
return sum(p * q for ra, rb in zip(a, b) for p, q in zip(ra, rb))
def diff(a, b):
return [[p - q for p, q in zip(ra, rb)] for ra, rb in zip(a, b)]
def numeric_grad(f, x, h=1e-6):
out = []
for i in range(len(x)):
row = []
for j in range(len(x[0])):
xp = [list(r) for r in x]
xm = [list(r) for r in x]
xp[i][j] += h
xm[i][j] -= h
row.append((f(xp) - f(xm)) / (2 * h))
out.append(row)
return out
def matrix_em_step(x, y, h):
"""The EM update for Poisson data with an explicit blur matrix, as a reference."""
n1, n2 = len(x), len(x[0])
n = n1 * n2
a = [[h[(i1 - j1) % n1][(i2 - j2) % n2] for j1 in range(n1) for j2 in range(n2)]
for i1 in range(n1) for i2 in range(n2)]
xv = [v for row in x for v in row]
yv = [v for row in y for v in row]
b = [sum(a[i][j] * xv[j] for j in range(n)) for i in range(n)]
col = [sum(a[i][j] for i in range(n)) for j in range(n)]
out = [xv[j] / col[j] * sum(a[i][j] * yv[i] / b[i] for i in range(n) if yv[i] > 0) for j in range(n)]
return [out[i * n2:(i + 1) * n2] for i in range(n1)]
def test_div_is_the_negative_adjoint_of_grad():
rng = random.Random(1)
x = rand_img(rng, 5, 7, -1, 1)
p1, p2 = rand_img(rng, 5, 7, -1, 1), rand_img(rng, 5, 7, -1, 1)
g1, g2 = grad(x)
lhs = inner(g1, p1) + inner(g2, p2)
rhs = -inner(x, div(p1, p2))
scale = math.sqrt(img_norm(g1) ** 2 + img_norm(g2) ** 2) * math.sqrt(img_norm(p1) ** 2 + img_norm(p2) ** 2)
assert abs(lhs - rhs) <= 1e-10 * scale
def test_blur_adjoint():
rng = random.Random(2)
h = gaussian_psf(8, 1.0)
x, y = rand_img(rng, 8, 8, -1, 1), rand_img(rng, 8, 8, -1, 1)
hx = circ_conv2(x, h)
ht = [[h[(-i) % 8][(-j) % 8] for j in range(8)] for i in range(8)]
assert abs(inner(hx, y) - inner(x, circ_conv2(y, ht))) <= 1e-10 * img_norm(hx) * img_norm(y)
def test_tv_curvature_is_minus_the_tv_gradient_and_is_bounded():
rng = random.Random(3)
x = rand_img(rng, 6, 6)
eps = 0.1
num = numeric_grad(lambda z: tv(z, eps), x)
kappa = tv_curvature(x, eps)
for rn, rk in zip(num, kappa):
for a, b in zip(rn, rk):
assert abs(a + b) < 1e-6
for _ in range(5):
z = rand_img(rng, 6, 6, 0, 10)
assert all(-4 <= v <= 4 for row in tv_curvature(z, 1e-6) for v in row)
def test_poisson_gradient_is_one_minus_the_rl_correction():
rng = random.Random(4)
h = gaussian_psf(6, 0.8)
x = rand_img(rng, 6, 6)
y = [[float(rng.randint(0, 5)) for _ in range(6)] for _ in range(6)]
num = numeric_grad(lambda z: neg_log_likelihood(z, y, h), x)
c = rl_correction(x, y, h)
for rn, rc in zip(num, c):
for a, b in zip(rn, rc):
assert abs(a - (1 - b)) < 1e-6
def test_the_step_is_a_scaled_gradient_step():
# x+ - x = -(x / (1 - lam kappa)) * grad J, so x is a fixed point exactly where grad J = 0.
rng = random.Random(5)
h = gaussian_psf(6, 0.8)
x = rand_img(rng, 6, 6)
y = [[float(rng.randint(0, 6)) for _ in range(6)] for _ in range(6)]
lam, eps = 0.05, 0.2
num = numeric_grad(lambda z: objective(z, y, h, lam, eps), x)
kappa = tv_curvature(x, eps)
xp = rltv(y, h, lam, 1, x0=x, eps=eps)
for i in range(6):
for j in range(6):
expect = x[i][j] - x[i][j] / (1 - lam * kappa[i][j]) * num[i][j]
assert abs(xp[i][j] - expect) < 1e-5
def test_lam_zero_is_richardson_lucy():
rng = random.Random(6)
h = gaussian_psf(6, 1.0)
y = [[float(rng.randint(0, 9)) for _ in range(6)] for _ in range(6)]
mean =sum(map(sum, y)) / 36
ref = [[mean] * 6 for _ in range(6)]
for _ in range(3):
ref = matrix_em_step(ref, y, h)
x = rltv(y, h, 0.0, 3)
assert img_norm(diff(x, ref)) < 1e-10 * img_norm(ref)
def test_delta_psf_gives_the_data_in_one_step():
rng = random.Random(7)
delta = [[1.0 if (i, j) == (0, 0) else 0.0 for j in range(5)] for i in range(5)]
y = rand_img(rng, 5, 5)
x = rltv(y, delta, 0.0, 1, x0=rand_img(rng, 5, 5))
assert img_norm(diff(x, y)) < 1e-12 * img_norm(y)
def test_positivity_for_small_lam_and_failure_for_large_lam():
rng = random.Random(8)
h = gaussian_psf(8, 1.0)
y = [[float(rng.randint(0, 20)) for _ in range(8)] for _ in range(8)]
x = rltv(y, h, 0.24, 20, eps=1e-6)
assert all(v >= 0 for row in x for v in row)
pit = [[1.0] * 8 for _ in range(8)]
pit[3][3] = 0.01
with pytest.raises(ValueError):
rltv(y, h, 0.5, 1, x0=pit, eps=1e-6)
def test_tv_term_lowers_the_error_on_noisy_counts():
# A measurement on one seed: a piecewise constant phantom, Poisson counts, 80 iterations.
n = 16
rng = random.Random(9)
xt = [[20.0 + (60.0 if 4 <= i < 11 and 5 <= j < 12 else 0.0) for j in range(n)] for i in range(n)]
h = gaussian_psf(n, 1.0)
b = circ_conv2(xt, h)
y = [[float(poisson_sample(rng, v)) for v in row] for row in b]
rl = rltv(y, h, 0.0, 80)
tvx = rltv(y, h, 0.02, 80, eps=1e-2)
e_rl = img_norm(diff(rl, xt))
e_tv = img_norm(diff(tvx, xt))
assert e_tv < 0.9 * e_rl
History
W. H. Richardson (1972) and L. B. Lucy (1974) introduced the multiplicative iteration, and Shepp and Vardi (1982) showed it is the EM algorithm for Poisson emission data. Rudin, Osher and Fatemi (1992) introduced total variation for noise removal. P. J. Green (1990) proposed the one-step-late modification of EM for MAP estimation with a prior in emission tomography. Dey, Blanc-Feraud, Zimmer, Roux, Kam, Olivo-Marin and Zerubia (2006) put total variation into this form for 3D confocal microscopy.
References
- N. Dey, L. Blanc-Feraud, C. Zimmer, P. Roux, Z. Kam, J.-C. Olivo-Marin and J. Zerubia, Richardson-Lucy algorithm with total variation regularization for 3D confocal microscope deconvolution, Microscopy Research and Technique 69(4), 2006, pages 260 to 266
- William Hadley Richardson, Bayesian-based iterative method of image restoration, Journal of the Optical Society of America 62(1), 1972, pages 55 to 59
- L. B. Lucy, An iterative technique for the rectification of observed distributions, The Astronomical Journal 79, 1974, the article from page 745
- Leonid I. Rudin, Stanley Osher and Emad Fatemi, Nonlinear total variation based noise removal algorithms, Physica D 60(1-4), 1992, pages 259 to 268
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 DC5KCE Edit this page History Report an error Markdown