Fourier, Then Deskew
Learn / Fourier, then deskew

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.

01

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:

eiθ = cos θ + i sin θThe point at angle θ (radians) on the circle of radius 1. The exponent is an arc length walked around the 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 θ.
Drag time, or press playtry f = 0.1, the video's slow spin
Complex plane. The tip traces the unit circle; its shadow on each axis is cos θ and sin θ.
Its two shadows over time: real part cos, imaginary part sin.
Frequency f (laps per second)
0.10
Time t (seconds)
4.39 s
Angle θ = 2πft2.76 rad
Point(-0.93, 0.37)
Laps done0.44
02

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:

ĝ(f) = average over t of g(t) · e−2πiftThe centre of mass of the wound-up drawing. As a function of the winding frequency f, this is the Fourier transform.
  • 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.
Set the beat, then sweep the winding
The sound, 1 + cos(2π · beat · t), over 4.5 seconds.
Wound up at the winding frequency, with its centre of mass.
x of the centre of mass for every winding frequency from 0 to 5. The dot is your current winding.
Beat (per second)
3.0
Winding (per second)
2.40
Centre of mass x-
Distance from 0-
03

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.

Pick the notes
Notes (Hz)
Envelope
What the microphone hears: all notes added, 0.1 s.
x of the centre of mass, 200 to 600 Hz. Dots mark the peaks found.
Unmixed. Thick grey: each true note. Colour: the note rebuilt from its peak alone.
Found-
04

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.
First: what k and l meantwo counts, one per direction
The (k, l) pattern
Along the top row, left to right: count the waves. That count is l.
Down the left column, top to bottom: that count is k. Dots are the 16 pixels; push k past 8 to see a slower red wave through the same dots.
k: waves going down
2
l: waves going across
3
Examples
Reading-
  • 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.
F(k, l) = Σa Σb f(a, b) · cos(2π(k·a + l·b)/N) − i · Σa Σb f(a, b) · sin(2π(k·a + l·b)/N)This is HIPR2's formula with e−iθ = cos θ − i sin θ written out. The cosine sum checks the pattern with its crests in one position, the sine sum the same pattern shifted by a quarter period. Together they are section 02's centre of mass, now winding across two directions.
  • 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.
Compute one cell of the spectrum by handclick a cell on the right, or scan them all
Image f(a, b)
Numbers
1. The image f(a, b), the input: 16 × 16 brightness values.
2. Test pattern cos(2π(k·a + l·b)/16).
3. = 1 × 2, pixel by pixel: 256 numbers. Yellow is positive, blue negative.
4. Add up all 256 numbers of 3: the total is one cell (outlined). Every cell is one (k, l). Across: l, down: k, centre (0, 0).
Pattern (k, l)-
Running total of 3-
Σ f · cos-
Σ f · sin-
|F(k, l)|-
Reading-
Hover a pixel in 1, 2 or 3-

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.
Going back: each cell is a stripe patternStackExchange's top answer, interactive
Spectrum cells from −8 to 8 (across: l, down: k). Light some up; the mirror cell glows faintly.
Inverse FFT

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.

05

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.

1. One dot means one stripe pattern A bright dot says the image contains that pattern; its brightness says how much. Add a second pattern to the image and a second pair of dots appears.
2. Where the dot sits tells you which pattern Distance from the centre is how many waves fit across the image, so the period is image size ÷ distance (here 128 px ÷ distance; the rings mark 16, 32 and 48 waves). Direction from the centre is the way the stripes change, at 90° to the stripes. Drag the yellow dot; the ring is its mirror twin, the same strength (rule 3).
-
3. Dots come in mirror twins A cosine is two arrows spinning opposite ways (cos θ = average of eiθ and e−iθ), so a normal image puts the same dot at (k, l) and at (−k, −l). An image whose pixels are whole arrows (complex numbers, shown here as colours) spins one way only and makes a single dot. Real photos are never like that, so their dots always come in pairs.
-
4. Smooth makes few dots; sharp makes many A smooth wave is one pattern. A sharp edge can only be built from many patterns added together, all changing the same way, so they line up: a row of dots.
-

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:

  1. Ignore the centre. It is always bright (the average brightness) and says nothing about patterns.
  2. Find the twin pairs and lines. Each is a pattern that repeats across the image.
  3. Read the angle of a line. The stripes run at 90° to it. For text, that is the tilt.
  4. Read the distance of the first dot. Period = N ÷ distance. For text, that is the line spacing.
  5. 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.
