Exercise: Legendre moments and reconstruction

Goal

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

  • explain why reconstructing an image from monomial moments is an ill-conditioned linear system (the Gram matrix),
  • run Gram–Schmidt on 1, x, x^2 and recognise the Legendre polynomials,
  • approximate a function by Legendre polynomials and see that this is an orthogonal projection,
  • describe how a reconstruction from moments differs from a Fourier low-pass, and what pixels do to orthogonality,
  • (math) prove the best-approximation property and convert geometric to Legendre moments.

Background

Idea What it means
Inner product \langle g, h\rangle = \int_{-1}^1 g h\,dx (or \sum_i g_i h_i \Delta x on a grid)
Gram matrix G_{jk} = \langle b_j, b_k\rangle of the basis functions; diagonal iff the basis is orthogonal
Condition number \kappa(G) = largest/smallest eigenvalue; about \log_{10}\kappa digits are lost when solving G a = m
Legendre polynomials P_0 = 1, P_1 = x, P_2 = \tfrac12(3x^2 - 1), (n+1)P_{n+1} = (2n+1)xP_n - nP_{n-1}, \int P_n^2 = \frac{2}{2n+1}
Coefficients a_n = \frac{2n+1}{2}\langle f, P_n\rangle; in 2D a_{pq} = \frac{(2p+1)(2q+1)}{4}\iint P_p P_q I
Reconstruction \hat f_N = \sum_{n \le N} a_n P_n (2D: \sum_{p+q \le N} a_{pq} P_p P_q), the orthogonal projection

By hand

B1. Gram–Schmidt on 1, x, x^2 over [-1, 1]. (a) Compute \langle 1, 1\rangle, \langle x, 1\rangle, \langle x^2, 1\rangle, \langle x^2, x\rangle. (b) q_0 = 1. Compute q_1 = x - \frac{\langle x, q_0\rangle}{\langle q_0, q_0\rangle} q_0 and q_2 = x^2 - (\dots)q_0 - (\dots)q_1. (c) Scale q_2 so that its value at x = 1 is 1 and compare with P_2.

B2. The 3 \times 3 Gram matrix of 1, x, x^2 on [-1, 1]. (a) Write it down. Why is it not diagonal? (b) Compute the cosine of the angle between 1 and x^2. (c) Write the Gram matrix of P_0, P_1, P_2.

B3. Approximate f(x) = |x| on [-1, 1] by P_0, P_1, P_2. (a) Compute a_0 = \tfrac12\int |x|\,dx, a_1 and a_2 = \tfrac52\int |x| P_2\,dx. (Use symmetry: \int_{-1}^1 |x| g = 2\int_0^1 x g for even g.) (b) Write \hat f_2(x) as a polynomial in x, evaluate it at x = 0 and x = \pm 1, and sketch it with |x|. (c) The relative error \|\hat f - f\|/\|f\| is 0.5 with P_0 alone and 0.125 with P_0, P_1, P_2. Why does adding P_1 not help here?

B4. The cosine between x^8 and x^{10} on [-1, 1] is 0.994. What angle is that? What is the cosine between x^9 and x^{10}, and why?

B5. The condition number of the monomial Gram matrix on [-1, 1] is 9.4 \times 10^6 at degree 10 and 3.1 \times 10^{14} at degree 20; on [0, 1] it is 5.2 \times 10^{14} at degree 10. How many of the 16 significant digits of a double are left in each case? What does this say about the choice of coordinates?

B6. Count: how many Legendre moments are there up to order 20, and up to 40? What fraction of the pixels of a 128 \times 128 image are they?

B7. Four pixels on [-1, 1] have their centres at x = -\tfrac34, -\tfrac14, \tfrac14, \tfrac34 (\Delta x = \tfrac12). Compute the sampled inner product \sum_i P_0(x_i) P_2(x_i)\,\Delta x. Is it 0? What does that mean for Legendre moments of a 4 \times 4 image?

Math questions

B8. (math) Verify \int_{-1}^1 P_n^2\,dx = \frac{2}{2n+1} for n = 0, 1, 2, and use the recurrence to compute P_3 and P_4.

B9. (math) Express a_{20}, a_{11} and a_{02} in terms of the geometric moments m_{pq} (on [-1, 1]^2).

