Exercise: transform coding, the DCT and the KLT

Goal

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

  • apply a small DCT by hand and use Parseval to find the error of dropping coefficients,
  • explain energy compaction with the two-pixel rotation and the KLT (PCA of blocks),
  • predict which 8 × 8 DCT coefficients a flat block, an edge or a texture has,
  • explain why the DCT beats the DFT on blocks (no jump at the block edges),
  • compare whole-image and block transforms at the same number of kept coefficients.

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

Background

Idea What it means
Orthonormal transform c = A x, x = A^\top c; rows of A are the basis vectors
Parseval \sum_k c_k^2 = \sum_n x_n^2; dropping coefficients costs exactly their squares
2-point DCT c_0 = (x_0 + x_1)/\sqrt2, c_1 = (x_0 - x_1)/\sqrt2: a 45° rotation
4-point DCT rows (0.5, 0.5, 0.5, 0.5), (0.653, 0.271, -0.271, -0.653), (0.5, -0.5, -0.5, 0.5), (0.271, -0.653, 0.653, -0.271)
8 × 8 DCT C = D X D^\top; C_{00} = 8 \cdot block mean; (u, v) = (horizontal, vertical) frequency
KLT eigenvectors of the covariance of the blocks (PCA), ordered by eigenvalue
DFT vs DCT DFT: block repeated periodically (jumps at the edges); DCT: block mirrored (no jumps)

By hand

B1. Two neighbouring pixels (x_0, x_1) = (100, 104). (a) Compute the 2-point DCT. (b) Drop c_1 and transform back. What is the squared error, and how does it compare with c_1^2?

B2. Use the 4-point DCT matrix of the background table. (a) Transform (1, 1, 1, 1) and (1, 2, 3, 4). (b) Check that the second row has length 1 and is orthogonal to the fourth. (c) What is the sum of the squared coefficients of (1, 2, 3, 4), and of the squared pixel values?

B3. Keep only c_0 of (1, 2, 3, 4). What is the reconstruction, and what is its squared error? Check with Parseval. Then keep c_0 and c_1: what is the squared error now?

B4. Pairs of neighbouring pixels (mean removed) have the covariance S = \sigma^2 \begin{pmatrix} 1 & \rho \\ \rho & 1 \end{pmatrix}. (a) Find the eigenvalues and eigenvectors of S (the KLT). Compare with the 2-point DCT. (b) What fraction of the energy is in the first KLT coefficient for \rho = 0.95, and for \rho = 0?

B5. 8 × 8 blocks, after subtracting 128 from every pixel. (a) A flat block of value 200: which coefficients are non-zero, and what is C_{00}? (b) A block whose left four columns are 200 and right four columns 60: which coefficients can be non-zero? Which row of the 64 basis images do they belong to? (c) The same edge, but horizontal (top four rows 200, bottom four rows 60)? (d) Stripes 40 40 230 230 40 40 230 230 repeated in every row?

B6. The row 10 20 30 40 50 60 70 80. Sketch three periods of its periodic extension and of its mirrored extension. Which has jumps? Which transform will need more coefficients for this row, and why?

B7. A 256 × 256 image is cut into 8 × 8 blocks. How many blocks are there? If you keep the largest 1% of all block-DCT coefficients, how many is that per block on average? What must happen to some blocks?

B1. (a) c_0 = 204/\sqrt2 = 144.25, c_1 = -4/\sqrt2 = -2.83. (b) With c_1 = 0: x = (c_0/\sqrt2, c_0/\sqrt2) = (102, 102). Squared error 2^2 + 2^2 = 8 = c_1^2. Nearly all of the energy is in c_0.

B2. (a) (1,1,1,1) \mapsto (2, 0, 0, 0): a constant has only the DC coefficient. (1,2,3,4) \mapsto (5, -2.230, 0, -0.159). (b) 0.653^2 + 0.271^2 + 0.271^2 + 0.653^2 = 1.000; 0.653 \cdot 0.271 + 0.271 \cdot (-0.653) + (-0.271) \cdot 0.653 + (-0.653)(-0.271) = 0. (c) 25 + 4.975 + 0 + 0.025 = 30 = 1 + 4 + 9 + 16.

