Algorithm Search⌘K

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.

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
Properties
deterministicexactnot in placeoffline
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 OO on an n1×n2n_1 \times n_2 grid with spacing dd. The reference is the tilted plane wave R=r e2πi(c1i/n1+c2j/n2)R = r\, e^{2\pi i (c_1 i/n_1 + c_2 j/n_2)} with a known amplitude r>0r > 0 and an integer carrier cc, in DFT index units. The camera records the hologram

h=∣R+O∣2=r2+∣O∣2+R‾ O+R O‾.h = |R + O|^2 = r^2 + |O|^2 + \overline{R}\, O + R\, \overline{O}.

The task is to find OO, and then the wave O0O_0 in the object plane at distance zz before the sensor, with O=PzO0O = P_z O_0 for the propagation PzP_z of the angular spectrum method. Only the third term carries OO linearly. The fourth carries O‾\overline{O}, which gives the twin image. The DFT is unnormalized, and a DFT index kk stands for its signed value kˉ\bar k, in [−n/2,n/2)[-n/2, n/2).

The algorithm

BB is the half-width of the square passband in DFT index units, and H−zH_{-z} is the transfer function of free space for the distance −z-z, zero for evanescent waves.

  1. DH-RECONSTRUCT(h, c, B, r, d, λ, z)
  2. 1Ĥ <- DFT2(h)
  3. 2for each index k = (k1, k2), with S[k] <- 0 at the start do
  4. 3if |k̄1| <= B and |k̄2| <= B then
  5. 4S[k] <- Ĥ[k - c] / r ▷ cut the sideband at -c and move it to 0
  6. 5S[k] <- S[k] · H_-z(k) ▷ back-propagate to the object plane
  7. 6return IDFT2(S)

Line L4 does the demodulation and the filtering in one step: the window around −c-c is read and written to the window around 00. Dividing by rr removes the reference amplitude. With z=0z = 0 the output is the wave on the sensor. Lines L2 to L5 cost O(n2)O(n^2), 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 ∣h^∣|\hat h| outside a small central square: for an object with a strong unscattered wave, the sidebands peak at ±c\pm c. The hologram is real, so ∣h^(k)∣=∣h^(−k)∣|\hat h(k)| = |\hat h(-k)|, and the sign of cc cannot be found from the data. The wrong sign reconstructs the twin wave, which focuses at −z-z instead of zz.

Example

Take n1=8n_1 = 8 rows and n2=32n_2 = 32 columns, d=1 μd = 1\ \mum and λ=0.5 μ\lambda = 0.5\ \mum, so every grid frequency propagates. The object wave on the sensor is a random field whose DFT is nonzero only for ∣kˉ1∣,∣kˉ2∣≤B=2|\bar k_1|, |\bar k_2| \le B = 2. The reference has r=1r = 1 and the carrier c=(0,c2)c = (0, c_2), so along the columns the four terms of the hologram spectrum sit at:

  • r2r^2: index 00;
  • ∣O∣2|O|^2: ∣kˉ2∣≤2B=4|\bar k_2| \le 2B = 4;
  • the sideband R‾O\overline{R} O: −c2−2≤kˉ2≤−c2+2-c_2 - 2 \le \bar k_2 \le -c_2 + 2;
  • the twin term RO‾R\overline{O}: c2−2≤kˉ2≤c2+2c_2 - 2 \le \bar k_2 \le c_2 + 2.

The table gives the relative error ∥Orec−O∥/∥O∥\|O_{\text{rec}} - O\| / \|O\| of the wave reconstructed on the sensor (z=0z = 0), as measured by the test file.

carrier c2c_2 condition relative error
5 c2<3Bc_2 < 3B: the sideband overlaps the autocorrelation term 1.9×10−11.9 \times 10^{-1}
6 c2=3Bc_2 = 3B: they share one column 5.6×10−25.6 \times 10^{-2}
7 separated 1.2×10−151.2 \times 10^{-15}
9 separated 1.3×10−151.3 \times 10^{-15}
13 separated, c2+B=15<16c_2 + B = 15 < 16 2.1×10−152.1 \times 10^{-15}
14 c2+B=16=n2/2c_2 + B = 16 = n_2/2: sideband meets the twin 4.7×10−14.7 \times 10^{-1}

