Exercise: phase correlation

Goal

By the end of this exercise you should be able to:

  • compute a short phase correlation by hand and explain why it is a spike,
  • show why gain and offset do not matter, and predict the effect of uneven illumination,
  • predict how noise affects phase correlation and choose a remedy (low-pass weight, exponent p),
  • explain the taper and read the peak height and peak ratio as a confidence.

Do the pen-and-paper part first, then the demo.

Background

Idea What it means
Cross-power spectrum A_k\overline{B_k}: phase difference and strength of wave k in both images
Phase correlation R_k = A_k\overline{B_k}/|A_k\overline{B_k}|, then the inverse FFT; a pure circular shift gives a spike of height 1
Exponent p divide by |A_k\overline{B_k}|^p: p = 0 is cross-correlation, p = 1 phase correlation
Low-pass weight multiply R_k by a smooth weight that fades out the highest frequencies
Hann taper w(n) = \tfrac12\big(1 - \cos\frac{2\pi n}{N-1}\big): 0 at both ends, 1 in the middle; in 2D w(x)w(y)
Peak height about the fraction of content shared by the two images
Peak ratio highest peak / second-highest peak; near 1: ambiguous

By hand

B1. A = (0, 1, 2, 0), B = (1, 2, 0, 0), A_k\overline{B_k} = (9, -5i, -1, 5i) (the previous unit). (a) Normalise every entry to size 1. (b) Take the inverse DFT, r(t) = \tfrac14\sum_k R_k\,i^{kt}. (c) Compare with the cross-correlation (2, 5, 2, 0).

B2. Same A, but B' = 2B + 1 = (3, 5, 1, 1). (a) Compute B'_k and compare with B_k = (3, 1 - 2i, -1, 1 + 2i). (b) Show that the normalised cross-power is the same as in B1. (c) What does the cross-correlation of A and B' look like (no means subtracted)?

B3. Two images share only one strong vertical edge (a long straight boundary, dark on the left, bright on the right); the rest is noise. Predict the shape of the phase-correlation surface. What can you measure, and what not?

B4. Two 128 \times 128 crops of one image, B’s frame (21, 13) pixels right and down of A’s, no noise. (a) What fraction of A’s pixels have a partner in B? Predict the phase-correlation peak height. (b) The same shift with 64 \times 64 crops? (c) Why does a Hann taper raise the peak a little in (a)?

B5. The Hann taper. (a) Write down w(n) for N = 5 and N = 8. (b) A 128 \times 128 tile overlaps its neighbour only in its last 24 columns. What is the average taper weight in those columns? What does that mean for registering mosaic tiles with a taper?

B6. A lattice of blobs 18 pixels apart is shifted by (21, 13). Which shifts give a high phase-correlation peak? What is the peak ratio likely to be?

B1. (a) Sizes (9, 5, 1, 5): R = (1, -i, -1, i). (b) r(0) = \tfrac14(1 - i - 1 + i) = 0; r(1) = \tfrac14(1 + (-i)(i) + (-1)(-1) + (i)(-i)) = \tfrac14(1 + 1 + 1 + 1) = 1; r(2) = \tfrac14(1 + i - 1 - i) = 0; r(3) = \tfrac14(1 - 1 + 1 - 1) = 0. A delta at t = 1. (c) The cross-correlation (2, 5, 2, 0) has its peak at 1 too, but with neighbours of 40 % of the peak; phase correlation leaves only the spike.

B2. (a) B'_k = (10, 2 - 4i, -2, 2 + 4i): for k \ne 0 exactly 2B_k; only B'_0 is not doubled (10 = 2\cdot3 + 4, the offset adds 4 \cdot 1 to the constant term). (b) For k \ne 0, A_k\overline{B'_k} = 2A_k\overline{B_k}, which has the same phase; for k = 0, A_0\overline{B'_0} = 30, normalised to 1 as before (9 → 1). So R and the delta are unchanged. (c) c'(t) = \sum_x A(x+t)(2B(x) + 1) = 2c(t) + \sum A = (4 + 3, 10 + 3, 4 + 3, 0 + 3) = (7, 13, 7, 3): same peak, twice as high, on a raised floor.

B3. A ridge: a line of high values along the edge direction. Shifting B along the edge (vertically) does not change how the edges line up, so every t_y scores the same for the right t_x. The horizontal shift is measured; the vertical shift is not determined at all (the “aperture problem”). In practice the noise picks a random point on the ridge.