B3. c_0 alone gives x = 5 \cdot (0.5, 0.5, 0.5, 0.5) = (2.5, 2.5, 2.5, 2.5), the mean. Squared error 1.5^2 + 0.5^2 + 0.5^2 + 1.5^2 = 5 = c_1^2 + c_2^2 + c_3^2 = 4.975 + 0 + 0.025. Keeping c_0 and c_1: error = c_3^2 = 0.025: two coefficients describe the ramp almost perfectly.

B4. (a) \det(S - \lambda I) = 0 gives \lambda = \sigma^2(1 \pm \rho), with eigenvectors (1, 1)/\sqrt2 and (1, -1)/\sqrt2: exactly the rows of the 2-point DCT, for every \rho > 0. (b) \frac{1 + \rho}{2}: 97.5% for \rho = 0.95, 50% for \rho = 0 (uncorrelated pixels: no rotation helps).

B5. (a) Only C_{00} = 8 \cdot (200 - 128) = 576. (b) Every row of the block is the same, so all vertical frequencies are zero: only the top row v = 0. The row (72, 72, 72, 72, -68, -68, -68, -68) is antisymmetric about its centre except for its mean (2): C_{00} = 8 \cdot 2 = 16, and of the others only the odd u = 1, 3, 5, 7 (antisymmetric cosines). (c) The left column u = 0: C_{00} and C_{10}, C_{30}, C_{50}, C_{70} (rows of the coefficient table). (d) Again only the top row; the pattern has period 4 (half a cycle per 2 pixels), so the largest coefficient is near u = 4 (2 periods in 8 pixels); the demo shows u = 3 and u = 5 largest, with u = 1 and u = 7 smaller, because the stripes are not centred like a cosine.

B6. Periodic: … 70 80 | 10 20 … 80 | 10 20 …: a jump from 80 down to 10 at every edge (a sawtooth). Mirrored: … 20 10 | 10 20 … 80 | 80 70 …: continuous (a triangle wave). The DFT needs many coefficients for the jumps (slow 1/k decay); the DCT describes the ramp with two (B3).

B7. 32 \cdot 32 = 1024 blocks. 1% of 65 536 coefficients is 655: 0.64 per block. At least 369 blocks get no coefficient at all, not even their average (DC): they decode as flat grey (the level shift). JPEG avoids this by always coding the DC of every block.

Math questions

B8. (math) Show that the 8 × 8 2D DCT C = D X D^\top is orthonormal as a map from \mathbb R^{64} to \mathbb R^{64} if D is, and that its basis images are the outer products of rows of D.

B9. (math) Show that the KLT coefficients are uncorrelated, and that the expected squared error of keeping only the first k of them is \sum_{j > k} \lambda_j.

B10. (math) Derive the DCT from the DFT of the mirrored signal y = (x_0, \dots, x_{N-1}, x_{N-1}, \dots, x_0): show Y_k = 2 e^{i\pi k/2N} \sum_n x_n \cos\frac{\pi(2n+1)k}{2N}.

B11. (math) Show that the DFT coefficients of a jump decay like 1/k: compute the DFT of the sawtooth x_n = n, n = 0, \dots, N-1, for k \ne 0 (hint: \sum_n n z^n for z = e^{-2\pi i k/N}). What is |X_k| for small k/N?

B8. Write X as a vector x (row-major). C = D X D^\top is c = (D \otimes D)x, and (D \otimes D)^\top (D \otimes D) = (D^\top D) \otimes (D^\top D) = I. The basis image for (u, v) is row (v, u) of D \otimes D: the entries D_{v y} D_{u x}, the outer product of rows v and u of D.

B9. c_j = u_j^\top x, so E[c_i c_j] = u_i^\top E[x x^\top] u_j = u_i^\top S u_j = \lambda_j u_i^\top u_j = \lambda_j \delta_{ij}. Dropping c_{k+1}, \dots gives the error x - \hat x = \sum_{j > k} c_j u_j, with E\|x - \hat x\|^2 = \sum_{j > k} E[c_j^2] = \sum_{j > k} \lambda_j (Parseval in the orthonormal basis u_j).