B10. (math) Let b_0, \dots, b_N be orthogonal and \hat f = \sum_k \frac{\langle f, b_k\rangle}{\langle b_k, b_k\rangle}b_k. Show that f - \hat f is orthogonal to every b_j, and that \|f - g\| \ge \|f - \hat f\| for every g in their span.

B11. (math) Show that the Gram matrix of 1, x, \dots, x^N on [0, 1] is the Hilbert matrix H_{jk} = \frac{1}{j+k+1}, and that on [-1, 1] the entries with j + k odd are 0. Why does the zero pattern not save the [-1, 1] matrix from being ill-conditioned?

B1. (a) \langle 1, 1\rangle = 2, \langle x, 1\rangle = 0, \langle x^2, 1\rangle = 2/3, \langle x^2, x\rangle = 0. (b) q_1 = x - 0 = x. q_2 = x^2 - \frac{2/3}{2}\cdot 1 - \frac{0}{2/3}x = x^2 - \frac13. (c) q_2(1) = \frac23, so q_2 / \frac23 = \frac32 x^2 - \frac12 = \frac12(3x^2 - 1) = P_2.

B2. (a) G = \begin{psmallmatrix} 2 & 0 & 2/3 \\ 0 & 2/3 & 0 \\ 2/3 & 0 & 2/5 \end{psmallmatrix}. Not diagonal because 1 and x^2 are both even and positive: \langle 1, x^2\rangle = 2/3 \ne 0. (b) \frac{2/3}{\sqrt{2 \cdot 2/5}} = 0.745 (an angle of 42°). (c) \operatorname{diag}(2, 2/3, 2/5).

B3. (a) a_0 = \tfrac12 \cdot 2\int_0^1 x\,dx = \tfrac12. a_1 = 0 (|x| is even, P_1 odd). a_2 = \tfrac52 \cdot 2\int_0^1 x \cdot \tfrac12(3x^2 - 1)\,dx = \tfrac52\left(\tfrac34 - \tfrac12\right) = \tfrac58. (b) \hat f_2 = \tfrac12 + \tfrac58 \cdot \tfrac12(3x^2 - 1) = \tfrac{3}{16} + \tfrac{15}{16}x^2. \hat f_2(0) = 0.1875, \hat f_2(\pm 1) = 1.125: a parabola that misses the corner at 0 (too high) and overshoots at the ends. (c) |x| is even, so its coefficient on the odd P_1 is 0: adding P_1 adds nothing. (The 400-sample demo gives the same 0.5 and 0.125.)

B4. \arccos 0.994 = 6.1°: nearly parallel. x^9 \cdot x^{10} = x^{19} is odd: the cosine is exactly 0. Monomials are orthogonal across parity, nearly parallel within it.

B5. \log_{10} 9.4 \times 10^6 \approx 7: about 9 digits left. \log_{10} 3.1 \times 10^{14} \approx 14.5: 1–2 digits left. On [0, 1] at degree 10 already about 1–2 left. Coordinates in [-1, 1] (centred) are much better than [0, 1], but even there monomials of high degree are unusable; an orthogonal basis needs no system at all.

B6. 231 and 861; 1.4 % and 5.3 % of 16384.

B7. P_2(\pm\tfrac34) = \tfrac12(3 \cdot \tfrac{9}{16} - 1) = \tfrac{11}{32}, P_2(\pm\tfrac14) = \tfrac12(\tfrac{3}{16} - 1) = -\tfrac{13}{32}. Sum: \tfrac12 \cdot 2\left(\tfrac{11}{32} - \tfrac{13}{32}\right) = -\tfrac{1}{16} = -0.0625 \ne 0. On 4 pixels the sampled P_0 and P_2 are not orthogonal: a Legendre moment computed by sampling mixes in a little of the other orders, and the reconstruction is not an exact projection. The fewer pixels and the higher the order, the worse.

B8. \int 1 = 2; \int x^2 = 2/3; \int \tfrac14(3x^2 - 1)^2 = \tfrac14(\tfrac{18}{5} - 4 + 2) = \tfrac25. Recurrence with n = 2: 3P_3 = 5xP_2 - 2P_1 = \tfrac52(3x^3 - x) - 2x, so P_3 = \tfrac12(5x^3 - 3x). With n = 3: 4P_4 = 7xP_3 - 3P_2, so P_4 = \tfrac18(35x^4 - 30x^2 + 3).