Inside the window 7≤c2≤137 \le c_2 \le 13 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 ∣kˉ1∣,∣kˉ2∣≤B|\bar k_1|, |\bar k_2| \le B. It shows three things.

  • Where the four terms sit (theorem). The DFT of r2r^2 is at 00, that of ∣O∣2|O|^2 in the square of half-width 2B2B, that of R‾O\overline{R}O in the square of half-width BB around −c-c, and that of RO‾R\overline{O} around +c+c. The second statement holds because the DFT of a product is a convolution of the DFTs.
  • Exact recovery (theorem). If for one axis aa the carrier satisfies 3B<∣ca∣3B < |c_a| and ∣ca∣+B<na/2|c_a| + B < n_a/2, the window around −c-c meets no other term. Then lines L1 to L4 give the DFT of OO exactly, and the output is P−zOP_{-z} O, which is O0O_0 when the band of O0O_0 propagates.
  • Noise (theorem). Every step is linear and the filter discards everything outside the window, so additive noise ee in the hologram changes the output by at most ∥e∥/r\|e\|/r.

The proof also gives the in-line case: with c=0c = 0, back propagation returns O0O_0 plus the twin, the conjugate wave focused at −z-z, plus the ∣O∣2|O|^2 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 n1×n2n_1 \times n_2 arrays on a periodic grid with spacing dd. For an array xx, x^=Fx\hat x = F x is its unnormalized 2D DFT, and an index k=(k1,k2)k = (k_1, k_2) is read as its signed value kˉ\bar k with −na/2≤kˉa<na/2-n_a/2 \le \bar k_a < n_a/2. Index arithmetic is modulo (n1,n2)(n_1, n_2). For an integer B≥0B \ge 0 and an index cc, let

QB(c)={k:∣k−c‾1∣≤B and ∣k−c‾2∣≤B},Q_B(c) = \{k : |\overline{k - c}_1| \le B \text{ and } |\overline{k - c}_2| \le B\},

the square of half-width BB around cc. A field OO on the sensor is band-limited to BB if O^\hat O is zero outside QB(0)Q_B(0). The reference is the tilted plane wave Rij=r e2πi(c1i/n1+c2j/n2)R_{ij} = r\, e^{2\pi i (c_1 i/n_1 + c_2 j/n_2)} with r>0r > 0 and an integer carrier cc, and the hologram is h=∣R+O∣2h = |R + O|^2.

Lemma 1 (the four terms). h=r2+∣O∣2+R‾O+RO‾h = r^2 + |O|^2 + \overline{R} O + R \overline{O}, and for OO band-limited to BB:

  1. r2^\widehat{r^2} is zero outside {0}\{0\};
  2. ∣O∣2^\widehat{|O|^2} is zero outside Q2B(0)Q_{2B}(0);
  3. R‾O^(k)=r O^(k+c)\widehat{\overline{R} O}(k) = r\, \hat O(k + c), which is zero outside QB(−c)Q_B(-c);
  4. RO‾^(k)=r O^(c−k)‾\widehat{R \overline{O}}(k) = r\, \overline{\hat O(c - k)}, which is zero outside QB(c)Q_B(c).