B10. Y_k = \sum_{n=0}^{N-1} x_n e^{-i\pi nk/N} + \sum_{n=0}^{N-1} x_n e^{-i\pi(2N-1-n)k/N}. The second exponent: e^{-2\pi i k} e^{i\pi(n+1)k/N} = e^{i\pi(n+1)k/N}. Factor out e^{i\pi k/2N}: e^{-i\pi nk/N} = e^{i\pi k/2N} e^{-i\pi(2n+1)k/2N} and e^{i\pi(n+1)k/N} = e^{i\pi k/2N} e^{i\pi(2n+1)k/2N}; their sum is e^{i\pi k/2N} \cdot 2\cos\frac{\pi(2n+1)k}{2N}.

B11. With z = e^{-2\pi i k/N} \ne 1 and z^N = 1: \sum_{n=0}^{N-1} n z^n = \frac{N z^N}{z - 1} - \frac{z(z^N - 1)}{(z-1)^2} = \frac{N}{z - 1}. So |X_k| = \frac{N}{|z - 1|} = \frac{N}{2\sin(\pi k/N)} \approx \frac{N^2}{2\pi k} for small k/N: decay like 1/k. The mirrored ramp (a triangle wave) has coefficients that decay like 1/k^2.

Explore: one block in three bases

Left: the image with the selected block (yellow; click to move it) and the energy in the best k coefficients, averaged over all blocks of the image, for the DCT (blue), the DFT (red) and the KLT (green). Middle: the block’s pixel values and its reconstruction from the kept coefficients. Right: the 64 coefficients of the block minus 128 (red positive, blue negative, grey dropped) and the 64 basis images (kept ones framed orange; click one to keep or drop it). Basis: DCT; DFT written as real cosine and sine basis images; KLT learnt from all 1024 blocks of the current image. Keep: the k largest coefficients of this block, the first k in zigzag order (eigenvalue order for the KLT), or by hand.

D1. Presets flat block: only DC, vertical edge and texture block. Check your answers to B5 (a), (b) and (d): which coefficients are non-zero, and what is C_{00}?

D2. Preset vertical edge with k largest. Lower k from 8 to 1. How much energy and what RMS error do 1, 2, 3 and 4 coefficients give? Which coefficient is kept first, and why not the DC?

D3. Preset ramp: DFT leaks, DCT does not (a steep ramp, DFT, first 3). Note the energy kept and the RMS error. Switch to the DCT. Then set k = 2 for both. Explain with B6.

D4. Preset a block of the cell (k = 6 largest). Compare the three bases. How many DCT coefficients do you need for an RMS error below about 11 grey levels? Why does this block need so many more than the synthetic blocks?

D5. Preset KLT looks like the DCT. Look at the KLT basis images: which DCT basis images do the first few resemble? Read the energy curves at k = 4 for the three bases. Then choose the test card image: how do the curves change, and why can the KLT now beat the DCT by much more?

D1. Flat (200 everywhere): only C_{00} = 576. Vertical edge (200 | 60, edge in the middle): C_{00} = 16 and the top-row coefficients 507.4, −178.2, 119.1, −100.9 at u = 1, 3, 5, 7: five non-zero, all in the top row. Texture (40 40 230 230 …): C_{00} = 56, and u = 1, 3, 5, 7 in the top row: −285.3, −583.8, 390.1, 56.7.

D2. k = 1: 82.0% of the energy, RMS error 29.7; k = 2: 92.2%, 19.6; k = 3: 96.7%, 12.8; k = 4: 99.9%, 2.0 (the fifth, the DC of 16, gives 100%). The first kept coefficient is C_{01} = 507.4, the half cosine that follows the step; the DC is only 16 because the block mean (130) is close to the level shift 128.

D3. DFT, first 3: 74.8% of the energy, RMS error 12.65. DCT, first 3: 99.6%, 1.58. With k = 2 the numbers are the same (the third zigzag coefficient is a vertical frequency, zero for this block). The DFT sees a sawtooth with a jump at the block edge (B6) and spreads the energy over all horizontal frequencies; the DCT sees a continuous triangle wave and needs one cosine.

