How does a page's spectrum give away its tilt?
From one spinning arrow to the line of code in jdeskew that reads a tilt. Every step has something to play with. Built from 3Blue1Brown's video, the OpenCV and HIPR2 Fourier pages, a DSP StackExchange thread and a crossML post on editing spectra.
The spinning arrow, e2πift
An arrow on a circle that spins f laps per second. Multiplying by it rotates things.
Euler's formula turns an exponent into a point on a circle:
- θ = π is half a lap, which lands on −1. That is eπi = −1.
- θ = 2πt completes a lap every time t grows by 1, so the arrow spins once per second.
- θ = 2π·f·t spins f times per second. A negative f spins clockwise; the Fourier transform uses e−2πift.
- Multiplying by it rotates. Its length is 1, and multiplying complex numbers adds their angles, so z · eiθ is z turned by θ.
Winding a signal around the circle
Wind a signal around the circle: its centre of mass leaves zero only at the signal's own frequency.
Take a sound whose intensity is g(t), here a pure beat g(t) = 1 + cos(2π·3t). Multiply it by the spinning arrow: at each moment the arrow points where the spin says, and its length is how loud the sound is. Then average all those points:
- Winding at the wrong speed: loud moments land all around the circle and cancel, so the centre of mass sits near 0.
- Winding at the beat's own speed: every loud moment lands on the same side, so the centre is pulled out. That is the spike.
- At f = 0 nothing spins, and the centre is the average loudness, 1. In images this is the DC term.
Unmixing: one peak per note
Winding adds up, so a chord of notes gives one clean peak per note.
Play several notes at once and the waveform looks like noise. But winding is linear: the centre of mass of a sum is the sum of the centres of mass. Each note only lights up when the winding matches it, so the transform shows one clean peak per note. A peak's position gives the pitch and its height the loudness, which is enough to rebuild each note on its own.
Each note fades in and out (a Hann envelope). Without the fade, the sudden start and stop would add ripples beside every peak. Keep that in mind: it is the same reason we taper a page before its FFT in section 08.
From sound to images: what f(a, b) and F(k, l) actually are
For an image, F(k, l) scores one stripe pattern: multiply the pattern into the image and add everything up.
For sound, the signal was one list of numbers over time and the transform was one curve over frequency. An image is a table of numbers, so its transform is a table too. Let's take a tiny 16 × 16 image so every cell is visible.
- f(a, b) is the image itself: the brightness of the pixel in row a (counting down) and column b (counting across). 0 is black, 1 is white. For a 16 × 16 image, a and b each run 0 to 15, so f is 256 numbers.
- F(k, l) is a score for one stripe pattern: the pattern that repeats k times going down and l times going across. Lay that pattern over the image, multiply the two pixel by pixel, and add up all 256 products. If the image contains that pattern, bright pixels keep landing on the pattern's crests and the sum is large. If not, positives and negatives cancel and the sum is near 0.
- Do it for every pattern. k and l each take 16 values (the card below shows why), so there are 16 × 16 = 256 patterns and the scores form a second 16 × 16 table: the spectrum. Same size as the image, one cell per stripe pattern instead of one cell per pixel.
- Only whole numbers. The DFT treats the image as a tile that repeats, so a pattern must wrap around seamlessly: 0, 1, 2, … whole waves.
- 8 is the finest. In 16 pixels the finest pattern alternates dark, light, dark, light: 8 waves. Push k above 8 with the slider and watch: 9 waves look exactly like 7 waves going the other way (−7), 15 like −1. Sampled patterns above 8 are copies, called aliases.
- So 16 choices each. The distinct counts are −8 to 7 for k and the same for l: 16 × 16 = 256 patterns, exactly as many as there are pixels. A negative count means the stripes lean the other way.
- Exactly enough. 256 scores are precisely what is needed to rebuild 256 pixels, nothing more and nothing less. That is why the spectrum has the same size as the image.
- Why two sums: the image's stripes might sit a little to one side of the test pattern's crests. The cosine sum catches stripes that line up with the crests, the sine sum catches stripes a quarter period over, and anything in between shows up in both.
- Magnitude |F| = √(cos-sum² + sin-sum²) is how much of the pattern there is, wherever it sits. Phase, the angle of (cos-sum, sin-sum), is where its crests sit. Tilt only needs the magnitude.
A worked example. Image: vertical stripes, f = 0.5 + 0.5 cos(2π·4b/16). Probe (0, 4), the same stripes: every product is 0.5 cos + 0.5 cos², the cos parts cancel over a full wave, and the cos² parts add to 0.5 × 128 = 64. Probe (0, 3), different stripes: the products swing between positive and negative and add to exactly 0. One bright cell, one dark cell.
What to notice. Pick Tilted stripes and click around: almost every cell scores near 0, and only two mirror-image cells light up, the ones whose pattern matches the stripes. Switch to Text rows: the bright cells line up on the vertical axis, because rows of text change as you go down. Switch to Tilted text: that line of bright cells tilts with the text. That tilted line is the streak jdeskew measures.
- Direction: a cell's direction from the centre is the direction in which its pattern changes, at 90° to the stripes.
- Distance: a cell further from the centre is a finer pattern. Period = N / distance, so the outermost cells are the finest pattern a pixel grid can hold, a period of 2 px.
- (0, 0) is DC: a "pattern" that never changes, so its score is just the sum of all pixels, the image's total brightness. It is usually by far the biggest cell, so the display caps it.
- Mirror pairs: (k, l) and (−k, −l) are the same stripes, so a real image's spectrum is always symmetric about the centre.
- fftshift: NumPy's FFT puts (0, 0) in the top-left corner of the table. np.fft.fftshift rearranges it so (0, 0) is in the middle, as drawn here. The FFT itself is just a fast way to compute all 256 scores at once instead of one by one.
In jdeskew: np.fft.fft2(opt_gray) computes all these scores for the whole binarised page (about a million cells at 1,024 px), fftshift centres them, and np.abs keeps the magnitude. The radial projection in section 08 then looks for the line of bright cells and reads its angle.
Reading any spectrum: four rules
Four rules let you read any spectrum, and predict it, without memorising anything.
You never need to memorise what a spectrum looks like. These four rules are enough to predict it from the image, or to read the image off the spectrum. Each card below lets you test one rule.
About the rings. They mark the strongest cells (at least a fixed share of the brightest dot), always together with their twin; weaker cells are still there, only dimmer. Three things that look like exceptions are not:
- A dot on the top edge with no partner at the bottom. A 128-pixel spectrum runs from −64 to 63, like −8 to 7 in section 04. There is no +64 row because +64 and −64 are the same pattern (every pixel flips), so an edge dot is its own twin.
- Dots at every multiple, not only odd ones, in Blocky: these stripes are 7 px light and 9 px dark, not exactly half and half, and uneven stripes need the even multiples too.
- Small clusters on the horizontal axis in Text rows: the synthetic words repeat every 23 px, and 128 ÷ 23 is not a whole number, so each dot smears over 2 or 3 cells. Real words are irregular and give a faint blur there instead; only the line spacing is truly regular, which is why deskewers trust the vertical streak.
Reading a spectrum, in order:
- Ignore the centre. It is always bright (the average brightness) and says nothing about patterns.
- Find the twin pairs and lines. Each is a pattern that repeats across the image.
- Read the angle of a line. The stripes run at 90° to it. For text, that is the tilt.
- Read the distance of the first dot. Period = N ÷ distance. For text, that is the line spacing.
- Be suspicious of lines along the axes. They usually come from a sharp border or straight edges, not from the content: the padding bug in section 08.
Stripes, harmonics, and how text gives away its tilt
Rows of text make a line of dots through the centre. The line's angle is the tilt.
A page of text is close to a set of blocky stripes: dark rows of letters, light gaps between them. Rule 4 says blocky means many dots. This section shows exactly which dots, and why they line up into the streak jdeskew measures.
- Only odd multiples, because of a symmetry. Shift a 50/50 stripe by half a period and it flips (white ↔ black). An even multiple (×2, ×4) fits whole waves into that half period, so it comes back unchanged and cannot help build something that flips: its amount is 0. An odd multiple lands half a wave off and flips too. (The 7/9 stripes in section 05 break this symmetry, so even multiples appear there.)
- Amounts 1, 1/3, 1/5, with alternating signs. The ×n wave wiggles n times inside one stripe; multiplied by the stripe and added up (section 04's score), most wiggles cancel and about 1/n survives. The alternating + and − sharpen the corners while flattening the top: watch it as you add waves.
- All of them change in the same direction as the stripes (each is a function of the same distance across the stripes, just n times faster; phase slides crests sideways but never turns them), so in the spectrum they sit on one straight line through the centre, at 1×, 3×, 5×… the first dot's distance. That line of dots is the streak.
- Rotate the stripes and the whole line rotates with them. HIPR2's last example rotates English text by 45° and reads the angle off this line, the idea jdeskew is built on.
Why very thin stripes look messy. The spectrum has an edge, 64 from the centre: the thinnest stripes a pixel grid can show (2 px). For 4 px stripes the first dot sits at 128 ÷ 4 = 32, but the ×3 and ×5 helper dots belong at 96 and 160, past the edge. They do not vanish. Like walking off one side of an old video game and coming back on the other, they wrap around and reappear in the wrong places, scattering into a messy grid. With 12-16 px stripes every helper dot fits inside the edge and the line stays clean. The tilt still reads right either way, because the first dot is the brightest.
- For jdeskew: at about 1,024 px page height, text lines are tens of pixels apart, so their dots stay inside the edge. One reason not to shrink pages too far.
- No frame, faint cross on the axes: the FFT pretends the image repeats like floor tiles. At the seams the stripes do not match, and those straight seams draw a faint cross (about 1% of the brightness).
- Rotated page: the page's edges are straight lines too. The edges running along the stripes overlap the stripes' line; the edges crossing them add a second line at 90° (HIPR2's "second line"), which the plot ignores because it only checks angles within 45° of upright. The tiny axis lines come from drawing tilted edges as pixel staircases.
- Box frame: four straight edges lined up with the axes make a strong cross (about 6%). Its upright line gives the plot a second peak at 0°, 61% as tall as the stripes' peak here. With little text, that 0° peak wins and the deskewer says "level": exactly the jdeskew padding bug in section 08.
One line to remember: every straight edge draws a line through the spectrum's centre, and the deskewer picks the brightest line. Text should win; borders and frames try to steal it.
Resolution and aliasing: why 1,024 px, and what goes wrong when you shrink
Detail finer than 2 px per wave cannot be stored. It wraps to the wrong place unless you blur first.
- Where the edge comes from. The thinnest stripe a pixel grid can draw is one dark pixel, one light pixel: 2 px per wave. So at most N ÷ 2 waves fit across an image N pixels wide, and the spectrum runs from −N/2 to N/2 − 1. For 128 px that is −64…63; for 16 px, −8…7; for jdeskew's 1,024 px, −512…511.
- A dot's distance counts waves on the page; the edge counts pixels. A page with 40 lines of text puts its first dot 40 from the centre, whatever the resolution. Resizing does not move the dots, it moves the edge: 512 at 1,024 px tall, 128 at 256 px, 32 at 64 px.
- Past the edge, a dot wraps around. Pixels cannot tell a too-fine wave from a coarse one going the other way (the wagon wheel of section 04), so a dot that belongs at +96 on a 128 px grid shows up at 96 − 128 = −32. In 2-D each direction wraps separately, so it usually lands at a different angle, off the text's line. Drag a dot past the edge below to watch it happen.
- The tilt usually survives, because the first dot is the brightest and stays inside; wrapped helpers are weaker (1/3, 1/5) and scatter. Too much wrapping, though, and stray lines can outvote the text.
Resizing to a fixed size, small versus big. jdeskew's paper (and our tests) first resize every page to the same height, 1,024 px. A small and a big image go through that resize in opposite directions:
- A small image, say 64 × 64, is blown up 16×. Upscaling cannot add detail: each pixel just becomes a 16 × 16 block (or a smooth blend). Its spectrum keeps the original dots, with the edge simply moved out from 32 to 512 and nothing new in between except faint copies from the blockiness. Whatever the small image could not hold is gone for good: if its text lines were under about 2 px apart, they were already lost, or worse, already wrapped to a wrong angle when the picture was taken, and upscaling keeps the wrong dots.
- A big image, say 2,048 px, is shrunk 2×. The edge comes in from 1,024 to 512. Text-line dots (about 40 to a few hundred) still fit, but finer detail between 512 and 1,024 (letter strokes, paper texture, a screen's pixel grid, halftone dots) no longer fits. Shrinking by just skipping pixels wraps that detail back in as stray dots and lines. Blurring first (averaging each block of pixels, OpenCV's INTER_AREA) removes it instead, so it fades away rather than landing in the wrong place.
- In code: jdeskew resizes with cv2.resize(…)'s default INTER_LINEAR, which barely blurs when shrinking a lot; our redesign uses INTER_AREA. One small reason it is more precise.
Try: at 512 px, compare "Skip pixels" (the fine paper texture wraps into a coarse diagonal pattern and stray dots) with "Average, blur first" (it fades away). Then pick 32 px: the 20 text lines are only 1.6 px apart there, under the 2 px minimum, so they were never captured properly, and blowing the image up cannot bring them back.
Editing the spectrum: filters, ringing, and phase
Change the spectrum, invert, and the image changes. Sharp cuts ring; soft cuts don't.
Because the spectrum is just another description of the image, you can change the image by changing its spectrum, then inverting. The crossML post builds a small app where you paint on the spectrum to remove frequencies and watch the image change. Below is the same idea. The test image has a diagonal stripe pattern over it, like the moiré you get photographing a screen. Its four bright off-centre dots are that pattern: paint them out and the stripes vanish.
- Low-pass keeps the centre: the image blurs (the OpenCV tutorial's mask). High-pass removes the centre: only edges survive.
- Ringing. A hard-edged mask makes ripples beside edges, because a sharp box in one domain is a sinc wave in the other. A soft Gaussian mask does not ring. Compare the presets.
- Mirror. Painting keeps the spectrum symmetric so the result stays a real image.
- Phase. "Magnitude only" throws the phase away and inverts: all the right frequencies, in all the wrong places (HIPR2's "corrupted beyond recognition").
- Convolution theorem. Blurring with a kernel multiplies the spectrum by the kernel's spectrum, which is why the OpenCV tutorial can explain a Laplacian (dark centre) as a high-pass filter and a Gaussian (bright centre) as a low-pass one.
jdeskew, line by line, and the padding bug
Threshold, pad, FFT, then find the brightest line through the centre. The bug was padding white before thresholding.
jdeskew (Pham et al., ICIP 2022) is sections 04 and 05 turned into about 30 lines of code. Here is _get_fft_magnitude before and after the fix that was merged upstream, with what each line does.
| Line | Value here | Meaning |
|---|
Every term, line by line
get_angle
- image: the page as a NumPy array; cv2.imread gives rows × columns × 3 colour channels (blue, green, red).
- image.shape is (height, width, channels), so image.shape[0] is the height in pixels.
- vertical_image_shape: the height to resize to first. None, the default, means no resize. The paper and our tests use 1024. Resizing keeps the FFT fast and makes text roughly the same size in pixels, which the fixed 15 px threshold window relies on.
- ratio = vertical_image_shape / image.shape[0]: the scale factor. cv2.resize(image, None, fx=ratio, fy=ratio): None means "use the factors, not an exact size"; the same factor for width and height keeps the page's shape. Default interpolation: linear.
- angle_max: how far to search, in degrees (−angle_max to +angle_max). None means 15. A 20° tilt cannot be found with 15; for photos we pass 45.
_get_fft_magnitude
- _ensure_gray: colour to one brightness channel (0 black to 255 white); already-gray images pass through.
- ~gray: 255 − value, so ink is bright and paper dark.
- adaptiveThreshold(~gray, 255, GAUSSIAN_C, BINARY, 15, -10): per pixel, ink (255) if it is more than 10 brighter than the bell-weighted average of its 15 × 15 window, else 0.
- _ensure_optimal_square(binary, value=0): pads the bottom and right with 0 up to getOptimalDFTSize(max(h, w)), the next size made only of factors 2, 3 and 5. Square, so angles in the spectrum are true.
- fft2 → one complex score per stripe pattern; fftshift → (0, 0) to the centre; abs → how much of each, phase dropped.
_get_angle_radial_projection
- r = c = m.shape[0] // 2: c is the centre's row and column; r is the ray length.
- num = 20: angles per degree. linspace(-angle_max, angle_max, int(angle_max·num·2)): that many evenly spaced angles, about 0.05° apart, turned into radians.
- For each angle t: np.arange(r) gives distances 0 … r−1; y = c + int32(d·cos t), x = c + int32(−d·sin t) are the ray's pixels (decimals dropped); points outside the array are removed; li[i] = sum(m[y, x]) is the ray's total brightness.
- argmax(li): the brightest ray; its angle in degrees is the answer. Edge rule: exactly −angle_max returns 0 (meant for blank pages).
- Using it: rotate(image, get_angle(image)) levels the page. A page turned counterclockwise by φ returns −φ.
def _get_fft_magnitude(image): gray = _ensure_gray(image) # colour to gray opt_gray = _ensure_optimal_square(gray) # pad to a square of a fast FFT size (OpenCV tutorial), with WHITE opt_gray = cv2.adaptiveThreshold(~opt_gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 15, -10) binary = cv2.adaptiveThreshold(~gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 15, -10) opt_gray = _ensure_optimal_square(binary, value=0) # threshold first, then pad with 0: no ink in the padding dft = np.fft.fft2(opt_gray) # section 04: wind the page in 2-D shifted_dft = np.fft.fftshift(dft) # DC to the centre magnitude = np.abs(shifted_dft) # keep magnitude: orientation lives here return magnitude
- The threshold marks a pixel as ink when it is 10 levels darker than the Gaussian-weighted average of its 15 × 15 neighbourhood. Binarising throws away shading and keeps the line structure.
- The bug. Before the fix the page was padded with white, then thresholded. A scan has white margins, so nothing changes. A photo is darker than white, so every pixel along the photo-to-padding edge is much darker than its neighbourhood and becomes ink: a sharp rectangle, which section 06 says puts a cross on the axes. On tilted photos that cross outvoted the text, and jdeskew answered about 0°.
- The fix thresholds the real image and adds the padding afterwards as 0 (no ink), so there is nothing to draw.
tr = np.linspace(-angle_max, angle_max, int(angle_max * num * 2)) / 180 * np.pi # candidate angles, 0.05° apart for i, t in enumerate(tr): x = np.arange(0, r) # radii along one ray from the centre y = c + np.int32(x * np.cos(t)) # ray at angle t from the vertical axis x = c + np.int32(-1 * x * np.sin(t)) li[i] = np.sum(m[y, x]) # total brightness along that ray a = tr[np.argmax(li)] / np.pi * 180 # the brightest ray is the streak: its angle is the tilt