Predict before you look0 of 0 right
Image 1 of 5. Which spectrum belongs to it?
Pick one of the three spectra.
06

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.

Why a blocky stripe is a row of dots: build it from wavesFourier series of a square wave
One row across the stripes. Grey: the blocky profile. Yellow: the sum of the waves so far. Each added wave sharpens the edges.
The waves used: ×1, ×3, ×5, … with amounts +1, −1/3, +1/5, −1/7 (yellow up, blue down). Each bar becomes a dot in the spectrum, but the spectrum only shows its size; the sign is phase, and the magnitude drops it.
Waves added
3
  • 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.
Set the stripes, then switch on the guideHIPR2, sections 6 and 9
Image, 128 × 128.
Spectrum. With the guide on: circles mark where the ×1, ×3, ×5, ×7 dots should be; dashed red ones have run past the edge and wrapped around.
Radial projection. For each angle (x), the brightness summed along that ray of the spectrum (y). Hover to see the ray. Tallest peak = the tilt; dashed green = truth.
Tilt
20°
Period
16 px
Profile
Frame
Guide
True tilt20°
Read from spectrum-
First dot at-
Dots inside the edge-

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.

06b

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.
Aliasing, visually: drag the dot past the edgethe square is all 128 pixels can hold
Where the dot really is (red ring when outside the square) and where the pixels put it (yellow).
The real stripes, drawn 4× finer than the pixel grid.
What 128 pixels record: one sample per pixel. Past the edge, a different, coarser pattern at a different angle appears.
Reading-

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.
The same page, captured small, same and big, then sized to 128 pxa 1/8-scale model of 64 → 1,024 and 2,048 → 1,024
Captured at
How to shrink
As captured.
Sized to 128 px, what the deskewer sees.
Its spectrum. Rings: strongest dots.
Radial projection. Hover for the ray. Green: the true 12°.
True tilt12°
Read-
What happened-

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.

07

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.
Paint on the spectrumcrossML's idea, plus OpenCV's filters
Input: shapes, text rows and a screen-like stripe pattern.
Spectrum. Drag to paint out frequencies; dimmed areas are removed.
Inverse FFT of the edited spectrum.
Brush
Brush size
4
Presets
08

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.

Run jdeskew step by stepclick a step: the picture and the code lines change together
Input
Code version
Step
What happens here-
Trace one photo through get_angle: every valuechange the inputs, the numbers follow
Photo height (image.shape[0])
4000 px
Photo width (image.shape[1])
3000 px
vertical_image_shape
angle_max
The page at each step. Grey: the page; hatched: the zero padding; dashed circle: the ray length r. Steps 2 and 3 share one zoom; the photo has its own, so read the sizes from the labels.
LineValue hereMeaning
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 −φ.
jdeskew/estimator.pybeforeafter, PR #30View diff
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.
_get_angle_radial_projectionreads the angle off the streakSource
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
Reproduce the bug and the fixsynthetic page, the real thresholding rule
Binary page after padding (white is ink).
log |FFT|. Text: a tilted streak. Photo border: a cross.
Radial projection. Hover to see each angle as a ray on the spectrum. The dot is jdeskew's answer.
Tilt
18°
Input
Order
Taper
True tilt18°
jdeskew reads-
Error-
09

What to keep

1The transform is a centre of massWind the signal at each frequency and average. It moves away from 0 only where the signal repeats at that frequency.
2One spectrum point is one stripe patternDirection from the centre is the direction of change; distance is the frequency.
3Text lines make a streakBlocky periodic rows give a line of harmonics at 90° to the text. Its angle is the tilt, read modulo 90°.
4Magnitude for orientation, phase for picturesjdeskew keeps only the magnitude; rebuilding an image needs both.
5Every sharp straight edge adds a lineA photo's border, filled corners, page edges, screen bezels. The padding bug and the perspective problem are both this.
6Soft beats sharpHard masks and borders ring (sinc); Hann and Gaussian fades do not. And never mirror-pad: a mirrored page holds +θ and −θ, so the sign of the tilt is lost.