B9. a_{20} = \tfrac{5 \cdot 1}{4}\iint P_2(x) I = \tfrac54\left(\tfrac32 m_{20} - \tfrac12 m_{00}\right); a_{02} = \tfrac54\left(\tfrac32 m_{02} - \tfrac12 m_{00}\right); a_{11} = \tfrac{3 \cdot 3}{4} m_{11} = \tfrac94 m_{11}.

B10. \langle f - \hat f, b_j\rangle = \langle f, b_j\rangle - \sum_k \frac{\langle f, b_k\rangle}{\langle b_k, b_k\rangle}\langle b_k, b_j\rangle = \langle f, b_j\rangle - \langle f, b_j\rangle = 0. For g in the span, \hat f - g is in the span too, so \|f - g\|^2 = \|(f - \hat f) + (\hat f - g)\|^2 = \|f - \hat f\|^2 + \|\hat f - g\|^2 (cross term 0).

B11. \int_0^1 x^{j+k}dx = \frac{1}{j+k+1}; \int_{-1}^1 x^{j+k}dx = \frac{1 - (-1)^{j+k+1}}{j+k+1}, which is 0 for j + k odd. The zeros split the problem into an even and an odd block, but within each block (e.g. 1, x^2, x^4, \dots) the functions are again nearly parallel: each block is ill-conditioned on its own.

Explore: monomials and Legendre in 1D

The interval [-1, 1] with 400 samples. Top left: the basis functions up to degree N: monomials, Legendre polynomials, or the Gram–Schmidt view (the next monomial, its projection onto the functions already orthogonalised, and what is left). Top right: the Gram matrix of the shown functions as cosines (\langle b_j, b_k\rangle / \|b_j\|\|b_k\|, 1 = same direction) and its condition number \kappa. Bottom: a signal fitted with degree N by both bases (monomials through the Gram system, Legendre by projection), and the error against N, in 64-bit or 32-bit arithmetic.

P1. Preset monomials look alike (N = 10). Read the cosines of (x^8, x^{10}), (x^9, x^{10}) and (1, x^2) in the Gram matrix, and \kappa. Switch to Legendre: what are the cosines and \kappa now, and where does that \kappa come from?

P2. Preset Gram–Schmidt to P₃: press Gram–Schmidt step to go back to step 1 and step through. At step 3, what is subtracted from x^2? Compare with B1. Watch the Gram matrix change.

P3. Choose the signal |x| and Legendre, and set N = 0, 2 and 4. Compare the errors with B3.

P4. Preset fit a step (N = 12). Compare the two errors. Raise N to 30: from which N do the two errors differ? Switch to 32-bit: from which N now?

P5. Preset monomials break down (the bump, N = 24). Read both errors. Explain the error-vs-N plot for the monomials in 64-bit and in 32-bit.

P1. \cos(x^8, x^{10}) = 0.99, \cos(x^9, x^{10}) = 0.00, \cos(1, x^2) = 0.75 (the grid values agree with B2 and B4); \kappa = 9.5 \times 10^6. Legendre: the identity matrix (all off-diagonal cosines 0), \kappa = 21: the Gram matrix is diagonal with entries 2/(2n+1), from 2 down to 2/21, so \kappa is just the ratio of the longest to the shortest basis function. Normalised Legendre polynomials would have \kappa = 1.

P2. At step 3, the projection of x^2 onto 1 is the constant 1/3 (the projection onto x is 0); the remainder x^2 - 1/3, scaled to 1 at x = 1, is P_2. After step k the top-left k \times k block of the Gram matrix is diagonal; after step 4 the whole matrix is (\kappa = 7 for P_0 \dots P_3).

P3. 0.5000, 0.1250 and 0.0625: N = 2 matches B3 exactly.

P4. At N = 12 both 0.1749. In 64-bit they agree to four digits up to N \approx 20 (0.1352 against 0.1353) and differ from about N = 24 (0.1312 against 0.1238); at 30: 0.1358 against 0.1131. In 32-bit the monomial fit departs from N \approx 13 (0.1727 against 0.1533 at N = 16).

