Algorithmadvanced
Digital holography reconstruction
Also called numerical hologram reconstruction.
Recover the complex object wave from a recorded hologram by filtering one sideband in Fourier space and numerically propagating it to focus.
- Solves
- Phase retrieval
- Time
- O(n^2 log n) worst
- Space
- O(n^2) extra
- Where
- n = the side of an n x n hologram, a power of two, with an FFT
- Model
- Real RAM
- Properties
- deterministicexactnot in placeoffline
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Ulf Schnars, Werner Juptner, 1994
Digital holography reconstruction computes the complex wave of an object, both its amplitude and its phase, from one intensity image, the hologram, recorded on a camera. The hologram is the interference of the object wave with a known reference wave. In the off-axis geometry the reference arrives at an angle, so the term that carries the object wave sits at its own place in the Fourier transform of the hologram. The algorithm cuts out that term, moves it to the center, and refocuses it with the angular spectrum method. It solves the phase retrieval problem by experiment design: the reference makes the phase visible in the intensity.
In plain words
A camera records only brightness. To see the phase of a light wave, the setup adds a second, clean wave that comes in at a small angle. Where the two waves add up the camera sees bright lines, and where they cancel it sees dark lines. The exact position of the lines shifts with the phase of the object wave, so the phase is now written in the brightness.
The computer takes the frequency picture of the recorded image. Because of the angle, the useful part sits away from the center, apart from two unwanted parts. The method cuts the useful part out, moves it back to the center, and transforms it back. The result is the wave at the camera. A second step moves the wave back to the object plane to bring it into focus, as a lens would.
The problem
The object wave on the sensor is a complex field on an grid with spacing . The reference is the tilted plane wave with a known amplitude and an integer carrier , in DFT index units. The camera records the hologram
The task is to find , and then the wave in the object plane at distance before the sensor, with for the propagation of the angular spectrum method. Only the third term carries linearly. The fourth carries , which gives the twin image. The DFT is unnormalized, and a DFT index stands for its signed value , in .
The algorithm
is the half-width of the square passband in DFT index units, and is the transfer function of free space for the distance , zero for evanescent waves.
DH-RECONSTRUCT(h, c, B, r, d, λ, z)- 1
Ĥ <- DFT2(h) - 2
for each index k = (k1, k2), with S[k] <- 0 at the start do - 3
if |k̄1| <= B and |k̄2| <= B then - 4
S[k] <- Ĥ[k - c] / r ▷ cut the sideband at -c and move it to 0 - 5
S[k] <- S[k] · H_-z(k) ▷ back-propagate to the object plane - 6
return IDFT2(S)
Line L4 does the demodulation and the filtering in one step: the window around is read and written to the window around . Dividing by removes the reference amplitude. With the output is the wave on the sensor. Lines L2 to L5 cost , so the algorithm needs only one forward and one inverse FFT.
The carrier. If the tilt of the reference is not known, take the peak of outside a small central square: for an object with a strong unscattered wave, the sidebands peak at . The hologram is real, so , and the sign of cannot be found from the data. The wrong sign reconstructs the twin wave, which focuses at instead of .
Example
Take rows and columns, m and m, so every grid frequency propagates. The object wave on the sensor is a random field whose DFT is nonzero only for . The reference has and the carrier , so along the columns the four terms of the hologram spectrum sit at:
- : index ;
- : ;
- the sideband : ;
- the twin term : .
The table gives the relative error of the wave reconstructed on the sensor (), as measured by the test file.
| carrier | condition | relative error |
|---|---|---|
| 5 | : the sideband overlaps the autocorrelation term | |
| 6 | : they share one column | |
| 7 | separated | |
| 9 | separated | |
| 13 | separated, | |
| 14 | : sideband meets the twin |
Inside the window the result is exact to rounding, as the theorem says. One step outside it on either side, the error is large.
Correctness
The proof works on the periodic grid, with the object wave band-limited to the square . It shows three things.
- Where the four terms sit (theorem). The DFT of is at , that of in the square of half-width , that of in the square of half-width around , and that of around . The second statement holds because the DFT of a product is a convolution of the DFTs.
- Exact recovery (theorem). If for one axis the carrier satisfies and , the window around meets no other term. Then lines L1 to L4 give the DFT of exactly, and the output is , which is when the band of propagates.
- Noise (theorem). Every step is linear and the filter discards everything outside the window, so additive noise in the hologram changes the output by at most .
The proof also gives the in-line case: with , back propagation returns plus the twin, the conjugate wave focused at , plus the term. That is the twin image problem, and the off-axis carrier is one way to solve it.
Proof: Off-axis reconstruction is exact when the sidebands separatefull
The setting is that of the algorithm. Images are arrays on a periodic grid with spacing . For an array , is its unnormalized 2D DFT, and an index is read as its signed value with . Index arithmetic is modulo . For an integer and an index , let
the square of half-width around . A field on the sensor is band-limited to if is zero outside . The reference is the tilted plane wave with and an integer carrier , and the hologram is .
Lemma 1 (the four terms). , and for band-limited to :
- is zero outside ;
- is zero outside ;
- , which is zero outside ;
- , which is zero outside .
Proof. The expansion is with . Item 1: the DFT of a constant is zero except at index . Item 2: the DFT of a pixelwise product is the cyclic convolution of the DFTs divided by , and the DFT of at is ; so , and a nonzero term needs and , so . Item 3: multiplying by moves the DFT by . Item 4: the same with and .
Lemma 2 (separation). Suppose that for one axis ,
Then is disjoint from , and .
Proof. Take ; the other case is the mirror image. By (S), , so the integers in , in and in all lie in , where the signed value of an index is unique. The first interval ends at , so it is disjoint from the second. The third starts at , so it is disjoint from the first. Along axis the three other sets lie in , and lies in , which is disjoint from it. Two sets whose coordinates along one axis are disjoint are disjoint.
Theorem. Let be band-limited to and let (S) hold. Then lines L1 to L4 compute the array with , and the output of line L6 is , where is angular spectrum propagation by with evanescent waves dropped. If moreover for a field in the object plane that is band-limited to , and every frequency in propagates, then the output is .
Proof. Line L1 gives , the sum of the four DFTs of Lemma 1. Lines L2 to L4 set, for , , and otherwise. For , the index lies in , where by Lemma 2 only the third term of Lemma 1 is nonzero. So . For , because is band-limited. Line L5 multiplies by the transfer function of and line L6 inverts the DFT, which is by the definition of the angular spectrum method. For the last claim, keeps the propagating frequencies and deletes the rest, so it is the identity on fields whose spectrum lies in the propagating set.
Corollary 1 (noise). If the recorded hologram is with any real noise , the output changes by , where in the Euclidean norm of the samples.
Proof. Every line is linear in the hologram, so the change is the output for the input . In the DFT basis that output keeps the entries of in , moves them, divides by and multiplies by numbers of modulus at most . With the Parseval theorem, .
Only the fraction of the noise energy inside the window passes. For white noise this fraction is about , so the filter also removes most of the noise; this is a statement about averages, not a bound for every .
Corollary 2 (the in-line case and the twin). For the separation fails. If the whole spectrum of is propagated by , with , the result is
The second term, the twin image, has the same energy as on the propagating band, and it is the wave propagated by : applied to it gives when every frequency of propagates.
Proof. With , , so . Apply and use . The DFT of at is , and on propagating frequencies, because depends on only and has modulus there. So , the twin term is , and of it is . The energy statement follows from and the Parseval theorem.
So in an in-line hologram the twin is a defocused copy of the conjugate object, which lies on the reconstruction at full energy. The off-axis carrier moves it to a different place in Fourier space, where the window of line L3 removes it.
Complexity
In the real RAM model with the fast Fourier transform, lines L1 and L6 cost for an hologram with a power of two. Lines L2 to L5 cost , with one complex exponential per entry for the transfer function, which can be stored for repeated use. The method keeps two arrays of complex numbers. A refocusing series at many distances costs one FFT for the hologram and then per distance.
Properties
- One shot. One hologram gives the complex wave. This allows the imaging of moving or changing objects at the frame rate of the camera.
- Linear in the hologram. The output is a linear map of , and noise passes with a gain of at most .
- Resolution versus carrier. The passband must fit between the central terms and the Nyquist limit. Along the carrier axis, and give . So off-axis holography uses at most about a quarter of the frequency range of the camera along that axis for the object.
- Numerical refocus. The distance is a parameter of the computation, so one recording can be focused at any depth afterward.
- Quantitative phase. The output phase is the optical path difference modulo . Large phase ranges need phase unwrapping.
Variants and improvements
- Phase-shifting holography (Yamaguchi and Zhang 1997). Record several in-line holograms with the reference phase shifted by known steps, and solve for the complex wave pixel by pixel. It uses the full band of the camera, at the cost of several exposures of a static object.
- Fresnel transform reconstruction. Propagate with a single-FFT Fresnel transform instead of the angular spectrum method. The output pixel size is then , which suits long distances.
- Removal of the zero order. Subtract the mean of the hologram, or record the reference and object intensities separately and subtract them, which removes and . Then only the twin must be separated, and the condition on the carrier becomes .
- Phase compensation. A non-integer carrier, a spherical reference or the optics of a microscope add a phase to the result. Methods fit and remove it, for example by a reference hologram with no object, or by fitting a polynomial to an empty region.
- In-line reconstruction with phase retrieval. For in-line holograms, iterative phase retrieval with a support or a positivity constraint can remove the twin, as in the work of Latychevskaia and Fink.
When to use it
Use off-axis reconstruction for quantitative phase imaging of living cells, for metrology of surfaces and for the measurement of deformation, when one exposure must give the full wave. Use phase-shifting when the object is static and the full resolution of the camera is needed. For a coherent source with no stable reference, use the transport of intensity equation or iterative phase retrieval instead.
Pitfalls
- The carrier is too small or too large. The sideband then overlaps the term or the twin, as in the example. Plan the tilt of the reference so that the sideband sits between them. A real optical carrier is for the tilt ; on the camera it must stay below minus the object band.
- A non-integer carrier. If the tilt does not match a grid frequency, the moved spectrum is off by a fraction of a pixel, and the result carries a residual linear phase. Fit and remove it.
- A too wide window. A larger window passes more resolution but also more of the other terms and more noise. A smooth window, for example a raised cosine edge, reduces ringing at the cost of a little resolution.
- Wrap-around in refocusing. Long refocusing distances spread the light beyond the window of the camera. Pad before the propagation, as in the angular spectrum method.
- The sign of the carrier. The data cannot tell from . If the focus is found at the wrong side of the sensor, the twin was selected.
- Saturation and nonlinearity of the camera. The analysis assumes a linear camera. Clipped fringes add harmonics of the carrier, at and higher, which can fall into the window.
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
# Part of https://algorithm.tamnd.com/digital-holography-reconstruction/. The authors are listed in prov/JPPVSQ.jsonl.
"""Off-axis digital holography: sideband filtering, demodulation and refocusing.
Conventions:
- Images are n1 x n2 lists of rows, pixel (i, j) at y = i d and x = j d, on a
periodic grid. The DFT is unnormalized forward with exp(-2 pi i j k / n)
(imgkit). DFT index k stands for the signed index k if 2 k < n, else k - n.
- Time dependence exp(-i omega t): the plane wave with the spatial frequency
f travels toward +z with the factor exp(2 pi i z sqrt(1 / lambda^2 - |f|^2)).
- The reference wave on the sensor is R = r exp(2 pi i (cy i / n1 + cx j / n2))
with r > 0 and the integer carrier (cy, cx), a tilted plane wave.
- The hologram is h = |R + O|^2 = |R|^2 + |O|^2 + conj(R) O + R conj(O). The
term conj(R) O is the object wave times exp(-2 pi i c . x), so its spectrum
is the object spectrum moved to -c. That is the sideband we keep.
Cost: one forward and one inverse 2D DFT, O(n^2 log n) for n x n images with
n a power of two.
"""
import cmath
import math
from imgkit import dft2, idft2
def signed_index(k, n):
"""k if 2 k < n, else k - n."""
return k if 2 * k < n else k - n
def transfer(n1, n2, d, wavelength, z):
"""The angular spectrum transfer function of free space, evanescent waves set to 0."""
inv2 = 1.0 / (wavelength * wavelength)
h = [[0j] * n2 for _ in range(n1)]
for k in range(n1):
fy = signed_index(k, n1) / (n1 * d)
for l in range(n2):
fx = signed_index(l, n2) / (n2 * d)
w = inv2 - fx * fx - fy * fy
if w > 0.0:
h[k][l] = cmath.exp(2j * math.pi * z * math.sqrt(w))
return h
def propagate(u, d, wavelength, z):
"""Angular spectrum propagation of the sampled field u by the distance z."""
spec = dft2(u)
h = transfer(len(u), len(u[0]), d, wavelength, z)
return idft2([[s * t for s, t in zip(rs, rh)] for rs, rh in zip(spec, h)])
def reference_wave(n1, n2, r, carrier):
"""R = r exp(2 pi i (cy i / n1 + cx j / n2)) on the grid."""
cy, cx = carrier
return [[r * cmath.exp(2j * math.pi * (cy * i / n1 + cx * j / n2)) for j in range(n2)] for i in range(n1)]
def record_hologram(obj_at_sensor, r, carrier):
"""The intensity |R + O|^2 on the sensor (real numbers)."""
ref = reference_wave(len(obj_at_sensor), len(obj_at_sensor[0]), r, carrier)
return [[abs(a + b) ** 2 for a, b in zip(ra, ro)] for ra, ro in zip(ref, obj_at_sensor)]
def find_carrier(hologram, exclude):
"""The carrier, up to sign, from the largest spectral peak outside the central square.
The central square |ky|, |kx| <= exclude holds |R|^2 and |O|^2. This
assumes that the object spectrum peaks at zero frequency, as it does when
the object wave has a strong unscattered part; then the two sidebands
peak at -c and +c. The hologram is real, so its spectrum has
|H(k)| = |H(-k)| and the two peaks are equally high: the data alone
cannot tell c from -c. The peak with kx > 0, or ky > 0 when kx = 0, is
returned. Choosing the wrong sign reconstructs the twin wave.
"""
spec = dft2(hologram)
n1, n2 = len(spec), len(spec[0])
best, arg = -1.0, (0, 0)
for k in range(n1):
for l in range(n2):
ky, kx = signed_index(k, n1), signed_index(l, n2)
if abs(ky) <= exclude and abs(kx) <= exclude:
continue
if kx < 0 or (kx == 0 and ky < 0):
continue
v = abs(spec[k][l])
if v > best:
best, arg = v, (ky, kx)
return arg
def reconstruct(hologram, carrier, band, r, d, wavelength, z):
"""The object wave at distance z before the sensor (z = 0 gives the wave on the sensor).
carrier = (cy, cx) is the integer carrier of the reference, band = B the
half-width of the square passband in DFT indices, r the reference
amplitude. The sideband conj(R) O, centered at -c, is cut out, moved to
the center, divided by r and propagated by -z.
"""
n1, n2 = len(hologram), len(hologram[0])
cy, cx = carrier
spec = dft2(hologram) # @line L1
hz = transfer(n1, n2, d, wavelength, -z)
out = [[0j] * n2 for _ in range(n1)]
for k in range(n1): # @line L2
for l in range(n2):
if abs(signed_index(k, n1)) <= band and abs(signed_index(l, n2)) <= band: # @line L3
out[k][l] = spec[(k - cy) % n1][(l - cx) % n2] / r # @line L4
out[k][l] *= hz[k][l] # @line L5
return idft2(out) # @line L6
imgkit.py 322 lines
# 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
test_digital_holography_reconstruction.py 149 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/digital-holography-reconstruction/. The authors are listed in prov/JPPVSQ.jsonl.
import cmath
import math
import random
from digital_holography_reconstruction import (
find_carrier,
propagate,
reconstruct,
record_hologram,
reference_wave,
signed_index,
)
from imgkit import dft2, idft2, img_norm
N1, N2, D, LAM, Z = 8, 32, 1.0, 0.5, 6.0 # every grid frequency propagates
def band_limited_field(rng, n1, n2, band):
"""A random field whose DFT is zero outside |ky|, |kx| <= band."""
spec = [[0j] * n2 for _ in range(n1)]
for k in range(n1):
for l in range(n2):
if abs(signed_index(k, n1)) <= band and abs(signed_index(l, n2)) <= band:
spec[k][l] = complex(rng.gauss(0, 1), rng.gauss(0, 1)) * n1 * n2 / 10.0
return idft2(spec)
def max_diff(a, b):
return max(abs(x - y) for ra, rb in zip(a, b) for x, y in zip(ra, rb))
def sub(a, b):
return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
def support(img, tol=1e-9):
spec = dft2(img)
n1, n2 = len(img), len(img[0])
return {(signed_index(k, n1), signed_index(l, n2)) for k in range(n1) for l in range(n2) if abs(spec[k][l]) > tol}
def test_exact_recovery_when_the_sidebands_separate():
rng = random.Random(1)
band = 2
obj = band_limited_field(rng, N1, N2, band)
at_sensor = propagate(obj, D, LAM, Z)
for carrier in ((0, 7), (0, 9), (0, 13), (3, 9), (0, -9)):
for r in (1.0, 4.0):
h = record_hologram(at_sensor, r, carrier)
assert max_diff(reconstruct(h, carrier, band, r, D, LAM, 0.0), at_sensor) < 1e-10
assert max_diff(reconstruct(h, carrier, band, r, D, LAM, Z), obj) < 1e-10
def test_hologram_spectrum_has_the_four_terms_where_the_theorem_says():
rng = random.Random(2)
band, c = 2, (0, 9)
o = band_limited_field(rng, N1, N2, band)
ref = reference_wave(N1, N2, 1.5, c)
dc = [[abs(a) ** 2 for a in row] for row in ref]
auto = [[abs(a) ** 2 for a in row] for row in o]
side = [[a.conjugate() * b for a, b in zip(ra, rb)] for ra, rb in zip(ref, o)]
twin = [[a * b.conjugate() for a, b in zip(ra, rb)] for ra, rb in zip(ref, o)]
h = record_hologram(o, 1.5, c)
total = [[w + x + y + v for w, x, y, v in zip(*rows)] for rows in zip(dc, auto, side, twin)]
assert max_diff(h, total) < 1e-10
assert support(dc) == {(0, 0)}
assert all(abs(ky) <= 2 * band and abs(kx) <= 2 * band for ky, kx in support(auto))
assert all(abs(ky + c[0]) <= band and abs(kx + c[1]) <= band for ky, kx in support(side))
assert all(abs(ky - c[0]) <= band and abs(kx - c[1]) <= band for ky, kx in support(twin))
def test_overlap_breaks_the_reconstruction():
rng = random.Random(3)
band = 2
o = band_limited_field(rng, N1, N2, band)
good = reconstruct(record_hologram(o, 1.0, (0, 7)), (0, 7), band, 1.0, D, LAM, 0.0)
bad = reconstruct(record_hologram(o, 1.0, (0, 5)), (0, 5), band, 1.0, D, LAM, 0.0)
assert max_diff(good, o) < 1e-10
# c = 5 < 3 B = 6: the window also catches the edge of the |O|^2 term.
assert img_norm(sub(bad, o)) > 1e-3 * img_norm(o)
# c + B = 16 = n2 / 2: the sideband and the twin share the Nyquist column.
bad2 = reconstruct(record_hologram(o, 1.0, (0, 14)), (0, 14), band, 1.0, D, LAM, 0.0)
assert img_norm(sub(bad2, o)) > 1e-3 * img_norm(o)
def test_find_carrier_up_to_sign():
rng = random.Random(4)
# A weak scatterer: a strong unscattered wave plus a small band-limited part.
o = [[1.0 + 0.2 * v for v in row] for row in band_limited_field(rng, N1, N2, 2)]
for c in ((0, 9), (2, 10), (0, -11), (-1, -8)):
h = record_hologram(o, 3.0, c)
found = find_carrier(h, 4)
assert found in (c, (-c[0], -c[1]))
assert found[1] > 0
# The spectrum of a real hologram is Hermitian, so the two peaks are equal.
spec = dft2(h)
assert abs(abs(spec[c[0] % N1][c[1] % N2]) - abs(spec[-c[0] % N1][-c[1] % N2])) < 1e-9
def test_noise_error_is_at_most_noise_over_r():
rng = random.Random(5)
band, c, r = 2, (0, 9), 2.0
obj = band_limited_field(rng, N1, N2, band)
h = record_hologram(propagate(obj, D, LAM, Z), r, c)
noise = [[rng.gauss(0, 0.3) for _ in range(N2)] for _ in range(N1)]
noisy = [[a + b for a, b in zip(ra, rb)] for ra, rb in zip(h, noise)]
err = img_norm(sub(reconstruct(noisy, c, band, r, D, LAM, Z), obj))
assert 0 < err <= img_norm(noise) / r + 1e-12
def test_inline_hologram_gives_the_twin_image():
rng = random.Random(6)
band, r = 2, 3.0
obj = band_limited_field(rng, N1, N2, band)
at_sensor = propagate(obj, D, LAM, Z)
h = record_hologram(at_sensor, r, (0, 0))
# Back-propagate (h - r^2) / r over the full grid: object, twin and |O|^2 terms.
back = propagate([[(v - r * r) / r for v in row] for row in h], D, LAM, -Z)
twin = propagate([[v.conjugate() for v in row] for row in at_sensor], D, LAM, -Z)
auto = propagate([[abs(v) ** 2 / r for v in row] for row in at_sensor], D, LAM, -Z)
total = [[a + b + e for a, b, e in zip(ra, rb, re)] for ra, rb, re in zip(obj, twin, auto)]
assert max_diff(back, total) < 1e-10
# The twin is not small: it has the same energy as the object.
assert abs(img_norm(twin) - img_norm(obj)) < 1e-10 * img_norm(obj)
# The twin is the conjugate object wave focused at -z: propagating it by +2 z gives conj(obj).
refocused = propagate(twin, D, LAM, 2 * Z)
assert max_diff(refocused, [[v.conjugate() for v in row] for row in obj]) < 1e-10
def test_matches_direct_sum_for_one_entry():
rng = random.Random(7)
band, c, r = 2, (1, 9), 1.0
o = band_limited_field(rng, N1, N2, band)
h = record_hologram(o, r, c)
out = reconstruct(h, c, band, r, D, LAM, 0.0)
# Direct sum: demodulate conj(R) O by R / r^2 in real space and low-pass by the band.
demod = [[h[i][j] * cmath.exp(2j * math.pi * (c[0] * i / N1 + c[1] * j / N2)) / r for j in range(N2)] for i in range(N1)]
for i, j in ((0, 0), (3, 17), (7, 31)):
s = 0j
for ky in range(-band, band + 1):
for kx in range(-band, band + 1):
coef = sum(
demod[p][q] * cmath.exp(-2j * math.pi * (ky * p / N1 + kx * q / N2)) for p in range(N1) for q in range(N2)
)
s += coef * cmath.exp(2j * math.pi * (ky * i / N1 + kx * j / N2))
assert abs(s / (N1 * N2) - out[i][j]) < 1e-9
History
Gabor (1948) invented holography in the in-line form, where the twin image lies on top of the reconstruction. Leith and Upatnieks (1962) added the tilted reference, which separates the terms in angle. Takeda, Ina and Kobayashi (1982) gave the Fourier transform method for carrier fringe patterns, which isolates one sideband numerically. Schnars and Juptner (1994) recorded holograms on a CCD and reconstructed them by computer. Yamaguchi and Zhang (1997) introduced phase-shifting digital holography, and Cuche, Marquet and Depeursinge (2000) described the spatial filtering of the sideband for digital off-axis holography.
References
- Ulf Schnars and Werner Juptner, Direct recording of holograms by a CCD target and numerical reconstruction, Applied Optics 33(2), 1994, 179 to 181, the recording on a CCD and the numerical reconstruction of the object wave (general locator)
- Etienne Cuche, Pierre Marquet and Christian Depeursinge, Spatial filtering for zero-order and twin-image elimination in digital off-axis holography, Applied Optics 39(23), 2000, 4070, the Fourier filtering of one sideband of an off-axis hologram (general locator)
- Mitsuo Takeda, Hideki Ina and Seiji Kobayashi, Fourier-transform method of fringe-pattern analysis for computer-based topography and interferometry, Journal of the Optical Society of America 72(1), 1982, 156, the selection of one spectral sideband of a carrier fringe pattern and its shift to the origin (general locator)
- Emmett N. Leith and Juris Upatnieks, Reconstructed wavefronts and communication theory, Journal of the Optical Society of America 52(10), 1962, 1123 to 1130, the off-axis reference that separates the twin images (general locator)
- D. Gabor, A new microscopic principle, Nature 161(4098), 1948, 777 to 778, in-line holography and the twin image (general locator)
- Ichirou Yamaguchi and Tong Zhang, Phase-shifting digital holography, Optics Letters 22(16), 1997, 1268, the recovery of the complex wave from several holograms with shifted reference phase (general locator)
- Tatiana Latychevskaia and Hans-Werner Fink, Solution to the twin image problem in holography, Physical Review Letters 98(23), 2007, 233901, iterative reconstruction of in-line holograms that removes the twin image (general locator)
- Joseph W. Goodman, Introduction to Fourier Optics, third edition, Roberts and Company, 2005, the chapter on holography (general locator)
Where this leads
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 JPPVSQ Edit this page History Report an error Markdown