Proof. The expansion is ∣R+O∣2=(R+O)(R+O)‾|R + O|^2 = (R + O)\overline{(R + O)} with ∣R∣2=r2|R|^2 = r^2. Item 1: the DFT of a constant is zero except at index 00. Item 2: the DFT of a pixelwise product is the cyclic convolution of the DFTs divided by n1n2n_1 n_2, and the DFT of O‾\overline{O} at kk is O^(−k)‾\overline{\hat O(-k)}; so ∣O∣2^(k)=(n1n2)−1∑qO^(q) O^(q−k)‾\widehat{|O|^2}(k) = (n_1 n_2)^{-1} \sum_q \hat O(q)\, \overline{\hat O(q - k)}, and a nonzero term needs q∈QB(0)q \in Q_B(0) and q−k∈QB(0)q - k \in Q_B(0), so k∈Q2B(0)k \in Q_{2B}(0). Item 3: multiplying by e−2πi(c1i/n1+c2j/n2)e^{-2\pi i (c_1 i/n_1 + c_2 j/n_2)} moves the DFT by −c-c. Item 4: the same with +c+c and O‾\overline{O}. □\square

Lemma 2 (separation). Suppose that for one axis aa,

3B<∣ca∣and∣ca∣+B<na/2.(S)3B < |c_a| \quad \text{and} \quad |c_a| + B < n_a/2. \tag{S}

Then QB(−c)Q_B(-c) is disjoint from {0}\{0\}, Q2B(0)Q_{2B}(0) and QB(c)Q_B(c).

Proof. Take ca>0c_a > 0; the other case is the mirror image. By (S), 4B<na/24B < n_a/2, so the integers in [−ca−B,−ca+B][-c_a - B, -c_a + B], in [−2B,2B][-2B, 2B] and in [ca−B,ca+B][c_a - B, c_a + B] all lie in [−na/2,na/2)[-n_a/2, n_a/2), where the signed value of an index is unique. The first interval ends at −ca+B<−2B-c_a + B < -2B, so it is disjoint from the second. The third starts at ca−B>2B>−ca+Bc_a - B > 2B > -c_a + B, so it is disjoint from the first. Along axis aa the three other sets lie in [−2B,ca+B][-2B, c_a + B], and QB(−c)Q_B(-c) lies in [−ca−B,−ca+B][-c_a - B, -c_a + B], which is disjoint from it. Two sets whose coordinates along one axis are disjoint are disjoint. □\square

Theorem. Let OO be band-limited to BB and let (S) hold. Then lines L1 to L4 compute the array SS with S=O^S = \hat O, and the output of line L6 is P−zOP_{-z} O, where P−zP_{-z} is angular spectrum propagation by −z-z with evanescent waves dropped. If moreover O=PzO0O = P_z O_0 for a field O0O_0 in the object plane that is band-limited to BB, and every frequency in QB(0)Q_B(0) propagates, then the output is O0O_0.

Proof. Line L1 gives h^\hat h, the sum of the four DFTs of Lemma 1. Lines L2 to L4 set, for k∈QB(0)k \in Q_B(0), S(k)=h^(k−c)/rS(k) = \hat h(k - c)/r, and S(k)=0S(k) = 0 otherwise. For k∈QB(0)k \in Q_B(0), the index k−ck - c lies in QB(−c)Q_B(-c), where by Lemma 2 only the third term of Lemma 1 is nonzero. So S(k)=O^(k−c+c)=O^(k)S(k) = \hat O(k - c + c) = \hat O(k). For k∉QB(0)k \notin Q_B(0), S(k)=0=O^(k)S(k) = 0 = \hat O(k) because OO is band-limited. Line L5 multiplies by the transfer function of −z-z and line L6 inverts the DFT, which is P−zOP_{-z} O by the definition of the angular spectrum method. For the last claim, P−zPzP_{-z} P_z keeps the propagating frequencies and deletes the rest, so it is the identity on fields whose spectrum lies in the propagating set. □\square

Corollary 1 (noise). If the recorded hologram is h+eh + e with any real noise ee, the output changes by WeW e, where ∥We∥≤∥e∥/r\|W e\| \le \|e\|/r in the Euclidean norm of the samples.

