What an image's spectrum means, and why it finds the tilt
The OpenCV tutorial, the HIPR2 Fourier page and the DSP StackExchange thread, explained section by section, with the missing equations restored, three things to play with, and a note on how each idea shows up in jdeskew.
Theory: an image is a signal in two directions
- A sine wave sin(2π f t) has a spectrum with one spike at f, the winding frequency where the centre of mass jumps.
- Once a signal is sampled into N values, its spectrum repeats every N bins, so the DFT shows one period of N frequencies.
- An image is sampled along x and y, so the 2-D DFT winds it in both directions at once. Each point (u, v) asks how much of a stripe pattern with u cycles across and v cycles down the image contains.
- Slow changes (sky, skin) are low frequencies near the centre. Fast changes (edges, fine text, noise) are high frequencies far from it.
FFT in NumPy
f = np.fft.fft2(img) # complex array, one value per stripe pattern fshift = np.fft.fftshift(f) # move zero frequency (DC) from the corner to the centre spectrum = 20*np.log(np.abs(fshift)) # magnitude only, on a log (dB) scale
- Each complex value is a centre of mass: its length says how much of that pattern is present, its angle (phase) where the pattern's crests sit.
- fftshift puts the average brightness (DC) in the middle so the picture is symmetric and readable.
- abs keeps the magnitude. Tilt is about which patterns exist, not where they sit, so jdeskew drops the phase.
- log because DC is millions of times larger than the rest.
- A larger output size makes NumPy pad with zeros. Keep that in mind for section 5.
Filtering in the spectrum, and why hard masks ring
Zero the centre (high-pass) and only edges survive. Keep only the centre (low-pass) and the image blurs. A hard-edged mask causes ripples (ringing), because a sharp box in one domain is a sinc in the other. A Gaussian mask has soft edges and does not ring. Try it below on a synthetic test image.
The same in OpenCV
dft = cv.dft(np.float32(img), flags=cv.DFT_COMPLEX_OUTPUT) # 2 channels: real, imaginary mag = cv.magnitude(dft_shift[:,:,0], dft_shift[:,:,1]) # sqrt(re² + im²)
Same maths. OpenCV wants float32, returns real and imaginary parts as two channels, and runs about 3× faster than NumPy here.
Padding to an optimal size
nrows = cv.getOptimalDFTSize(342) # 360: a product of 2s, 3s and 5s nimg = cv.copyMakeBorder(img, 0, bottom, 0, right, cv.BORDER_CONSTANT, value=0) # about 4× faster
Why Laplacian and Sobel are high-pass filters
Take the FFT of a small kernel and you see what it lets through. Mean and Gaussian are bright at the centre (low-pass, blur). Laplacian is dark at the centre (high-pass, edges). Sobel x and Sobel y pass frequencies along one axis (edges in one direction). The reason: convolving an image with a kernel multiplies their spectra (the convolution theorem). Our structure-tensor baseline is built from Sobel gradients.
The DFT, with the equations restored
- Read the forward formula as winding: multiply every pixel by a 2-D spinning arrow and add everything up. The result F(k, l) is one centre of mass: how much of the wave with k cycles down and l cycles across the image contains.
- F(0, 0) is DC: winding at frequency 0 means no spin, so it is the sum, the average brightness.
- The inverse adds every wave back, weighted by F(k, l), and recovers the image exactly. It is the unmixing notebook run backwards.
- 1/N² goes on one of the two, never both. NumPy puts it on the inverse.
Separable, then fast
A 2-D DFT is a 1-D DFT along every row, then along every column of the result: 2N one-dimensional transforms. A plain 1-D DFT costs N² operations; the FFT costs N·log N, about 10,000 instead of 1,000,000 per row at N = 1,024. Classic FFTs want N = 2ⁿ; modern ones accept sizes made of 2s, 3s and 5s, which is what getOptimalDFTSize picks.
Magnitude, phase and the log scale
- Magnitude holds the geometry: orientations and spacings. That is all a deskewer needs.
- Phase looks like noise but places everything. Invert the magnitude alone and the image is "corrupted beyond recognition". Try Drop phase on the OpenCV tab.
- DC dwarfs everything, so the spectrum is shown on a log scale. It then shows energy at all frequencies, falling as frequency rises, plus vertical and horizontal lines from regular patterns in the photo. Straight structures in our photos (page edges, bezels) do the same and compete with the text.
Stripes, harmonics, and finding the text orientation
HIPR2 builds up from stripes to text. Set the stripes below and watch the spectrum: the peaks sit perpendicular to the stripes, at distance N / period from the centre, and rotate with them. Square-wave stripes (like lines of text) add harmonics at 3×, 5×, 7× the frequency along the same line. The frame option reproduces HIPR2's last example and our bug.
- Two mirrored points plus DC: the spectrum of a real image is always symmetric.
- Direction: the points lie along the direction in which brightness changes fastest, perpendicular to the stripes.
- Distance: 128 / period. The finest possible pattern, period 2 px (0.5 cycles per pixel), sits at the edge. HIPR2's 2-px-wide stripes have period 4, so they sit halfway out.
- Harmonics: a square wave of frequency f is a sum of sines at f, 3f, 5f, … with strengths 1, 1/3, 1/5, …. Lines of text are blocky and periodic too, so a page's streak is a row of harmonics, which is what jdeskew's radial projection sums.
- Rotated page: HIPR2's rotated text had "a second line … from the black corners". Here the rotated page's edges add their own lines. Box border: an axis-aligned frame adds a cross on the axes: jdeskew's padding bug.
Linearity, and why multiplying images blurs spectra
- Addition: FT(A + B) = FT(A) + FT(B). Add two spectra, invert, and you get the two images added. This is why unmixing works.
- Multiplication does not distribute (exercise 6). Multiplying two images convolves their spectra. A Hann window convolves the page's spectrum with a small smooth bump: a slight blur, no cross. A hard border convolves it with a sinc: long ripples along the axes, the cross.
The DCT, and why we never use it for tilt
The discrete cosine transform uses cosines only, gives real numbers and powers JPEG, where high-frequency coefficients are dropped. But it behaves like a DFT of the image mirrored at its edges, and a mirrored page contains the text at both +θ and −θ. The spectrum then cannot tell clockwise from counterclockwise, which is why mirror padding is ruled out in our plan (Moisan 2011).
The top answer, made interactive: one spectrum point is one stripe pattern
Click points in the frequency grid (left) to light them up. The image (right) is the inverse FFT: each point is a rotated cosine stripe pattern, and several points add up. Click a lit point to turn it off. This is the EPFL basis demo linked in the comments.
One lit pixel in the frequency domain gives a rotated cosine pattern in the image. Its position sets the stripes' direction and spacing, and any image is a weighted sum of such patterns. His pictures put the lowest frequency top-left because he did not fftshift.
cos(ωx + ψy) is a 2-D wave with one frequency per direction; its FFT gives (ω, ψ), just as the FFT of cos(ωx) gives ω.
For audio the spectrum is easier to read than the waveform. For images it is the reverse: the spectrum scrambles the picture, and most of what you see lives in the phase.
Fourier is one choice of orthogonal basis. A signal is broken into simple pieces, and orthogonality means each piece's amount is found independently by projection: multiply and sum. Wavelets and PCA are other bases.
High frequency means abrupt changes; noise is mostly high frequency, so low-pass filtering removes it.
What to carry into the deskew experiments.