P5. Monomials 0.147, Legendre 0.017. In 64-bit the monomial error follows the Legendre one until N \approx 22, then jumps around: the Gram system (\kappa \approx 10^{14} and more) has lost all its digits, so the coefficients are dominated by rounding error. In 32-bit (7 digits) this happens already at N \approx 13. The Legendre fit needs no system and keeps improving.

Explore: rebuild an image from its moments

A 64 \times 64 image is rebuilt from its moments up to order N (slider) with four bases: monomials (least squares through the Gram system; coordinates in [-1, 1] or [0, 1]; computed only up to N = 32), Legendre, Zernike (on the inscribed disc, the next unit) and a Fourier low-pass that keeps the same number of coefficients (lowest frequencies first). Under each panel: the number of coefficients and the relative error against the input; the plot shows the error against N for all four. The display range is the input’s range \pm 30\,\%, so overshoots are visible. pixels chooses how the Legendre polynomials meet the pixel grid: sampled at the centres, averaged over each pixel, or the discrete orthogonal polynomials. noise adds Gaussian noise (the error is still measured against the clean input).

E1. Preset low orders = blurry ellipse (nucleus, N = 2). How many coefficients, and what do the reconstructions look like? Raise N to 20. Which basis has the smallest error at N = 2 and at N = 20?

E2. Preset monomials explode (letter E, N = 14, monomial coordinates [0, 1]). Compare the monomial and Legendre errors. Switch the monomial coordinates to [-1, 1]. Then look at the monomial curve in the error plot for both choices.

E3. Preset Legendre vs Fourier ringing (square, N = 16). Compare the errors and the ripples of Legendre and Fourier. Where are the ripples strongest?

E4. Choose micrograph and N = 40. Read the Legendre error with point samples, pixel-integrated and discrete (exact). Look at the Legendre curve in the plot for point samples. Explain.

E5. Preset noise in high orders (nucleus, \sigma = 0.3, N = 40). Find the N with the smallest error for Legendre, Zernike and Fourier. Why does the error rise again?

E1. 6 coefficients; every reconstruction is a blurry blob (Legendre and monomials a smooth hill, error 0.685; Zernike 0.571; Fourier 0.564). At N = 20 (231 coefficients): Legendre 0.226, Zernike 0.185, Fourier 0.175; the dent of the nucleus is visible. Fourier is slightly best at both; Legendre and monomials agree (same space, well-conditioned at this N).

E2. Monomials on [0, 1]: error 2.430, the image is a mess of large values; Legendre 0.366. With [-1, 1]: 0.365, the same as Legendre. In the plot the [0, 1] curve departs from about N = 12 (0.482 against 0.419) and jumps around; the [-1, 1] curve follows Legendre up to about N = 24 (0.316 against 0.312) and then departs (0.566 at N = 25, 0.361 against 0.290 at N = 28). Both bases span the same polynomials; only the rounding errors of the ill-conditioned Gram system differ.

E3. Legendre 0.254, Zernike 0.242, Fourier 0.227. Both overshoot next to the edges (Legendre values from −0.142 to 1.144, Fourier from −0.137 to 1.180). The Legendre ripples run parallel to the image border and get closer together towards it; the Fourier ripples are evenly spaced and continue across the border (the Fourier basis treats the image as periodic). The largest single error is at the square’s corners for both.

E4. Point samples 0.349, pixel-integrated 0.099, discrete 0.094. With point samples the error falls to about 0.160 at N = 16–20 and then rises (0.218 at 30): the sampled polynomials are less and less orthogonal on the grid as the order grows, and the micrograph is bright up to the image border, where the high-order polynomials are largest. The pixel-integrated and discrete bases keep improving.

E5. Legendre: smallest at N = 24 (0.268), 0.340 at N = 40; Zernike: N = 18 (0.257), 0.421 at 40; Fourier: N = 22 (0.238), 0.318 at 40. Low orders capture the shape; the noise is spread over all orders, so high orders add more noise than shape. As with a low-pass filter, stopping early is a denoiser.

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 moments/src/orthogonal_moments/exercise.rs. Pixel i of n has its centre at (2i + 1)/n - 1 in [-1, 1] (the function centre is given).