B4. (a) (128 - 21)(128 - 13)/128^2 = 107 \cdot 115/16384 = 0.75: a peak of about 0.75, less in practice because the parts without a partner add noise; the demo gives 0.62. (b) (64 - 21)(64 - 13)/64^2 = 43 \cdot 51/4096 = 0.54; the demo gives 0.32, and the floor is relatively higher. (c) The taper weights the middle of each crop most; with a moderate shift, the middle of A is inside the overlap, so the shared fraction as weighted is higher (the demo: 0.67 instead of 0.62).

B5. (a) N = 5: (0, 0.5, 1, 0.5, 0). N = 8: (0, 0.19, 0.61, 0.95, 0.95, 0.61, 0.19, 0). (b) The average of w(n) over the last 24 of 128 samples is 0.10 (at most 0.29), against 0.5 over the whole tile: the overlap, the only part that the two tiles share, is almost switched off. Tapering is fine for crops that overlap mostly (drift, channels), but for mosaic tiles with small overlaps it removes the information: stitching registers the tiles without a taper and resolves the consequences (the four candidates) separately.

B6. Every shift that moves the lattice onto itself: (21 + 18m, 13 + 18n) for integers m, n, e.g. (3, -5), (3, 13), (-15, -5), (21, 13). All of these give about equally high peaks; which one wins depends on the crop borders and the noise. Peak ratio close to 1: ambiguous.

Math questions

B7. (math) (Sub-pixel shifts.) In 1D, let the normalised cross-power be an exact phase ramp for a non-integer shift t_0: R_k = e^{-2\pi i k t_0/N} for k = -\frac{N-1}{2}, \ldots, \frac{N-1}{2} (N odd). Show that r(t) = \frac1N\sum_k R_k e^{2\pi i kt/N} = \frac{\sin\big(\pi(t - t_0)\big)}{N\sin\big(\pi(t - t_0)/N\big)}, the Dirichlet kernel (“periodic sinc”) centred at t_0. What are the two largest samples for t_0 = 0.5 and large N?

B8. (math) (a) Show that the exponent p = 0 gives the cross-correlation. (b) Show that phase correlation of f and g equals the cross-correlation of the whitened images \tilde f, \tilde g with \tilde F_k = F_k/|F_k|, \tilde G_k = G_k/|G_k|. Why is whitening an edge-enhancing filter for typical images, whose |F_k| falls off with |k|?