D4. DCT 60.7% (RMS 17.9), DFT 61.7% (17.7), KLT 63.2% (17.3): all similar and poor. With the DCT, k = 20 gives 85.8% and RMS 10.7. The micrograph block is grainy (electron-microscope texture and noise at the pixel scale); its energy is spread over many coefficients, while a flat block, a straight edge or regular stripes need one to five.

D5. The first KLT images look like the DCT’s DC, the two lowest horizontal and vertical cosines and then second-order patterns; the curves at k = 4: DCT 87.0%, DFT 85.6%, KLT 87.3%: the KLT is only a little better. On the test card: DCT 86.4%, DFT 88.8%, KLT 97.4%. The card has a few kinds of blocks (flat, one edge, the same stripes again and again), so its blocks lie in a low-dimensional subspace that the KLT learns; the DCT does not adapt to that. For natural, smooth images the KLT’s advantage is small, which is why a fixed basis (nothing to store) wins in practice.

Explore: periodic or mirrored?

One row of 8 samples (drag the black points up or down). Top: its periodic extension, what the DFT assumes; middle: its mirrored extension, what the DCT assumes. Right: the size of the DFT (red) and DCT (blue) coefficients in frequency order, and the row rebuilt from the first k coefficients of each (dashed: the original).

R1. Preset ramp, k = 3: note the RMS errors. Compare the coefficient bars: how fast do they fall off for each transform?

R2. Preset step (20 20 20 20 80 80 80 80). Compare the errors for k = 2 and k = 4. Does the DCT still win clearly? Why is a step harder for the DCT than a ramp?

R3. Preset smooth bump with k = 2. Which transform wins now? Look at the periodic extension to explain it.

R4. Preset random: what does k change? What does that say about compressing noise?

R1. k = 3: DCT 2.49, DFT 13.55. DCT: 127.3, −64.4, 0, −6.7, 0, −2.0, 0, −0.5: fast decay. DFT (real form): 127.3, −20.0, −48.3, −20.0, −20.0, −20.0, −8.3, −14.1: the coefficients stay large to the end, the signature of the jump.

R2. k = 2: DCT 12.69, DFT 28.06; k = 4: DCT 8.36, DFT 11.48. The DCT is still better, but neither is good: the jump now lies inside the block, and mirroring cannot remove it. Edges inside a block are expensive for every Fourier-type basis (they ring, as the next unit shows).

R3. k = 2: DFT 2.33, DCT 15.74 (with k = 3: DFT 1.46, DCT 1.19). The bump starts and ends at about the same height (30 and 40), so its periodic extension has almost no jump, and one DFT cosine-sine pair describes the hump; the DCT needs its second cosine (k = 2) for a shape that rises and falls. The DCT’s advantage is about the ends of the block.

R4. Almost nothing: the error drops from 25.6 (k = 1) to 25.3 (k = 4) for both. Noise has its energy spread evenly over all coefficients in every orthonormal basis; no transform compacts it.

Explore: the whole image, three bases

The Fourier unit’s demo with a basis switch: DFT of the whole image (as there), DCT of the whole image, or 8 × 8 DCT (every block transformed separately; the coefficient picture groups them by frequency, one 32 × 32 tile per (u, v)). In the DCT bases only “no filter” and “keep largest” apply. The readout gives the share of coefficients kept, the share of the image’s variation they keep, and the RMS error.

F1. keep largest at 3% (as in the Fourier unit’s exercise). Note the variation kept and the RMS error for the three bases. Which is best?

F2. Now keep 1% and 10%. What happens to the 8 × 8 DCT at 1%? Look at the rebuilt image and use B7.

F3. In the 8 × 8 DCT picture, the top-left tile is a small copy of the image. Why?

F1. 3%: DFT 81.3% of the variation, RMS 0.100; DCT 83.7%, 0.093; 8 × 8 DCT 81.5%, 0.099. The whole-image DCT is best: it has no wrap-around jump at the image border, which costs the DFT coefficients. The block DCT is as good as the whole-image DFT, despite its 1024 separate blocks.

F2. 1%: DFT 72.8% (0.120), DCT 75.5% (0.114), 8 × 8 DCT 64.5% (0.137). 655 coefficients for 1024 blocks: many blocks keep nothing and come out flat mid grey, others keep only their DC (flat at their mean): the image breaks into visible 8 × 8 squares. 10%: DFT 89.8% (0.074), DCT 91.8% (0.066), 8 × 8 DCT 91.2% (0.068).

