Exercise: the 2D wavelet transform
Before this unit: Multiresolution, filter banks and Daubechies wavelets (previous unit); Day 1: Images, filters and frequencies.
See also: Day 3: Bit depth and noise.
Goal
By the end of this exercise you should be able to:
- compute one level of the 2D Haar transform of small blocks by hand and predict which subband an edge lights up,
- count the coefficients of a subband pyramid,
- turn dropped coefficient energy into an MSE and a PSNR, and compare bases at an equal number of coefficients,
- explain why the decimated transform is shift-variant, and why a coefficient count is not a file size.
Do the pen-and-paper part first, then the demo. Questions marked (math) are for those who want the derivations; the concept questions do not depend on them.
Background
| Idea | What it means |
|---|---|
| Separable 2D DWT | one level of the 1D filter bank on every row, then on every column |
| Subbands | LL approximation; V high-pass along x (vertical edges); H high-pass along y (horizontal edges); D high-pass along both |
| 2 \times 2 Haar block \begin{pmatrix} a & b\\ c & d\end{pmatrix} | LL = \tfrac12(a+b+c+d), V = \tfrac12(a-b+c-d), H = \tfrac12(a+b-c-d), D = \tfrac12(a-b-c+d) |
| Pyramid (Mallat layout) | repeat on LL; L levels on N \times N give N^2 coefficients |
| Orthonormal transform | \mathrm{MSE} = \frac{1}{N^2}\sum_{\text{dropped}} c^2 |
| PSNR (8 bits) | 10\log_{10}(255^2/\mathrm{MSE}) (camera noise unit) |
By hand
B1. Compute the four Haar subband values of each 2 \times 2 block: \text{(a)}\ \begin{pmatrix} 5 & 5\\ 5 & 5\end{pmatrix} \qquad \text{(b)}\ \begin{pmatrix} 2 & 8\\ 2 & 8\end{pmatrix} \qquad \text{(c)}\ \begin{pmatrix} 2 & 2\\ 8 & 8\end{pmatrix} \qquad \text{(d)}\ \begin{pmatrix} 8 & 2\\ 2 & 8\end{pmatrix} Which band responds to which kind of edge?
B2. A 4 \times 4 image with a horizontal edge: the first three rows are all 1, the last row is all 9. (a) Compute one level of the 2D Haar transform (four 2 \times 2 subbands). Which bands are nonzero? (b) Now the edge lies one row higher: the first two rows are 1, the last two are 9. Which bands are nonzero after one level? After two levels? (c) What does this say about how the transform reacts to moving an edge by one pixel?
B3. A 256 \times 256 image, 4 levels. (a) How large is each subband at each level, and how many coefficients are there in total? (b) What fraction of the coefficients is in the final LL?
B4. Keeping a fraction of all coefficients of the micrograph (4 levels) gives these PSNR values (dB):
| kept | Haar | db4 | CDF 9/7 | Fourier | 8\times8 DCT |
|---|---|---|---|---|---|
| 1 % | 18.2 | 18.6 | 18.8 | 18.4 | 10.5 |
| 5 % | 20.9 | 21.5 | 21.8 | 21.0 | 21.2 |
| 20 % | 25.7 | 26.4 | 26.7 | 25.0 | 26.2 |
- Which basis would you use, and how much better is it than Fourier at 5 %, in dB and as a ratio of MSEs?
- Why does the DCT collapse at 1 %? (Hint: 655 coefficients for 1024 blocks.)
- For the synthetic disc at 2 %, the values are Haar 47.6, db4 40.5, DCT 34.9, Fourier 29.8. Why is the ranking different from the micrograph?
B5. In an orthonormal transform of a 256 \times 256 image, the dropped coefficients have a total squared value of 10^6. What are the MSE and the PSNR? What happens to the PSNR if twice as much energy is dropped?
B6. You keep 5 % of the coefficients of a 256 \times 256 8-bit image. Estimate the number of bits if each kept coefficient is stored as an 8-bit value plus its position. What compression ratio is that? Name two things a real codec does to do better.
B1. (a) LL = 10, V = H = D = 0. (b) LL = 10, V = \tfrac12(2 - 8 + 2 - 8) = -6, H = D = 0: a vertical edge (change along x) lights V. (c) LL = 10, H = \tfrac12(2 + 2 - 8 - 8) = -6, V = D = 0: a horizontal edge lights H. (d) LL = 10, D = \tfrac12(8 - 2 - 2 + 8) = 6, V = H = 0: a checkerboard (diagonal) pattern lights D. The sign tells the direction (here: brighter on the right gives a negative V, because V is left minus right).
B2. (a) Blocks (rows 1–2) are flat 1s: LL = 2, details 0. Blocks in rows 3–4 are \begin{pmatrix}1 & 1\\ 9 & 9\end{pmatrix}: LL = 10, H = \tfrac12(1 + 1 - 9 - 9) = -8, V = D = 0. Subbands: LL = \begin{pmatrix} 2 & 2\\ 10 & 10\end{pmatrix}, H = \begin{pmatrix} 0 & 0\\ -8 & -8\end{pmatrix}, V = D = 0. Only H has details. (b) Every 2 \times 2 block is flat (rows 1–2 all 1, rows 3–4 all 9): all level-1 details are 0, LL = \begin{pmatrix} 2 & 2\\ 18 & 18\end{pmatrix}. At level 2, LL is one block \begin{pmatrix}2 & 2\\ 18 & 18\end{pmatrix}: LL = 20, H = \tfrac12(2 + 2 - 18 - 18) = -16. (c) The same edge, moved by one row, appears at a different level with different values: the transform is not shift-invariant. Where an edge falls relative to the even–odd grid decides which coefficients see it.
B3. (a) Level 1: three bands of 128 \times 128 = 16\,384; level 2: three of 64 \times 64 = 4096; level 3: three of 1024; level 4: three of 256; final LL 16 \times 16 = 256. Total 3(16\,384 + 4096 + 1024 + 256) + 256 = 65\,536 = 256^2. (b) 256/65\,536 = 1/256 = 0.39\,\% (= 4^{-4}).
B4. (a) CDF 9/7 (or db4, 0.3 dB behind): 21.8 against 21.0 dB for Fourier, 0.8 dB, i.e. an MSE ratio of 10^{0.08} = 1.20: 20 % less squared error. The differences are small on this textured image; what you see differs more (blocks, ringing). (b) 655 coefficients for 1024 blocks: at least 369 blocks keep nothing, not even their average (DC), and become 0 (black). Real codecs always code every DC coefficient. (c) The disc is piecewise constant: flat regions and one smooth edge. Wavelets (Haar best: no smooth part needs vanishing moments) describe it with few coefficients along the edge; Fourier needs all frequencies for the edge. The micrograph is full of fine texture that no basis compresses well, which pulls all bases together.
B5. \mathrm{MSE} = 10^6/65\,536 = 15.26, \mathrm{PSNR} = 10\log_{10}(65\,025/15.26) = 36.3 dB. Twice the dropped energy doubles the MSE: 36.3 - 10\log_{10}2 = 33.3 dB (3 dB less).
B6. 0.05 \cdot 65\,536 = 3277 coefficients; each 8 bits of value plus \log_2 65\,536 = 16 bits of position: 3277 \cdot 24 = 78\,648 bits, against 65\,536 \cdot 8 = 524\,288 for the raw image: ratio 6.7. Real codecs quantise the values coarsely (fewer bits per value), code the positions jointly (large coefficients cluster along edges and across levels), and entropy-code the result. (Compression day.)
Math questions
B7. (math) Derive the four 2 \times 2 Haar formulas by applying the 1D step (a, b) \mapsto ((a+b)/\sqrt2, (a-b)/\sqrt2) first to both rows, then to both columns.
B8. (math) Let W be an orthogonal N \times N matrix (one 1D level or a full 1D transform). Show that X \mapsto WXW^\top preserves \sum_{ij} X_{ij}^2, and derive \mathrm{MSE} = \frac{1}{N^2}\sum_{\text{dropped}} c^2.
B9. (math) Show that an L-level pyramid of an N \times N image (N divisible by 2^L) has exactly N^2 coefficients, using a geometric sum.
B10. (math) Show that a circular shift of an image by one pixel changes only the phases of its DFT coefficients. Then give a 1D two-sample example showing that the Haar detail coefficients are not invariant to a shift by one sample.
B7. Rows: (a, b) \mapsto \big(\tfrac{a+b}{\sqrt2}, \tfrac{a-b}{\sqrt2}\big), (c, d) \mapsto \big(\tfrac{c+d}{\sqrt2}, \tfrac{c-d}{\sqrt2}\big). Columns: the left column \big(\tfrac{a+b}{\sqrt2}, \tfrac{c+d}{\sqrt2}\big) gives LL = \tfrac{a+b+c+d}{2} (top) and H = \tfrac{a+b-c-d}{2} (bottom); the right column gives V = \tfrac{a-b+c-d}{2} and D = \tfrac{a-b-c+d}{2}.
B8. \sum_{ij}X_{ij}^2 = \operatorname{tr}(X^\top X), and \operatorname{tr}\big((WXW^\top)^\top WXW^\top\big) = \operatorname{tr}(W X^\top X W^\top) = \operatorname{tr}(X^\top X W^\top W) = \operatorname{tr}(X^\top X) (cyclic trace, W^\top W = I). The map is linear, so the error image X - \hat X maps to the dropped coefficients C - \hat C; its energy is preserved: \sum (x - \hat x)^2 = \sum_{\text{dropped}} c^2; divide by N^2.
B9. Level j has three bands of (N/2^j)^2 = N^2/4^j; the final LL has N^2/4^L. Total 3N^2\sum_{j=1}^{L} 4^{-j} + N^2 4^{-L} = 3N^2\cdot\frac{1 - 4^{-L}}{3} + N^2 4^{-L} = N^2.
B10. y_{m,n} = x_{m, n-1} (indices mod N) gives Y_{k,l} = e^{-2\pi i l/N}X_{k,l}: |Y_{k,l}| = |X_{k,l}|. Haar on 4 samples (0, 8, 8, 8): details \big(\tfrac{0-8}{\sqrt2}, 0\big) = (-5.66, 0). Shifted by one (circularly) to (8, 0, 8, 8): (5.66, 0). Shifted by two, (8, 8, 0, 8): (0, -5.66). The same edge moves between coefficients and changes sign; there is no simple relation like a phase factor, because the downsampling keeps only even positions.
Explore
A 256 \times 256 image (the micrograph or a synthetic one) and its 2D wavelet transform. Panels: the image, the subbands (Mallat layout: grey LL in the corner, detail bands in blue/red, each scaled to its own largest value; with log |w| all bands in grey on a log scale), the reconstruction, and the error. keep K largest keeps a percentage of all coefficients (dropped ones are faded in the subband panel); zero bands lets you click subbands to remove them. compare shows the reconstructions from the same number of coefficients in the wavelet basis, the global Fourier basis and the 8 \times 8 block DCT. The plot gives PSNR against the percentage kept for the three. shift by 1 px moves the image one pixel to the right.
E1. Preset one level: three orientations (oriented bars, Haar, 1 level). In which band does each bar appear, and where? Compare with B1. Then set levels to 3.
E2. Preset pyramid of the cell (db2, 4 levels). Which band looks like a thumbnail? Which bands are the brightest in log |w| display, and which level has the most coefficients?
E3. Preset keep 3 %: Haar blocks. Read the PSNR and look at the reconstruction. Then select db4 and db8. What changes in the numbers and in the look of the errors?
E4. Preset wavelets vs Fourier vs DCT at 5 %. Read the three PSNRs. Move keep % to 1. What happens to the DCT reconstruction, and why (B4b)? Then choose CDF 9/7.
E5. Still in compare, choose the image disc and keep % = 2. Read the PSNRs. Select Haar: what is special at 3 %?
E6. Preset drop the finest level = blur (db4, 3 levels, the three level-1 bands removed). How many coefficients are kept, and what is the PSNR? Bring back V and H, keeping only D removed: PSNR? And only V removed? Then remove levels 1 and 2 entirely and compare with keep K largest at a similar percentage.
E7. Preset shift variance (square, Haar, 2 levels). By how much do the detail coefficients change? And the band energies? Choose the micrograph and db4, 3 levels.
E1. The vertical bar’s left and right sides appear in V (top right), as two vertical lines of opposite colour; the horizontal bar’s top and bottom in H (bottom left); the diagonal bar in all three detail bands, strongest along its edges. Flat areas are white (0) everywhere. With 3 levels the coarser bands show the same structures at lower resolution, and only the edges that fall inside a coarser pattern appear there.
E2. The top-left LL (16 \times 16) is the thumbnail. In log |w| the LL and the coarse bands are brightest (largest values): the energy sits at coarse scales. Level 1 has the most coefficients (3 \times 128^2 = 49\,152, three quarters of all), mostly small.
E3. Haar at 3 %: 19.9 dB, and the reconstruction is made of visible rectangular blocks. db4: 20.4 dB, db8: 20.5 dB; the blocks disappear and the error turns into a smooth blur with faint ringing near strong edges.
E4. At 5 %: db4 21.5, Fourier 21.0, DCT 21.2 dB; Fourier rings everywhere, the DCT shows 8 \times 8 blocks. At 1 %: db4 18.6, Fourier 18.4, DCT 10.5 dB, with many black blocks: those blocks kept no coefficient, not even their average. CDF 9/7: 21.8 dB at 5 %, 18.8 at 1 %.
E5. Disc at 2 %: Haar 47.6, db4 40.5, DCT 34.9, Fourier 29.8 dB (with the demo’s 4 levels). With Haar at 3 % the readout says “∞ (exact)”: the disc (with its antialiased edge) has fewer than 3 % nonzero Haar coefficients, so keeping 3 % keeps all of them.
E6. 16 384 of 65 536 coefficients (25 %), 23.9 dB: the fine texture is gone, the image is blurred. Only D removed: 31.5 dB; only V removed: 27.5 dB (vertical edges become soft): the diagonal band carries the least energy. Levels 1 and 2 removed: 4096 coefficients (6.3 %), 20.3 dB, worse than keeping the largest 5 % (21.4 dB with 3 levels): choosing coefficients by size beats choosing them by band.
E7. Square, Haar, 2 levels: the detail coefficients change by 68 % (\|c_{\text{shifted}} - c\|/\|c\|), but the level-1 band energies stay the same (1.27 \cdot 10^6 in V). Micrograph, db4, 3 levels: 92 %, with level-1 V energy 7.58 \cdot 10^6 \to 7.35 \cdot 10^6. The energy per band hardly changes; the individual coefficients do.
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 wavelets/src/dwt2d/exercise.rs. One level of the 1D filter bank of the last unit is given (analysis_1d, synthesis_1d, periodic border), with the filters Haar, db2 and db4.
C1. dwt2d_level(img, h): one level of the 2D transform, with the four bands in place:
for every row y: row y = analysis_1d(row y) # left half low-pass along x, right half high-pass
for every column x: column x = analysis_1d(column x) # top half low-pass along y, bottom half high-pass
# now: LL top left, V top right, H bottom left, D bottom right
The checks are B1 (the four 2 \times 2 blocks) and B2(a).
C2. idwt2d_level(c, h): the inverse, synthesis_1d on every column, then on every row. The check: one level and back gives the image.
C3. dwt2d(img, h, levels) and idwt2d(c, h, levels): the pyramid, repeating C1 on the LL band in the top-left corner (half the width and height every level), and back. The checks are B2(b) (two levels: LL = 20, H = −16, all else 0), \sum c^2 = \sum x^2, and the way back.
C4. keep_fraction(c, fraction): keep the largest coefficients, set the rest to 0, and return the dropped energy. psnr(a, b, peak): 10\log_{10}(\text{peak}^2/\mathrm{MSE}). The checks are B5 (36.3 dB, and 3 dB less for twice the dropped energy) and that the squared error equals the dropped energy.
Then cargo run -p wavelets -- dwt2d and open the pictures in out/dwt2d/.
C5. The program prints how much of the energy the LL band holds (db4, 4 levels). Compare with the lecture. Look at pyramid.png (shown twice as large; each detail band scaled on its own). What do the detail bands of the micrograph look like?
C6. The program prints the PSNR for keeping 1, 5 and 20 % of the coefficients with Haar, db2, db4 and Fourier. Compare with the table of B4. Then compare keep5-haar.png, keep5-db4.png and keep5-fourier.png: what kind of error does each basis make?
C7. Shift variance: the program shifts a square (Haar, 2 levels) and the micrograph (db4, 3 levels) by one pixel and prints how much the detail coefficients change, and the energy of the level-1 V band before and after. What do you conclude?
The model solution is wavelets/src/dwt2d/solution.rs in the download.
C5. The 16 \times 16 LL band, 0.4 % of the coefficients, holds 95.7 % of the energy, as on the slide “How sparse is a real image?”. In pyramid.png LL is a small thumbnail of the cell in the top-left corner; the detail bands look grainy at every level: the micrograph’s fine texture puts many small coefficients everywhere, and the edges of the nucleus are only faintly visible among them.
C6.
| kept | Haar | db2 | db4 | Fourier |
|---|---|---|---|---|
| 1 % | 18.2 | 18.5 | 18.6 | 18.4 |
| 5 % | 20.9 | 21.3 | 21.5 | 21.0 |
| 20 % | 25.7 | 26.1 | 26.4 | 25.0 |
The Haar, db4 and Fourier columns are those of B4. Haar’s reconstruction is made of rectangular blocks; db4’s is smoother, with the outline of the nucleus kept sharp and some faint ripples next to edges; the Fourier one is blurred everywhere, with fine ripples spread over the whole image.
C7. Square: 66.4 % of the detail coefficients’ norm changes, but the energy of the level-1 V band stays 26.25. Micrograph: 92.5 %, with the level-1 V energy going from 116.6 to 113.0 (in grey values 0..1). A one-pixel shift moves edges across the even–odd grid, so the individual coefficients change almost completely, while the energy per band hardly changes. The decimated transform is not shift-invariant.
Where this leads
Sparsity is useful beyond compression. Noise does not become sparse in any basis: an orthonormal transform spreads white noise evenly over all coefficients. The next unit, wavelet shrinkage, uses this to denoise by keeping the large coefficients and shrinking the small ones.