C1. legendre(n, x): P_n(x) by the three-term recurrence, keeping only the last two values:

prev = 1,  p = x                       # P0 and P1
for k = 1 .. n−1:
    next = ((2k + 1) · x · p − k · prev) / (k + 1)
    prev = p,  p = next

The checks are P_3 and P_4 of B8 at a few points, and P_n(\pm 1) = (\pm 1)^n.

C2. gram_schmidt(max_degree, xs): Gram–Schmidt on the monomials sampled at the points xs, with every vector scaled to length 1. The result is a set of polynomials that are exactly orthogonal on these points (the discrete orthogonal polynomials of the slide “Pixels: sampled polynomials are not orthogonal”):

for n = 0 .. max_degree:
    v = (x_i^n for every point i)
    for every vector b made so far:
        v = v − (v · b) · b
    t[n] = v / length(v)

The check is B1 on the three points -1, 0, 1 (the third vector is x^2 - \tfrac23, scaled), and orthonormality on 16 pixels up to degree 10.

C3. legendre_moments(img, order): the image on [-1, 1]^2, the polynomials sampled at the pixel centres, \Delta x = 2/\text{width}, \Delta y = 2/\text{height}:

for every p, q with p + q ≤ N:
    a[p][q] = (2p+1)(2q+1)/4 · sum over pixels of P_p(x) · P_q(y) · I(x, y) · Δx · Δy

The checks are B7 (a 4 \times 4 image of ones has a_{20} = -5/32, not 0) and B3 (|x| sampled 400 times: a_0 = 0.5, a_1 = 0, a_2 = 0.625).

C4. reconstruct(a, width, height): \hat I(x, y) = \sum_{p+q \le N} a_{pq} P_p(x) P_q(y) at every pixel centre. The check: a polynomial of degree 2 comes back from its moments up to order 2.

Then cargo run -p moments -- orthogonal-moments. It rebuilds a nucleus, a letter F and a piece of the micrograph (64 \times 64) from their moments up to order N = 2, 8, 20, 40, prints the relative errors, and draws them in out/orthogonal-moments/reconstructions.png (one row per image: the input, then the four orders).

C5. Describe the reconstructions as N grows. Where do the ripples appear, and how are they spaced?

C6. For the micrograph the error at N = 40 is larger than at N = 20. Why? The program also prints the error at N = 40 with the discrete polynomials of C2. Compare with E4.

C7. Count the cost: (N+1)(N+2)/2 moments, each a sum over all 64 \times 64 pixels. How many multiplications does C3 need at N = 40? Why is it worth computing every P_p at every column once, before the loops?

The model solution is moments/src/orthogonal_moments/solution.rs in the download.

C5. At N = 2 (6 numbers) every image is a blurry blob: errors 0.559 (nucleus), 0.774 (F), 0.241 (micrograph). At N = 8 the nucleus is a bright oval band and the F a smeared shape; at N = 20 both are clearly recognisable (0.216, 0.320), at N = 40 sharper still (0.176, 0.215). Next to every edge the reconstruction overshoots, and faint ripples run parallel to the image border, closer together near it: the zeros of P_n crowd towards \pm 1.

C6. The micrograph is bright up to the image border. With the polynomials sampled at the pixel centres, the high orders are no longer orthogonal on the 64 \times 64 grid, and the error lands where they are largest: a bright frame of stripes along the border. The error rises from 0.187 (N = 20) to 0.357 (N = 40). With the discrete orthogonal polynomials it is 0.140 at N = 40. The demo shows the same for its crop (0.349 sampled, 0.094 discrete).

C7. 861 moments × 4096 pixels ≈ 3.5 million multiply-and-add steps (two multiplications each). If P_p(x) and P_q(y) were computed by the recurrence inside the loop, each would cost up to 40 more steps: some 100 times more work. With the table, the polynomials cost only 41 \times 64 evaluations per direction.

Where this leads

Legendre moments live on a square, and a rotated image mixes them in a complicated way. The next unit moves to the disc and polar coordinates: Zernike polynomials are orthogonal there, and their magnitudes do not change at all when the image rotates.