Proof. Every line is linear in the hologram, so the change is the output for the input ee. In the DFT basis that output keeps the entries of e^\hat e in QB(−c)Q_B(-c), moves them, divides by rr and multiplies by numbers of modulus at most 11. With the Parseval theorem, ∥We∥2=(n1n2)−1∑∣entries∣2≤(n1n2)−1∑k∣e^(k)∣2/r2=∥e∥2/r2\|W e\|^2 = (n_1 n_2)^{-1} \sum |\text{entries}|^2 \le (n_1 n_2)^{-1} \sum_k |\hat e(k)|^2 / r^2 = \|e\|^2/r^2. □\square

Only the fraction of the noise energy inside the window passes. For white noise this fraction is about ∣QB(−c)∣/(n1n2)|Q_B(-c)|/(n_1 n_2), so the filter also removes most of the noise; this is a statement about averages, not a bound for every ee.

Corollary 2 (the in-line case and the twin). For c=0c = 0 the separation fails. If the whole spectrum of (h−r2)/r(h - r^2)/r is propagated by −z-z, with O=PzO0O = P_z O_0, the result is

P−zh−r2r=O0+P−zPzO0‾+1rP−z∣O∣2.P_{-z} \frac{h - r^2}{r} = O_0 + P_{-z} \overline{P_z O_0} + \frac{1}{r} P_{-z} |O|^2.

The second term, the twin image, has the same energy as O0O_0 on the propagating band, and it is the wave O0‾\overline{O_0} propagated by −2z-2z: P2zP_{2z} applied to it gives O0‾\overline{O_0} when every frequency of O0‾\overline{O_0} propagates.

Proof. With c=0c = 0, R=rR = r, so (h−r2)/r=O+O‾+∣O∣2/r(h - r^2)/r = O + \overline{O} + |O|^2/r. Apply P−zP_{-z} and use P−zO=P−zPzO0=O0P_{-z} O = P_{-z} P_z O_0 = O_0. The DFT of PzO0‾\overline{P_z O_0} at kk is Hz(−k) O^0(−k)‾\overline{H_z(-k)\, \hat O_0(-k)}, and Hz(−k)‾=H−z(k)\overline{H_z(-k)} = H_{-z}(k) on propagating frequencies, because HzH_z depends on ∣f∣|f| only and has modulus 11 there. So PzO0‾=P−zO0‾\overline{P_z O_0} = P_{-z} \overline{O_0}, the twin term is P−2zO0‾P_{-2z} \overline{O_0}, and P2zP_{2z} of it is O0‾\overline{O_0}. The energy statement follows from ∣H∣=1|H| = 1 and the Parseval theorem. □\square

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 O(n2log⁡n)O(n^2 \log n) for an n×nn \times n hologram with nn a power of two. Lines L2 to L5 cost O(n2)O(n^2), with one complex exponential per entry for the transfer function, which can be stored for repeated use. The method keeps two arrays of n2n^2 complex numbers. A refocusing series at many distances costs one FFT for the hologram and then O(n2log⁡n)O(n^2 \log n) 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 hh, and noise passes with a gain of at most 1/r1/r.
  • Resolution versus carrier. The passband must fit between the central terms and the Nyquist limit. Along the carrier axis, 3B<∣ca∣3B < |c_a| and ∣ca∣+B<na/2|c_a| + B < n_a/2 give B<na/8B < n_a/8. 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 zz 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 2π2\pi. 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 λz/(nd)\lambda z/(n d), 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 r2r^2 and ∣O∣2|O|^2. Then only the twin must be separated, and the condition on the carrier becomes B<∣ca∣B < |c_a|.
  • 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 ∣O∣2|O|^2 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 sin⁡θ/λ\sin\theta/\lambda for the tilt θ\theta; on the camera it must stay below 1/(2d)1/(2d) 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 cc from −c-c. 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 ±2c\pm 2c 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.

digital_holography_reconstruction.pyI0RawGitHub
# 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

  1. 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)
  2. 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)
  3. 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)
  4. 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)
  5. D. Gabor, A new microscopic principle, Nature 161(4098), 1948, 777 to 778, in-line holography and the twin image (general locator)
  6. 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)
  7. 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)
  8. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example