Exercise: images in frequency space
Before this unit: Filtering & convolution (previous unit).
Goal
By the end of this exercise you should be able to:
- predict where a wave or a stripe pattern shows up in the spectrum, and why a real image has a spectrum with mirror pairs,
- explain what a shift does to the spectrum,
- find the frequency response of a kernel by trying it on a few waves, and say whether it is low-pass or high-pass,
- predict aliasing when an image is sampled too coarsely,
- choose between low-pass, high-pass, band-pass and notch filters for a given problem,
- (math) compute a small DFT by hand, prove that the waves are orthogonal, and derive the mirror symmetry, the shift theorem and the frequency response in general.
Do the pen-and-paper part first, then the interactive parts. Questions marked (math) ask for derivations; do the others first.
By hand
B1. The 8 samples x = (1, 0, -1, 0, 1, 0, -1, 0) are one wave. How many cycles does it complete in the window? Its spectrum has exactly two non-zero coefficients. At which frequencies, and why two?
B2. Predict where the bright dots are in the centred spectrum of a 256 × 256 image of (a) vertical stripes (lines running up and down), 16 pixels apart; (b) horizontal stripes, 4 pixels apart; (c) the sum of the two images. Which dots lie further from the centre, and why?
B3. (Frequency response by numbers.) Filter three signals of length 8 with the blur \tfrac14\,(1, 2, 1) and with the second difference (1, -2, 1), wrapping around at the ends: the flat signal 1, 1, 1, \dots; the slow wave 1, 0, -1, 0, 1, 0, -1, 0; the fastest wave 1, -1, 1, -1, \dots. Each output is the input wave multiplied by a number: find it. Which filter is low-pass and which high-pass? Compare the number for the flat signal with the sum of the weights.
B4. (Shift.) Shift the wave x = (1, 0, -1, 0) one step to the right, wrapping around: y = (0, 1, 0, -1). Its DFT is X = (0, 2, 0, 2), and that of y is Y = (0, -2i, 0, 2i). Compare the sizes |X_k| and |Y_k|. What does a shift change, and what does it keep? What does this mean for the magnitude spectrum of a cell that moves within an image?
B5. (Aliasing.) A stripe pattern repeats every 3 pixels: \cos(2\pi n/3) for n = 0, 1, 2, \dots You halve the image by keeping every 2nd pixel. Write down the kept samples for n = 0, 2, 4, 6, 8, 10, 12. What period do you see in the small image, and what period does that correspond to in the original pixels? Could the small image have shown the true pattern at all? What should you have done before keeping every 2nd pixel?
B1. One cycle every 4 samples, so 2 cycles in the window of 8: frequency 2. A real wave such as \cos is the sum of two complex waves, frequency +2 and frequency -2, so it has two coefficients: X_2 = X_6 = 4 (index 6 = 8 - 2 is frequency -2), all others 0. That is the mirror pair.
B2. (a) Vertical stripes change brightness from left to right: dots on the horizontal axis, at 256/16 = 16 cycles, (u, v) = (\pm 16, 0). (b) Horizontal stripes change from top to bottom: dots on the vertical axis at 256/4 = 64, (0, \pm 64). (c) The DFT is linear, so the spectrum of the sum is the sum of the spectra: all four dots. The dots of (b) are four times further out, because those stripes are four times finer (higher frequency). In every case the pair of dots lies perpendicular to the stripes and mirrored through the centre.
B3. Blur, each output is \tfrac14(\text{left} + 2\cdot\text{centre} + \text{right}). Flat: 1, 1, 1, \dots, multiplied by 1. Slow wave: 0.5, 0, -0.5, 0, \dots, multiplied by 0.5. Fastest: \tfrac14(-1 + 2 - 1) = 0 everywhere, multiplied by 0. Second difference, \text{left} - 2\cdot\text{centre} + \text{right}: flat: 0, multiplied by 0. Slow wave: -2, 0, 2, 0, \dots, multiplied by −2. Fastest: -1 - 2 - 1 = -4 at a +1, so -4, 4, -4, \dots, multiplied by −4. The blur keeps the flat signal, halves the slow wave and removes the fastest: low-pass. The second difference removes the flat signal and grows with the frequency (0, 2, 4 in size): high-pass. The number for the flat signal is the sum of the weights: \tfrac14(1 + 2 + 1) = 1 and 1 - 2 + 1 = 0.
B4. |X| = (0, 2, 0, 2) and |Y| = (0, 2, 0, 2): the sizes are the same. The shift changed the complex numbers (2 \to -2i and 2 \to 2i), that is the phase of each wave: it now peaks one step later. The magnitude spectrum is unchanged. So a cell that moves within the image has the same magnitude spectrum: the magnitudes say what structures are there, the phases say where.
B5. The kept samples are \cos(2\pi n/3) at n = 0, 2, 4, \dots: 1, -0.5, -0.5, 1, -0.5, -0.5, 1. They repeat every 3 samples of the small image, which is 6 original pixels: a false pattern twice as coarse as the real one. The small image has pixels 2 original pixels apart and needs at least two samples per cycle, so it can only show periods of 4 original pixels or more: a period of 3 cannot be represented, and it folds back as period 6. Blur (low-pass) the image first, to remove the pattern before keeping every 2nd pixel; then the small image shows a flat grey instead of a false pattern.
Math questions
B6. (math) (Orthogonality.) Show that for integers m, n \ge 1, \int_0^1 \sin(2\pi m t)\,\sin(2\pi n t)\,dt = \begin{cases} 0 & m \ne n,\\ \tfrac12 & m = n.\end{cases} (Use \sin a \sin b = \tfrac12[\cos(a - b) - \cos(a + b)].) If f(t) = \sum_n a_n \sin(2\pi n t), how do you get a_3 back from f?
B7. (math) Compute the DFT X_k = \sum_{n=0}^{3} x_n e^{-2\pi i kn/4} of x = (1, 0, -1, 0) for k = 0, 1, 2, 3. Which wave is x? Why are there two non-zero coefficients for a single wave? (Check your answer against B4.)
B8. (math) Show that for a real signal x, X_{N-k} = \overline{X_k}. Use this to explain why a single stripe pattern in an image gives a pair of dots in its 2D spectrum, mirrored through the centre.
B9. (math) (Shift theorem.) Let y_n = x_{n-m} (indices modulo N: the signal is shifted by m and wraps around). Show that Y_k = e^{-2\pi i km/N}\, X_k. What happens to |X_k|, and what to the phase? What does this mean for the magnitude spectrum of a cell that moves within the image? (Compare with B4.)
B10. (math) (Frequency response.) Filtering with the 1D kernel w = (w_{-1}, w_0, w_1) multiplies the wave e^{i\omega n} by \hat w(\omega) = w_{-1}e^{-i\omega} + w_0 + w_1 e^{i\omega}. Compute \hat w(\omega) for
(a) the blur \tfrac14(1, 2, 1) and (b) the second difference (1, -2, 1).
Evaluate both at \omega = 0 (a constant signal) and \omega = \pi (the fastest wave the grid can hold: +1, -1, +1, \dots). Which is low-pass, which high-pass? Relate \hat w(0) to the sum of the weights. Check your formulas against the numbers of B3, where the slow wave has \omega = \pi/2.
B6. \sin(2\pi m t)\sin(2\pi n t) = \tfrac12[\cos 2\pi(m-n)t - \cos 2\pi(m+n)t]. Over one period, \int_0^1 \cos(2\pi j t)\,dt = 0 for any integer j \neq 0 and = 1 for j = 0. If m \ne n both terms integrate to 0. If m = n, the first term is \tfrac12 \cdot 1 and the second 0, giving \tfrac12. So, multiplying f by \sin(2\pi \cdot 3 t) and integrating kills every term except n = 3: a_3 = 2\int_0^1 f(t)\sin(6\pi t)\,dt. This is a projection onto one basis vector.
B7. e^{-2\pi i k n/4} = (-i)^{kn}, and only n = 0 and n = 2 contribute: X_k = 1 - (-i)^{2k} = 1 - (-1)^k. So X = (0, 2, 0, 2). The signal x_n = \cos(2\pi n/4) is one cycle of a cosine. Since \cos\theta = \tfrac12(e^{i\theta} + e^{-i\theta}), it is made of frequency +1 and frequency -1, and index k = 3 = N - 1 is frequency -1.
B8. X_{N-k} = \sum_n x_n e^{-2\pi i (N-k)n/N} = \sum_n x_n e^{-2\pi i n}\, e^{2\pi i kn/N} = \sum_n x_n e^{2\pi i kn/N}, since e^{-2\pi i n} = 1. For real x_n this is the complex conjugate of X_k. A real stripe pattern is a cosine wave, which needs both e^{+i\theta} and e^{-i\theta}: frequencies (u, v) and (-u, -v), a pair of dots mirrored through the centre, with equal magnitude.
B9. Y_k = \sum_n x_{n-m} e^{-2\pi i kn/N}. Substitute p = n - m (the sum runs over all residues modulo N either way): Y_k = \sum_p x_p e^{-2\pi i k(p+m)/N} = e^{-2\pi i km/N} X_k. The factor has modulus 1, so |Y_k| = |X_k|: the magnitude is unchanged and only the phase changes, by -2\pi km/N. The magnitude spectrum of an image does not depend on where the cell is: it describes what structures are present, not where. (This is why the magnitude spectrum is useful as a texture feature, and also why the phase cannot be thrown away when rebuilding an image.)
B10. (a) \hat w(\omega) = \tfrac14(e^{-i\omega} + 2 + e^{i\omega}) = \tfrac14(2 + 2\cos\omega) = \tfrac12(1 + \cos\omega). \hat w(0) = 1: constants pass unchanged. \hat w(\pi) = 0: the fastest wave is removed completely. Low-pass. (b) \hat w(\omega) = e^{-i\omega} - 2 + e^{i\omega} = 2\cos\omega - 2 = -4\sin^2(\omega/2). \hat w(0) = 0: constants are removed. \hat w(\pi) = -4: the fastest wave is amplified 4 times (and flipped). High-pass; for small \omega, \hat w \approx -\omega^2, the frequency response of a second derivative (\tfrac{d^2}{dt^2}e^{i\omega t} = -\omega^2 e^{i\omega t}). In both cases \hat w(0) = \sum w, the sum of the weights.
Explore: build a wave
The demo below adds up five waves, a_f \sin(2\pi f\,t) for f = 1, \dots, 5 cycles per window, over one window 0 \le t \le 1. Each slider sets one amplitude a_f and has the same colour as its thin line in the plot; the bold black line is the sum. (A sine is a cosine with phase \varphi = -\pi/2.) The bar chart shows the amplitude spectrum |a_f|: the amount of each frequency, which is what the Fourier transform of the black curve gives back.
W1. Choose pure tone. How many cycles does the sum complete in the window, and what does the spectrum look like? Now set that slider to −1. What changes in the plot, and what changes in the spectrum? Which of the three sinusoid parameters (frequency, amplitude, phase) did the sign change?
W2. Start from all zero, set a_1 = 1, then add a_3 \approx 0.33 and finally a_5 = 0.2 (or press square). Describe how the shape of the sum changes at each step. Roughly what height do the flat parts reach? Which frequencies would you have to add to make the edges steeper still?
W3. Press sawtooth and compare its spectrum with the one for square. Then change the signs of a_2 and a_4 to +1/2 and +1/4. What happens to the signal, and to the spectrum? (Compare with B4 and B9.) Finally, change only a_3 to -1/3. Does the signal still have the same shape? What information does the amplitude spectrum leave out?
W1. The pure tone is \sin(2\pi\cdot 2\cdot t): two cycles in the window, and a single bar at f = 2 of height 1. With amplitude −1 the wave is flipped upside down, which is the same as sliding it half a cycle along: the phase changed by \pi. Frequency and the height |a| are the same, so the amplitude spectrum does not change.
W2. a_1 alone is one smooth swell. Adding the third harmonic flattens the tops and steepens the sides; adding the fifth flattens them further, with small ripples on the plateaus. The flat parts sit near \pm\pi/4 \approx \pm 0.79 (that is the limit of \sin x + \tfrac13\sin 3x + \tfrac15\sin 5x + \dots; with three terms the plateaus wiggle around this value). Steeper edges need higher odd harmonics: f = 7, 9, 11, \dots with amplitudes 1/7, 1/9, \dots. Sharp edges live at high frequencies.
W3. The square wave uses only the odd frequencies; the sawtooth uses all five, with heights 1, 1/2, 1/3, 1/4, 1/5. Flipping the signs of a_2 and a_4 gives the same sawtooth, moved by half a window: shifting t by 1/2 multiplies \sin(2\pi f t) by (-1)^f, so it flips exactly the even frequencies. The spectrum is unchanged, as in B4 and B9: a time shift changes the phases, not the amplitudes. Flipping only a_3 is not a shift: the signal gets a clearly different shape, yet the bars are still the same. The amplitude spectrum leaves out the phase of each wave (here only its sign), so different signals can share the same amplitude spectrum. The full Fourier transform keeps the phase too, which is why the signal can be rebuilt from it.
Explore: filter an image
The demo below is the lecture’s micrograph (a 256 × 256 crop). Left: the image; middle: its 2D spectrum, log of the magnitude, with frequency 0 in the centre; right: the image rebuilt from the coefficients you keep. Removed coefficients are shown dark red. The radial filters keep the coefficients whose distance r from the centre lies between a min radius and a max radius (the two blue circles; ∞ means no upper limit). The buttons are presets: low-pass sets min = 0, high-pass sets max = ∞, band-pass uses both. The box “keep average brightness (centre)” keeps the centre coefficient whatever the min radius is. The readout gives the share of coefficients kept, the share of the image’s variation they carry, and the RMS error of the rebuilt image (pixel values run from 0 to 1).
E1. Choose low-pass (min radius 0) and set the max radius to 5, 30 and 90. For each, note the percentage of coefficients kept and the percentage of the variation kept. What does that tell you about where the image’s content sits in the spectrum?
E2. Choose keep largest at 3%. Then go back to low-pass and find the max radius that also keeps about 3% of the coefficients. Which of the two has the smaller error? Look at where the kept coefficients lie in the spectrum in “keep largest” mode: why are the two results so similar?
E3. Choose high-pass (max radius ∞) with min radius 10. What is left of the cell? Why is the picture grey rather than black, although most of the low frequencies are gone? Untick keep average brightness (centre) to check your answer.
E4. Tick add stripe artefact and choose no filter: note the error. The stripe adds two bright coefficients to the spectrum, marked with yellow rings. Erase them by dragging over them. What happens to the error? Why are there two dots for one stripe? Then try removing the stripe with a low-pass filter instead, at max radius 15. Which approach is better here?
E5. Go back to low-pass with max radius 30, then raise the min radius from 0 to 5, so that only a ring between the two circles is kept. How many coefficients does that remove, and how much of the variation? What disappears from the image, and what is left? Compare with E1.
E1. Radius 5 keeps 0.12% of the coefficients but already 53% of the variation; radius 30 keeps 4.3% of the coefficients and 81% of the variation; radius 90 keeps 39% and 96%. A tiny disc of low frequencies carries most of the variation: the broad light and dark regions. The many high-frequency coefficients each carry little; together they make the fine detail (and the grain). This is why a frequency basis compresses natural images well.
E2. Keep largest 3%: 81% of the variation, RMS error 0.100. Low-pass with max radius 25 also keeps 3.0% of the coefficients: 78% of the variation, error 0.109. Keeping the largest coefficients is slightly better, because it picks the coefficients that matter for this image, while the disc is fixed in advance. They are similar because most of the largest coefficients are low frequencies anyway: in “keep largest” mode the kept coefficients crowd around the centre, with a scatter of single ones further out.
E3. Only edges and fine texture remain: the outline of the nucleus, the membranes, the grain inside the cell. Large uniform regions all become the same grey, because their brightness is low-frequency content. The picture stays grey because the centre coefficient (frequency 0, the average brightness of the whole image) is kept by the “keep average brightness” box, even though it lies inside the min radius. Untick the box and the average of the rebuilt image drops from 0.66 to 0: the values vary around 0, the negative half is shown as black (about half the pixels), and the RMS error jumps from 0.18 to 0.69.
E4. With the stripe and no filter the error is 0.106 (the stripe itself). The stripe is a single 2D wave, so it adds a single bright pair of coefficients, about 19 units from the centre (16 across, 10 down, and its mirror image). Erasing them brings the error down to about 0.02; zeroing exactly the two coefficients would give 0.002, the brush also removes a few of the cell’s own coefficients around them. There are two dots because a real-valued wave is the sum of a frequency and its mirror image (+k and -k), the mirror symmetry of B1 and B8. A low-pass filter at max radius 15 also removes the stripe, but it removes the cell’s detail too: the error is 0.127, worse than leaving the stripe in. A notch removes exactly what you want to remove; a low-pass removes everything above a frequency.
E5. Raising the min radius from 0 to 5 removes very few coefficients: the kept share drops from 4.3% to 4.2% (only 68 of the 65 536 coefficients lie inside radius 5, not counting the centre, which is kept). But the variation kept drops from 81% to 29%, and the RMS error rises from 0.10 to 0.19. As in E1, the few lowest frequencies carry about half of the variation: they are the broad shading, such as the dark nucleus against the lighter cytoplasm. Without them the nucleus becomes the same mid grey as its surroundings, and what is left is structure of intermediate size: the outline of the nucleus, membranes and small organelles, but neither the overall shading (below the min radius) nor the fine grain (above the max radius). A band-pass picks out structures of one size range.
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 images/src/fourier/exercise.rs. The library has complex numbers: Complex::from_angle(θ) is e^{i\theta}, and + and * work as usual.
C1. dft(x): the DFT straight from its definition, a sum for every frequency:
for k in 0 .. N−1:
X[k] = 0
for n in 0 .. N−1:
X[k] = X[k] + x[n] · e^(−2πi·k·n/N)
The checks are the table of the lecture slide “The DFT is a change of basis” and B1.
C2. idft(X): the inverse, with + in the exponent and a factor \tfrac1N. The check: idft(dft(x)) gives x back.
C3. frequency_response(w, n): the number each wave is multiplied by when filtered with the small kernel w. Put the kernel into a signal of length n (centre weight at index 0, the weight for offset d at index -d, wrapped around), and take its DFT. The check is B3.
C4. dft2(img, inverse): the 2D DFT is the 1D DFT of every row, then of every column of the result.
C5. lowpass(img, radius): transform, set every coefficient whose frequency (u, v) is further than radius from 0 to zero, transform back, keep the real part. Index k above N/2 stands for the negative frequency k - N.
Then cargo run -p images -- fourier. It takes a few seconds, and prints the frequency responses of the two kernels of B3 for all 8 frequencies.
C6. How many complex multiplications does your dft2 need for an N \times N image? Compare N = 256 and N = 1024 with the FFT, which needs about 2N^2\log_2 N.
C7. The printed responses of the blur and the second difference are real numbers. Why? And why is the response of “take the right neighbour”, in the check of C3, complex with size 1?
The model solution is images/src/fourier/solution.rs in the download.
C6. One 1D DFT of length N takes N^2 multiplications. dft2 does N rows and N columns, so 2N \cdot N^2 = 2N^3 in all:
| N | dft2 (2N^3) |
FFT (2N^2\log_2 N) |
|---|---|---|
| 256 | 3.4 \cdot 10^7 | 10^6 |
| 1024 | 2.1 \cdot 10^9 | 2 \cdot 10^7 |
Four times the side length makes the plain DFT 64 times slower, and the FFT only about 20 times.
C7. Both kernels are symmetric (w_{-1} = w_1). The sines of +d and -d cancel in the sum, so only cosines remain: real numbers. The printed values are \tfrac12(1 + \cos\omega) and -2(1 - \cos\omega) with \omega = 2\pi k/8. “Take the right neighbour” is a shift: it keeps the size of every wave and only moves it, so it changes the phase and not the size. That is B4 again.
Where this leads
Frequency-space features (peaks, orientation, texture energy in a ring) are a classic input for classifying textures (texture features). Larger blurs at many scales (a scale space) and the Laplacian of Gaussian come back when we detect objects (scale space, on the edges day). The next unit, principal component analysis, is another change of basis: not fixed waves, but directions learned from a set of images.
Later: the optical transfer function of a microscope (image formation), deconvolution as division in frequency space (deconvolution), localised waves (wavelets), the cosine transform in JPEG, the central-slice theorem of tomography, and shifts found from the phase of the spectrum (phase correlation).