B9. (math) Let g(x) = f(x + t_0) + \eta(x) with noise spectrum H_k. Write G_k = e^{2\pi i kt_0/N}(F_k + H'_k) with |H'_k| = |H_k|. Show that the phase error of R_k satisfies |\sin\delta_k| \le |H_k|/|F_k| when |H_k| < |F_k|. Where in the spectrum is the error large for a typical image with white noise?

B7. r(t) = \frac1N\sum_{k=-m}^{m}e^{2\pi i k(t - t_0)/N} with m = (N-1)/2, a geometric sum with ratio q = e^{2\pi i(t - t_0)/N}: \sum_{k=-m}^{m}q^k = \frac{q^{m+1/2} - q^{-m-1/2}}{q^{1/2} - q^{-1/2}} = \frac{\sin(\pi(t - t_0))}{\sin(\pi(t - t_0)/N)}, since (m + \tfrac12)\cdot\frac{2\pi(t - t_0)}{N} = \pi(t - t_0). Dividing by N gives the formula; at t = t_0 it is 1 (limit). For large N, N\sin(\pi u/N) \approx \pi u and r(t) \approx \operatorname{sinc}(t - t_0) = \sin(\pi(t-t_0))/(\pi(t - t_0)). For t_0 = 0.5 the samples at t = 0 and t = 1 are equal, \approx 2/\pi = 0.64: the spike is split between two pixels. Fitting this shape locates t_0 (the stitching unit).

B8. (a) |A_k\overline{B_k}|^0 = 1: nothing is divided, the inverse FFT of A_k\overline{B_k} is the cross-correlation. (b) \tilde F_k\overline{\tilde G_k} = \frac{F_k\overline{G_k}}{|F_k||G_k|} = \frac{F_k\overline{G_k}}{|F_k\overline{G_k}|}, so the cross-correlation of the whitened images (the correlation theorem) is the phase correlation. Whitening divides each wave by its size; when |F_k| falls off with |k|, the high frequencies are amplified relative to the low ones, like a sharpening filter: what remains are edges, lines and texture.

B9. R_k \propto (F_k + H'_k)\overline{F_k}\,e^{-2\pi i kt_0/N}, whose phase differs from the ideal -2\pi kt_0/N by \delta_k = \arg\big(1 + H'_k/F_k\big). The point 1 + z with |z| = |H_k|/|F_k| < 1 lies in a disc of radius |z| around 1, so its angle satisfies |\sin\delta_k| \le |z|. White noise has about the same |H_k| at every frequency, while |F_k| of a typical image falls off with |k|: the error is small at low frequencies and large (random phase) at high frequencies, exactly where a low-pass weight helps.

Explore

Left: the micrograph with frame A (blue) and frame B (red); drag frame B, or set the shift with the sliders. Middle: the two crops (B with its degradations) and a small panel with the spectrum of A or the phase of A_k\overline{B_k} as a colour. Right: the correlation surface with shift (0, 0) in the centre; green ring: the true shift, cyan cross: the highest peak, white circles: the next ones. p blends from cross-correlation (p = 0) to phase correlation (p = 1). uneven light brightens the whole field from one corner to the other (both crops); ramp on B only crop B. brute force computes NCC for every shift directly and times it.

E1. Preset same image, shifted: delta: B is A rolled around by (21, 13). Read the peak height and the peak ratio. Show the cross-power phase panel: what pattern do you see, and how does it change if you change the shift?

E2. Preset CC: broad peak, then phase: sharp peak. Compare the peak heights, the next-highest peaks and the peak ratios. Which shift is second best for CC?

E3. Preset illumination ramp on B (CC, a ramp of 500 grey levels across B). Where is CC’s peak? Switch the method to phase, then to NCC. Which finds the shift? Then set the ramp to 0, gain 0.5 and offset 80 with phase correlation: does anything change?

E4. Preset noise: phase peak drowns (σ = 120 on both crops). Where is the highest peak, and how high is the surface at the true shift? Then preset noise + low-pass weight. Also try p = 0.5 without low-pass, and CC.

E5. Preset no taper: false (0, 0) peak (CC, uneven light 600, no taper). Where is the peak? Look at the spectrum panel, then tick Hann taper. Then untick the taper again and choose phase correlation: where are the false peaks now?

E6. Preset periodic texture. Where is the highest peak, and what is the value at the true shift? Explain with B6.

E7. Preset phase: sharp peak. Switch the crop size to 64. How do the peak height and the ratio change? Compare with B4.

E8. Preset overlap NCC, then press brute force. Compare the result, the number of multiply-adds and the time with the FFT route.

E1. Height 1.00, peak ratio ∞ (everything else is zero up to rounding). The phase of A_k\overline{B_k} is a set of parallel stripes running through the whole spectrum: a phase ramp -2\pi(k_xt_x/128 + k_yt_y/128), wrapping around every 2\pi. Their direction and spacing are set by the shift: a larger shift gives more, narrower stripes.

E2. CC: peak at (21, 13), 4.03\cdot10^6; the second best (20, 10) still has 2.81\cdot10^6 (70 %), ratio 1.44. Phase: peak 0.67, next peaks 0.03 (at (-23, -6) and (-33, 16)), ratio 23.3.

E3. CC’s peak is at (54, 1): wrong. Phase correlation finds (21, 13) with the same height 0.67 and ratio 23.0. NCC (on the overlap) fails too, at (62, -57): NCC removes a constant offset and gain, not a ramp. With gain 0.5 and offset 80 the phase-correlation surface is exactly the same as without (0.671, ratio 23.26).

E4. The highest peak is at (-6, 7) (0.043, ratio 1.03), the true shift only 0.033: the spike has drowned. With the low-pass weight (sd 0.08 cycles per pixel) the peak is back at (21, 13), ratio 1.54. p = 0.5 gives (21, 14), CC also (21, 14): one pixel off, still close. The low-pass weight keeps the reliable low frequencies with equal votes and removes the noisy ones.

E5. The peak is at (0, 0) (the next ones on the line t_y = 0): the jumps at the crop borders do not move with the shift. The spectrum shows a bright horizontal and vertical cross. With the taper the cross disappears and CC finds (21, 13) (ratio 1.31). Phase correlation without taper finds (21, 13) (0.62), but the next peaks are at (15, 0) and (12, 0): still the axis line, only weaker.

E6. The highest peak is at (3, -5) (0.15), one lattice period from the truth in both directions; (3, 13) (0.10) and (-15, -5) (0.09) follow, and the true shift (21, 13) scores only 0.03. Peak ratio 1.58: not convincing. Every shift by a whole number of periods matches the lattice; only the crop borders make one of them a little better.

E7. At 64 \times 64 the peak drops from 0.67 to 0.32 and the ratio from 23 to 5.2: the shared fraction drops from 75 % to 54 % (B4), and there are fewer frequencies to vote, so the floor is relatively higher.

E8. NCC (through FFTs) finds (21, 13) with NCC 1.000; its second peak (20, 10) has 0.69. Brute force finds the same shift with 268 million multiply-adds and takes around a second or two in the browser (1.6 s in a test run), against tens of milliseconds for the FFT route; the readout shows the times on your machine.

Code

Write the algorithms of this unit yourself, in Rust. Setup, and how to run and check your code: coding exercises: getting started. Your code goes in fftreg/src/phasecorr/exercise.rs.

C1. phase_correlation_1d(a, b): as the cross-correlation of the last unit, but every product is divided by its size first (\varepsilon = EPS, a tiny number). The checks are your answers to B1 and B2.

C2. hann(n): the Hann taper. The check is B5(a).

C3. phase_correlation(a, b, settings): the 2D version, with the exponent p, an optional taper and an optional low-pass weight.

A' = (A − mean of A) · taper,   B' = (B − mean of B) · taper      # taper = 1 if switched off
FA = FFT(A'),  FB = FFT(B')
for every frequency k = (kx, ky):
    P = FA(k) · conj(FB(k))
    R(k) = P / (|P|^p + ε)
    if low-pass: R(k) = R(k) · exp(−f² / (2 sd²))       # f = frequency in cycles per pixel
r = real part of the inverse FFT of R

The checks: a circular shift gives a spike of height 1 and zeros elsewhere; a gain and an offset on B change nothing; p = 0 is the cross-correlation.

C4. peak_and_ratio(r): the highest peak as a signed shift, its height, and its ratio to the second-highest local maximum (larger than its 8 neighbours, wrapping around), not just the second-highest value, which usually sits right next to the peak.

Then cargo run -p fftreg -- phasecorr. It registers two 128 \times 128 crops of the micrograph, B 21 px right and 13 px down of A, under several conditions, prints the peak, ratio and height, and saves each surface in out/phasecorr/ (shift 0 in the middle).

C5. Compare cc with phase, and cc-ramp with phase-ramp (a brightness ramp of 500 grey levels across B): peak, ratio, height. Compare the height with your prediction in B4(a), with and without the taper (phase-no-taper).

C6. With strong noise on both crops (SD 120 grey levels): which settings find the shift? Look at phase-noise.png and phase-noise-lowpass.png.

C7. cc-uneven-no-taper: the whole field is unevenly lit and there is no taper. Where is the peak, and why? Then phase-lattice: a lattice of blobs 18 px apart. Explain its peak and ratio with B6.

The model solution is fftreg/src/phasecorr/solution.rs in the download.

C5. Both find (21, 13). Cross-correlation: ratio 1.90, a broad peak; phase correlation: ratio 20.8, a single sharp spike of height 0.68 on a flat floor. With the ramp the cross-correlation still peaks at (21, 13), but its ratio drops to 1.04: another shift scores almost as high, and a stronger ramp would win. Phase correlation is unchanged (0.679, ratio 21.0). The height: B4(a) predicts 0.75 (the shared fraction); without the taper it is 0.63, with the taper 0.68, which weights the middle of the crops, where they share content.

C6. Plain phase correlation fails: its highest peak is at (-1, -7) with height 0.041 and ratio 1.01, while the truth scores only 0.028; the surface is noise. Cross-correlation (p = 0) and p = 0.5 find (21, 13), but with ratios of only 1.12 and 1.06. The low-pass weight (sd 0.08 cycles per pixel) gives a smoother, blotchy surface whose brightest blob sits at the truth, ratio 1.46, but its top lands one pixel off, at (21, 12). The noisy high frequencies get a full vote in plain phase correlation; the remedies weight them down, at the price of a broader peak.

C7. The peak is at (0, 0), ratio 1.01, and cc-uneven-no-taper.png shows a bright horizontal band through the middle: the shifts with t_y = 0 all score high. Without a taper the crops jump in brightness where the right border meets the left one (and the bottom the top); these jumps are at the same place in A and B and do not move with the shift, so they vote for shift 0. With the taper (cc-uneven-taper) the peak is back at (21, 13), ratio 1.30. The lattice: the peak is at (3, -5), one lattice period (18 px) away from the truth in each direction, with ratio 1.09. Every shift by a multiple of 18 moves the lattice onto itself, so many peaks are almost equally high: a ratio near 1 says “do not trust this”.

Where this leads

The spike sits on whole pixels, and the circular FFT only knows the shift up to the size of the image. The next unit turns a peak into a usable shift (the four candidates, sub-pixel estimation), combines many pairwise shifts into a consistent mosaic, and corrects drift.