F3. The (0, 0) tile holds the DC coefficient of every block, 8 \times (block mean − 0.5), at the block’s position: a 32 × 32 thumbnail of the image (one pixel per 8 × 8 block; shown as a magnitude, so it shows how far each block’s mean lies from mid grey). The other tiles show where in the image each frequency is strong, e.g. the edges of the nucleus in the low-frequency tiles.

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 compression/src/dct/exercise.rs.

C1. dct_matrix(n): the N \times N DCT matrix, one basis vector per row:

for k in 0 .. N−1:
    α = sqrt(1/N) if k = 0, else sqrt(2/N)
    for n in 0 .. N−1:
        D[k][n] = α · cos(π (2n + 1) k / 2N)

The checks are the 4-point matrix of the background table, and that the rows of the 8-point matrix are orthonormal (B2(b)).

C2. dct(x) and idct(c): the coefficients c = D x and back, x = D^\top c. The checks are B1, B2 and B3, including Parseval.

C3. dct2(block) and idct2(coeffs): the 2D DCT C = D X D^\top, separable:

transform every row with the 1D DCT
then transform every column of the result

C[(u, v)] is the coefficient of horizontal frequency u and vertical frequency v. The checks are B5(a) (C_{00} = 576), B5(b) with the demo’s numbers of D1, and that idct2 undoes dct2.

C4. keep_largest_blocks(img, fraction): block transform coding without quantisation:

for every 8 × 8 block: C = dct2(block)
t = the size |c| of the k-th largest of all coefficients     # k = fraction · number of pixels
set every coefficient with |c| < t to 0
for every block: block = idct2(C)

Then cargo run -p compression -- dct and open the pictures in out/dct/: basis64.png (the 64 basis images made with your idct2), and the micrograph rebuilt from 1 %, 3 % and 10 % of its coefficients, with 8 × 8 blocks (blocks-keep*.png) and with one DCT of the whole image (whole-keep*.png). The program subtracts mid grey before the transform (JPEG’s level shift), and prints the share of the image’s variation that is kept, and the RMS error.

C5. Compare the numbers for blocks and the whole image with F1 and F2 of the demo. Look at blocks-keep1.png and whole-keep1.png: why does the block version break up at 1 %? (B7.)

C6. Count the cost: how many multiplications does the matrix method of C2 need for one DCT of the whole 256 \times 256 micrograph (all rows, then all columns), and how many for its 1024 blocks of 8 \times 8?

The model solution is compression/src/dct/solution.rs in the download.

C5. Share of the variation kept (RMS error): at 1 %, blocks 64.5 % (0.137) and whole image 75.5 % (0.114); at 3 %, 81.5 % (0.099) and 83.7 % (0.093); at 10 %, 91.2 % (0.068) and 91.8 % (0.066). These are the demo’s numbers. At 1 % there are 655 coefficients for 1024 blocks: many blocks keep nothing and come out mid grey, others only their DC and come out flat. blocks-keep1.png is a mosaic of flat squares. The whole-image version is smoothly blurred, without a grid. At 3 % and 10 % the two are close.

C6. Whole image: one 256-point DCT by matrix is 256^2 = 65\,536 multiplications; 256 rows and 256 columns make 512 \cdot 65\,536 = 3.4 \cdot 10^7. Blocks: an 8-point DCT is 64 multiplications, 16 per block (8 rows, 8 columns), so 1024 per block and about 10^6 for all 1024 blocks: 32 times fewer (= 256 / 8). That is one reason for small blocks; a fast transform (like the FFT) makes large DCTs cheaper too.

Where this leads

The transform only rearranges the image. JPEG (next unit) quantises the 64 coefficients of each block with a table, coarse for high frequencies, reads them in zigzag order so the zeros come last, and entropy-codes them with run lengths and Huffman codes. The same “transform, then keep the important coefficients” idea is behind wavelet compression (JPEG 2000) and behind PCA-based shape and appearance models (shape models). On the sparse representations day the 64 DCT patches become the starting dictionary that is then learned from the image itself (dictionary learning).