Every image is a sum of striped waves
The Fourier transform rewrites one image as a recipe: which stripe patterns, at which sizes and angles, added together, rebuild it exactly. Work through the sections in order, or jump to the one you need.
- Build an image from wavesClick a frequency, see the stripes it makes
- Reading a spectrumWhat dots, lines, rings and crosses mean
- Filter labLow-pass, high-pass, band filters and ringing
- Kernels are filters tooBlur, Sobel and Laplacian as frequency masks
- Hybrid imagesLow frequencies of one image, high of another
- Magnitude vs phaseWhich half of the spectrum holds the picture
- Periodic noise removalClick the spikes away with a notch filter
- Where it’s usedThe CV pipeline, use cases and why it matters
- The codeLoop-only Python and the OpenCV version
Build an image from waves
Click the dark square to add a wave and watch the image it makes.
Each dot is one wave. Its distance from the centre is the frequency (how many stripes fit across the image), its direction is the direction the wave travels, so the stripes run perpendicular to the line from the centre to the dot. Every dot comes with a mirror twin on the opposite side: a real-valued image needs the pair, and the transform of any photo is symmetric this way.
Predict before you click: a dot straight above the centre makes horizontal or vertical stripes? Now drag one dot slowly outward. What happens to the stripe spacing?
So do we need two images?
No. The transform takes one image of size H×W and returns one array of H×W complex numbers, the spectrum. Nothing is lost: the inverse transform gives the exact same pixels back. Two images only appear when the task itself compares or mixes images: aligning two frames (phase correlation), blending them (hybrid images), or convolving an image with a kernel, which you can treat as a second tiny “image”.
For an image f(y, x) with M rows and N columns, the formula is:
Read it as a similarity score. For each candidate wave (u cycles down, v cycles across) you multiply the image by that wave and add everything up. If the image has a lot of that pattern, the sum is big. The result is complex: its magnitude says how much of the wave is present, its phase says where the wave’s crests sit. F(0, 0) is just the sum of all pixels, the “wave” with zero frequency, which is why it’s always the brightest point.
Reading a spectrum
Pick a test pattern and look at its magnitude spectrum. Three display tricks are always used, and the switches let you turn each off to see why: shifting the zero frequency to the centre, a log scale (the centre is often a million times brighter than the rest), and an optional window that fades the borders.
What to look for
Stripes give two clean dots. Rotate them and the dots rotate too. At angles that don’t fit a whole number of cycles in the image, the dots smear: that’s spectral leakage, the transform assumes the image tiles the plane, and a wave that doesn’t wrap cleanly isn’t a single frequency.
A square gives a cross-shaped pattern of ripples (a 2D sinc), a disc gives rings. Sharp edges need many high frequencies; that’s why things with crisp boundaries spread energy far from the centre. The Gaussian blob is the special case: its transform is another Gaussian, with no ripples. Make it wider in space and it gets narrower in frequency. That inverse relationship is the uncertainty principle of signal processing, and you’ll meet it again with blur kernels.
A single edge gives a line through the centre perpendicular to the edge. Real photos show the same thing: strong lines in the spectrum mean many edges at one orientation (buildings, fences, text lines). The bright “+” cross through almost every photo’s spectrum is mostly fake: it comes from the seam where the left border wraps into the right. Tick the Hanning window and watch it fade.
Load the sample scene and switch off the log scale. Almost all the energy sits in a few pixels at the centre. Natural images have most of their energy at low frequencies, with magnitude falling off roughly as 1/frequency, which is why compression and blurring lose so little that you notice.
Filter lab: keep some frequencies, drop the rest
Filtering in the frequency domain is three steps: transform, multiply the spectrum by a mask (1 = keep, 0 = remove), transform back. A low-pass mask keeps the centre and gives a blurred image: the smooth shapes and shading. A high-pass mask keeps the outside and gives edges, texture and noise.
The mask edge matters. An ideal mask (a hard circle) makes ripples, or ringing, next to every edge in the result. A hard edge in frequency is a sinc in space, the same ripples you saw for the square, now smeared over your image. A Gaussian mask has no ripples at all, which is exactly why Gaussian blur is the default blur. Butterworth sits in between: order 1 is soft, order 10 is almost ideal.
Set Ideal, low-pass, cutoff around 15, on the text pattern. Look at the halos around the letters. Switch to Gaussian at the same cutoff. Then try high-pass with cutoff 5: you get something very close to an edge map, which is what Sobel and Laplacian also compute.
Kernels are filters too
The convolution theorem connects this to what you already know: convolving an image with a kernel in pixel space is the same as multiplying their spectra. So every kernel you used with cv2.filter2D, GaussianBlur or Sobel is secretly a frequency mask. Here’s the mask for each one.
The box blur’s response has dark rings with bright lobes between them: it lets some fairly high frequencies through, which is why box blurs look slightly “blocky” compared to Gaussian. Sobel x is dark along a vertical line through the centre, so it kills every wave that doesn’t vary left-to-right, and it is also dark at the very centre, so flat areas become zero. It’s an oriented band-pass. The Laplacian is a ring that rises with frequency: a pure high-pass with no orientation. Motion blur zeroes whole columns of frequencies, which is why simple deblurring has to divide by numbers near zero and blows up noise.
Practical consequence: direct convolution costs about k² operations per pixel, the FFT route costs about log(N) per pixel no matter how big the kernel is. OpenCV’s filter2D switches to a DFT-based method on its own for kernels around 11×11 and larger.
Hybrid images: low frequencies from one, high from another
Your eye’s sensitivity to frequency depends on viewing distance. Up close you resolve fine detail, from far away only the coarse shapes survive. So take the low frequencies of image A and add the high frequencies of image B: up close you see B, from across the room you see A. This uses two images, but each one still gets its own transform.
The sum, shown at decreasing size
The default pair is a smile (A) and a frown (B). Squint, or lean back from the screen. Then raise A’s cutoff until the smile shows through even at full size: the gap between the two cutoffs is what makes the illusion work.
Magnitude or phase: which one holds the picture?
Spectrum pictures always show magnitude, so it’s tempting to think that’s where the image lives. Swap them between two images and find out.
The result follows the phase. Magnitude says how much of each wave there is; phase says where the crests line up, and edges are exactly the places where many waves line up at once. Phase-only reconstruction gives you a crude edge drawing, magnitude-only gives a blob. Two practical consequences: phase correlation (in the use-case table below) aligns images using phase alone, and when a network or codec damages phase you get structural artefacts, while damaged magnitude mostly changes contrast and texture.
Removing periodic noise with a notch filter
Some noise is a pattern: scan-line banding, electrical interference, halftone dots from a printed photo, moiré from a screen. In pixel space it covers everything, but in frequency space it collapses to a couple of bright spikes, and you can delete them without touching the rest of the picture. No spatial filter can do that as cleanly.
Click one spike: its mirror twin gets notched too, because removing only one would leave a complex-valued image. Try a large notch radius and see the picture itself start to lose detail along the noise direction.
Where it fits in a computer vision pipeline
The Fourier transform is rarely the final step. It’s a change of viewpoint you switch into when a problem is easier to state in terms of “which sizes and orientations of pattern” than in terms of “which pixels”, and then switch back. It shows up at nearly every stage.
| Use case | Why frequency space helps | In OpenCV |
|---|---|---|
| Blur / focus detection | A blurry frame has little energy far from the centre. One number tells you whether to keep the frame, before you spend GPU time on it. | cv2.dft + a radius mask |
| Image registration, video stabilisation | A shift in space only changes phase. Normalising the cross-power spectrum and transforming back gives a sharp peak at the shift, with sub-pixel precision, in one shot. | cv2.phaseCorrelate |
| Periodic noise removal | Repeating noise concentrates into a few spikes that a notch removes cleanly. | cv2.dft, mask, cv2.idft |
| Fast large-kernel filtering, template matching | Convolution becomes multiplication; cost stops depending on kernel size. | filter2D and matchTemplate use the DFT internally for big inputs |
| Deblurring | If you know the blur kernel, divide by its spectrum, with regularisation where it’s near zero (Wiener filter). | Built from cv2.dft |
| Anti-aliasing | Downsampling folds frequencies above the new Nyquist limit back in as false patterns. Low-pass first. This is why pyrDown blurs before it drops pixels. | cv2.pyrDown, INTER_AREA |
| Compression | Most energy is in low frequencies, so coarsely quantising the high ones is barely visible. JPEG does this per 8×8 block with the DCT, a close cousin of the DFT. | cv2.dct, cv2.imencode |
| Deep learning | Domain adaptation by swapping low-frequency magnitude between synthetic and real images (Fourier Domain Adaptation, useful for sim-to-real); detecting generated images from upsampling artefacts that show up as spectral peaks; FFT-based token mixing (FNet, global filter networks); Fourier neural operators. | Usually torch.fft |
Why bother at all, when you could do most of these in pixel space? Three reasons. Some operations are only simple in frequency space: “remove the stripes at 38 cycles” has no short pixel-space description. Some are only fast there: big convolutions and correlations. And some questions are only answerable there: “is this image sharp”, “is there a repeating pattern”, “what got lost when I downsampled”, “why does my model fail on real camera images when it trained on renders”.
The code
Two versions of the same pipeline. The first uses nothing but Python loops for the maths, with three implementations of the same transform so you can feel the cost: the direct formula, the separable version (rows then columns) and a radix-2 FFT. On a 64×64 image they took about 1.5 s, 150 ms and 16 ms here, and they agree to about 10−9. The second is the OpenCV version, with the use cases above as functions.
fourier_from_scratch.py
"""
fourier_from_scratch.py
=======================
2D Fourier transform of ONE image, written with plain Python loops.
No NumPy in the math. cv2 is used only to read/resize the image and
matplotlib only to show the results, so every transform step is visible.
F(u, v) = sum_y sum_x f(y, x) * exp(-2*pi*i * (u*y/M + v*x/N))
f(y, x) is the image (M rows, N cols). F(u, v) is a complex number that says
"how much of the wave with u cycles down the image and v cycles across it is
in this picture" (|F| = amplitude, angle(F) = where the wave's crests sit).
Three ways to compute the same thing, so you can feel the cost difference:
dft2_naive direct double sum O(M^2 * N^2)
dft2_separable 1D DFT on rows, then cols O(M*N*(M+N))
fft2 recursive radix-2 FFT O(M*N*log(M*N))
Run:
python fourier_from_scratch.py --image dog.jpeg --size 64 --cutoff 8
(--size 64 keeps the naive version to a few seconds; it is O(N^4).)
"""
import argparse
import cmath
import math
import time
import cv2 # only for loading + resizing
import matplotlib.pyplot as plt # only for display
# ---------------------------------------------------------------------------
# Image I/O (the only place a library touches pixels)
# ---------------------------------------------------------------------------
def synthetic_image(size):
"""Fallback test image: a bright square plus fine vertical stripes."""
img = [[0.0] * size for _ in range(size)]
for y in range(size):
for x in range(size):
v = 40.0
if size // 4 <= x < 3 * size // 4 and size // 4 <= y < 3 * size // 4:
v = 200.0 # low-frequency block
v += 30.0 * math.cos(2 * math.pi * 12 * x / size) # high-freq stripes
img[y][x] = v
return img
def load_gray(path, size):
img = cv2.imread(path, cv2.IMREAD_GRAYSCALE) if path else None
if img is None:
print(f"[info] could not read {path!r}; using a synthetic image")
return synthetic_image(size)
img = cv2.resize(img, (size, size), interpolation=cv2.INTER_AREA)
return [[float(img[y][x]) for x in range(size)] for y in range(size)]
# ---------------------------------------------------------------------------
# 1. Naive 2D DFT: literally the formula, four nested loops
# ---------------------------------------------------------------------------
def dft2_naive(img, inverse=False):
M, N = len(img), len(img[0])
sign = 1 if inverse else -1
# Precompute the complex exponentials ("twiddle factors") once.
wy = [[cmath.exp(sign * 2j * math.pi * u * y / M) for y in range(M)] for u in range(M)]
wx = [[cmath.exp(sign * 2j * math.pi * v * x / N) for x in range(N)] for v in range(N)]
F = [[0j] * N for _ in range(M)]
for u in range(M):
for v in range(N):
acc = 0j
wxv = wx[v]
for y in range(M):
row = img[y]
wyu = wy[u][y]
for x in range(N):
acc += row[x] * wyu * wxv[x]
F[u][v] = acc / (M * N) if inverse else acc
return F
# ---------------------------------------------------------------------------
# 2. Separable 2D DFT: the 2D exponential factors into (rows) x (cols),
# so do a 1D DFT on every row, then a 1D DFT on every column.
# ---------------------------------------------------------------------------
def dft1d(seq, inverse=False):
n = len(seq)
sign = 1 if inverse else -1
out = [0j] * n
for k in range(n):
acc = 0j
for t in range(n):
acc += seq[t] * cmath.exp(sign * 2j * math.pi * k * t / n)
out[k] = acc / n if inverse else acc
return out
def transpose(a):
return [list(col) for col in zip(*a)]
def dft2_separable(img, inverse=False, transform_1d=dft1d):
rows = [transform_1d(r, inverse) for r in img] # along x
cols = [transform_1d(c, inverse) for c in transpose(rows)] # along y
return transpose(cols)
# ---------------------------------------------------------------------------
# 3. Radix-2 Cooley-Tukey FFT (length must be a power of two)
# Split into even/odd samples, transform each half, combine with twiddles.
# ---------------------------------------------------------------------------
def _fft1d_rec(seq, sign):
n = len(seq)
if n == 1:
return [complex(seq[0])]
even = _fft1d_rec(seq[0::2], sign)
odd = _fft1d_rec(seq[1::2], sign)
out = [0j] * n
for k in range(n // 2):
t = cmath.exp(sign * 2j * math.pi * k / n) * odd[k]
out[k] = even[k] + t
out[k + n // 2] = even[k] - t
return out
def fft1d(seq, inverse=False):
n = len(seq)
assert n & (n - 1) == 0, "FFT length must be a power of two"
out = _fft1d_rec(seq, 1 if inverse else -1)
return [v / n for v in out] if inverse else out
def fft2(img, inverse=False):
return dft2_separable(img, inverse, transform_1d=fft1d)
# ---------------------------------------------------------------------------
# Helpers: shift, magnitude, masks, inverse
# ---------------------------------------------------------------------------
def roll2d(a, dy, dx):
M, N = len(a), len(a[0])
out = [[None] * N for _ in range(M)]
for y in range(M):
for x in range(N):
out[(y + dy) % M][(x + dx) % N] = a[y][x]
return out
def fftshift(F):
"""Move the zero-frequency (DC) term from the corner (0,0) to the centre."""
return roll2d(F, len(F) // 2, len(F[0]) // 2)
def ifftshift(F):
return roll2d(F, -(len(F) // 2), -(len(F[0]) // 2))
def log_magnitude(F):
"""log(1 + |F|): the DC term is huge, so log makes the rest visible."""
return [[math.log1p(abs(c)) for c in row] for row in F]
def phase_of(F):
return [[cmath.phase(c) for c in row] for row in F]
def make_mask(M, N, cutoff, kind="lowpass", shape="gaussian", order=2):
"""Mask for a CENTRED spectrum. D = distance from the centre (in cycles)."""
cy, cx = M // 2, N // 2
mask = [[0.0] * N for _ in range(M)]
for y in range(M):
for x in range(N):
d = math.hypot(y - cy, x - cx)
if shape == "ideal":
h = 1.0 if d <= cutoff else 0.0
elif shape == "butterworth":
h = 1.0 / (1.0 + (d / cutoff) ** (2 * order))
else: # gaussian
h = math.exp(-(d * d) / (2.0 * cutoff * cutoff))
mask[y][x] = h if kind == "lowpass" else 1.0 - h
return mask
def multiply(F, mask):
return [[F[y][x] * mask[y][x] for x in range(len(F[0]))] for y in range(len(F))]
def real_part(a):
return [[c.real for c in row] for row in a]
def max_abs_diff(A, B):
return max(abs(A[y][x] - B[y][x]) for y in range(len(A)) for x in range(len(A[0])))
# ---------------------------------------------------------------------------
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--image", default="dog.jpeg")
ap.add_argument("--size", type=int, default=64, help="power of two, e.g. 32/64/128")
ap.add_argument("--cutoff", type=float, default=8.0, help="filter radius in cycles")
ap.add_argument("--skip-naive", action="store_true", help="naive DFT is O(N^4)")
args = ap.parse_args()
img = load_gray(args.image, args.size)
M, N = len(img), len(img[0])
# --- forward transform, three ways ------------------------------------
timings = {}
t = time.perf_counter(); F_fft = fft2(img); timings["fft2"] = time.perf_counter() - t
t = time.perf_counter(); F_sep = dft2_separable(img); timings["separable"] = time.perf_counter() - t
if not args.skip_naive:
t = time.perf_counter(); F_naive = dft2_naive(img); timings["naive"] = time.perf_counter() - t
print(f"naive vs fft max |diff| = {max_abs_diff(F_naive, F_fft):.2e}")
print(f"separable vs fft max |diff| = {max_abs_diff(F_sep, F_fft):.2e}")
for k, v in timings.items():
print(f"{k:>10s}: {v * 1000:9.1f} ms ({M}x{N})")
# Optional sanity check against NumPy (not used in the math above)
try:
import numpy as np
ref = np.fft.fft2(np.array(img))
print(f"fft vs numpy max |diff| = {np.abs(np.array(F_fft) - ref).max():.2e}")
except ImportError:
pass
# DC term = sum of all pixels = M*N*mean brightness
print(f"F[0][0] = {F_fft[0][0].real:.1f} (sum of pixels = {sum(map(sum, img)):.1f})")
# --- filter in the frequency domain ------------------------------------
Fc = fftshift(F_fft) # DC in the middle
lp_mask = make_mask(M, N, args.cutoff, "lowpass", "gaussian")
hp_mask = make_mask(M, N, args.cutoff, "highpass", "gaussian")
low = real_part(fft2(ifftshift(multiply(Fc, lp_mask)), inverse=True))
high = real_part(fft2(ifftshift(multiply(Fc, hp_mask)), inverse=True))
back = real_part(fft2(F_fft, inverse=True))
print(f"round trip error max |img - ifft(fft(img))| = {max_abs_diff(img, back):.2e}")
# --- show ---------------------------------------------------------------
panels = [
(img, "image f(y,x)"),
(log_magnitude(Fc), "log(1+|F|), shifted"),
(phase_of(Fc), "phase of F"),
(lp_mask, f"gaussian low-pass, D0={args.cutoff:g}"),
(low, "low frequencies only"),
(high, "high frequencies only"),
]
fig, axes = plt.subplots(2, 3, figsize=(11, 7))
for ax, (data, title) in zip(axes.ravel(), panels):
ax.imshow(data, cmap="gray")
ax.set_title(title)
ax.axis("off")
fig.tight_layout()
plt.show()
if __name__ == "__main__":
main()
fourier_cv2.py
"""
fourier_cv2.py
==============
The same Fourier pipeline as fourier_from_scratch.py, using OpenCV.
Conventions OpenCV uses (worth memorising):
* cv2.dft(float32_img, flags=cv2.DFT_COMPLEX_OUTPUT) -> array (H, W, 2)
[..., 0] = real part, [..., 1] = imaginary part
* The zero frequency sits at [0, 0]. np.fft.fftshift moves it to the centre.
* cv2.idft(F, flags=cv2.DFT_SCALE | cv2.DFT_REAL_OUTPUT) gives the image
back (DFT_SCALE divides by H*W, DFT_REAL_OUTPUT drops the ~0 imag part).
* cv2.getOptimalDFTSize(n) gives a fast size (products of 2, 3, 5).
Run:
python fourier_cv2.py --image dog.jpeg --cutoff 30
python fourier_cv2.py --image dog.jpeg --image2 cat.jpeg # hybrid + phase swap
"""
import argparse
import cv2
import matplotlib.pyplot as plt
import numpy as np
# ---------------------------------------------------------------------------
# Core transform
# ---------------------------------------------------------------------------
def load_gray(path, size=None):
img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
if img is None:
raise FileNotFoundError(path)
if size:
img = cv2.resize(img, (size, size), interpolation=cv2.INTER_AREA)
return img
def pad_to_optimal(img):
"""Zero-pad to a size cv2.dft handles fastest."""
h, w = img.shape
H, W = cv2.getOptimalDFTSize(h), cv2.getOptimalDFTSize(w)
return cv2.copyMakeBorder(img, 0, H - h, 0, W - w, cv2.BORDER_CONSTANT, value=0)
def dft_shifted(img):
"""Forward DFT, centred. Returns (H, W, 2) float32."""
F = cv2.dft(np.float32(img), flags=cv2.DFT_COMPLEX_OUTPUT)
return np.fft.fftshift(F, axes=(0, 1))
def idft_shifted(F_shift):
"""Inverse of dft_shifted. Returns a float32 image."""
F = np.fft.ifftshift(F_shift, axes=(0, 1))
return cv2.idft(F, flags=cv2.DFT_SCALE | cv2.DFT_REAL_OUTPUT)
def log_magnitude(F_shift):
mag = cv2.magnitude(F_shift[..., 0], F_shift[..., 1])
return np.log1p(mag)
def phase(F_shift):
return cv2.phase(F_shift[..., 0], F_shift[..., 1])
def to_u8(x):
return cv2.normalize(x, None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8)
# ---------------------------------------------------------------------------
# Frequency-domain masks (for a centred spectrum)
# kind : lowpass | highpass | bandpass | bandreject
# shape: ideal | gaussian | butterworth
# cutoff = D0 (radius in cycles per image), width = band width
# ---------------------------------------------------------------------------
def distance_grid(shape):
h, w = shape[:2]
y, x = np.ogrid[:h, :w]
return np.sqrt((y - h // 2) ** 2 + (x - w // 2) ** 2).astype(np.float32)
def make_mask(shape, kind="lowpass", filt="gaussian", cutoff=30.0, width=10.0, order=2):
D = distance_grid(shape)
eps = 1e-6
if kind in ("lowpass", "highpass"):
if filt == "ideal":
H = (D <= cutoff).astype(np.float32)
elif filt == "butterworth":
H = 1.0 / (1.0 + (D / cutoff) ** (2 * order))
else:
H = np.exp(-(D ** 2) / (2.0 * cutoff ** 2))
return H if kind == "lowpass" else 1.0 - H
# band filters: build a band-REJECT, then flip for band-pass
if filt == "ideal":
R = ~((D >= cutoff - width / 2) & (D <= cutoff + width / 2))
R = R.astype(np.float32)
elif filt == "butterworth":
R = 1.0 / (1.0 + ((D * width) / (D ** 2 - cutoff ** 2 + eps)) ** (2 * order))
else:
R = 1.0 - np.exp(-(((D ** 2 - cutoff ** 2) / (D * width + eps)) ** 2))
return R if kind == "bandreject" else 1.0 - R
def apply_mask(F_shift, mask):
return F_shift * mask[..., None] # same mask on real and imag
def filter_image(img, **mask_kw):
F = dft_shifted(img)
mask = make_mask(F.shape, **mask_kw)
return idft_shifted(apply_mask(F, mask)), mask
# ---------------------------------------------------------------------------
# Use cases
# ---------------------------------------------------------------------------
def hybrid_image(img_low, img_high, low_cut=12, high_cut=20):
"""Low frequencies of one image + high frequencies of another.
Up close you see img_high, from far away you see img_low."""
low, _ = filter_image(img_low, kind="lowpass", filt="gaussian", cutoff=low_cut)
high, _ = filter_image(img_high, kind="highpass", filt="gaussian", cutoff=high_cut)
return low + high
def swap_magnitude_phase(a, b):
"""Magnitude of a with phase of b. The result looks like b:
phase carries *where* edges are, magnitude carries *how much* of each wave."""
Fa, Fb = dft_shifted(a), dft_shifted(b)
mag_a = cv2.magnitude(Fa[..., 0], Fa[..., 1])
ph_b = cv2.phase(Fb[..., 0], Fb[..., 1])
re, im = cv2.polarToCart(mag_a, ph_b)
return idft_shifted(np.dstack([re, im]))
def add_periodic_noise(img, fx=30, fy=10, amp=40.0):
h, w = img.shape
y, x = np.mgrid[:h, :w]
noise = amp * np.sin(2 * np.pi * (fx * x / w + fy * y / h))
return np.float32(img) + noise.astype(np.float32)
def notch_filter(img, peaks, radius=4):
"""Remove periodic noise: zero small discs at the noise spikes
(and their mirror images, since a real image has a symmetric spectrum)."""
F = dft_shifted(img)
h, w = img.shape
mask = np.ones((h, w), np.float32)
for (dy, dx) in peaks: # offsets from the centre
for sy, sx in ((dy, dx), (-dy, -dx)):
cv2.circle(mask, (w // 2 + sx, h // 2 + sy), radius, 0, -1)
mask = cv2.GaussianBlur(mask, (0, 0), 1.5) # soft edges, less ringing
return idft_shifted(apply_mask(F, mask)), mask
def find_spikes(img, k=1, ignore_radius=6):
"""Find the k strongest *local* spikes in one half of the spectrum.
Natural images have a smooth, falling spectrum; periodic noise shows up as
isolated bright points, so subtract a blurred copy and pick the outliers."""
lm = log_magnitude(dft_shifted(img))
h, w = lm.shape
resid = lm - cv2.GaussianBlur(lm, (0, 0), 4)
resid[distance_grid(lm.shape) < ignore_radius] = 0 # skip DC region
resid[h // 2 + 1:, :] = 0 # one half (symmetry)
peaks = []
for _ in range(k):
_, _, _, (px, py) = cv2.minMaxLoc(resid)
peaks.append((py - h // 2, px - w // 2))
cv2.circle(resid, (px, py), 5, 0, -1)
return peaks
def high_frequency_ratio(img, cutoff=30):
"""Sharpness score: share of spectral amplitude outside radius `cutoff`
(DC removed by subtracting the mean). Blurry frames score low, which is
how you can auto-reject motion-blurred frames or drive autofocus.
The Hanning window fades the borders to zero: the DFT treats the image as
tiling the plane, so without it the hard seam between the left and right
(and top and bottom) edges adds fake high frequencies, the bright "+"
cross you see through most spectra."""
f = np.float32(img)
win = cv2.createHanningWindow(f.shape[::-1], cv2.CV_32F)
F = dft_shifted((f - f.mean()) * win)
mag = cv2.magnitude(F[..., 0], F[..., 1])
D = distance_grid(mag.shape)
return float(mag[D > cutoff].sum() / (mag.sum() + 1e-9))
def phase_correlation_demo(img, shift=(12.3, -7.6)):
"""Recover a translation between two images in one shot (registration,
video stabilisation). Uses the FFT internally."""
M = np.float32([[1, 0, shift[0]], [0, 1, shift[1]]])
moved = cv2.warpAffine(img, M, img.shape[::-1], borderMode=cv2.BORDER_REFLECT)
win = cv2.createHanningWindow(img.shape[::-1], cv2.CV_32F) # tame edge effects
(dx, dy), response = cv2.phaseCorrelate(np.float32(img), np.float32(moved), win)
return (dx, dy), response
# ---------------------------------------------------------------------------
def show(panels, cols=3, title=None):
rows = int(np.ceil(len(panels) / cols))
fig, axes = plt.subplots(rows, cols, figsize=(4 * cols, 3.8 * rows))
for ax in np.ravel(axes):
ax.axis("off")
for ax, (im, t) in zip(np.ravel(axes), panels):
ax.imshow(im, cmap="gray")
ax.set_title(t)
if title:
fig.suptitle(title)
fig.tight_layout()
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--image", default="dog.jpeg")
ap.add_argument("--image2", default=None, help="second image for hybrid / phase swap")
ap.add_argument("--size", type=int, default=256)
ap.add_argument("--cutoff", type=float, default=30)
args = ap.parse_args()
img = load_gray(args.image, args.size)
# --- 1. transform, and check against NumPy ---------------------------
F = dft_shifted(img)
F_np = np.fft.fftshift(np.fft.fft2(img.astype(np.float64)))
rel = np.abs((F[..., 0] + 1j * F[..., 1]) - F_np).max() / np.abs(F_np).max()
print(f"cv2.dft vs np.fft.fft2 relative max diff: {rel:.2e}")
back = idft_shifted(F)
print(f"round trip max error: {np.abs(back - img).max():.2e}")
print(f"optimal DFT size for 300x401: {pad_to_optimal(np.zeros((300, 401), np.uint8)).shape}")
show([
(img, "image"),
(log_magnitude(F), "log(1+|F|) centred"),
(phase(F), "phase"),
], title="One image -> one spectrum")
# --- 2. low / high / band filters ------------------------------------
panels = []
for kind in ("lowpass", "highpass", "bandpass"):
for filt in ("ideal", "gaussian"):
out, mask = filter_image(img, kind=kind, filt=filt, cutoff=args.cutoff, width=20)
panels += [(mask, f"{filt} {kind} mask"), (out, f"{filt} {kind} result")]
show(panels, cols=4, title="Filtering = multiply the spectrum by a mask")
# --- 3. periodic noise removal with a notch ---------------------------
noisy = add_periodic_noise(img, fx=30, fy=10, amp=40)
peaks = find_spikes(noisy, k=1)
print(f"noise spike found at offset {peaks[0]} (expected (-10, -30), the mirror of (10, 30))")
clean, notch = notch_filter(noisy, peaks)
show([
(noisy, "image + periodic noise"),
(log_magnitude(dft_shifted(noisy)), "spectrum: two bright spikes"),
(clean, "after notch filter"),
], title="Periodic noise removal")
# --- 4. sharpness score ------------------------------------------------
for s in (0, 2, 5):
test = cv2.GaussianBlur(np.float32(img), (0, 0), s) if s else img
print(f"blur sigma={s}: high-frequency energy ratio = {high_frequency_ratio(test):.4f}")
# --- 5. registration by phase correlation -----------------------------
(dx, dy), resp = phase_correlation_demo(img)
print(f"phaseCorrelate recovered shift dx={dx:.2f}, dy={dy:.2f} (true 12.30, -7.60)")
# --- 6. two-image experiments -----------------------------------------
img2 = load_gray(args.image2, args.size) if args.image2 else cv2.flip(img, 1)
show([
(hybrid_image(img, img2), "hybrid: low(img) + high(img2)"),
(cv2.resize(to_u8(hybrid_image(img, img2)), (64, 64)), "same, viewed small"),
(swap_magnitude_phase(img, img2), "|F(img)| + phase(img2)"),
], title="Experiments that use two images")
plt.show()
if __name__ == "__main__":
main()
The OpenCV conventions that trip people up
cv2.dft needs float32 input and returns an (H, W, 2) array, real and imaginary parts in the last axis, unlike NumPy’s complex array. Zero frequency is at [0, 0], so call np.fft.fftshift(F, axes=(0, 1)) before you look at it or build a centred mask, and ifftshift before going back. Use cv2.idft(F, flags=cv2.DFT_SCALE | cv2.DFT_REAL_OUTPUT) or you’ll get values H×W times too large. And pad with cv2.getOptimalDFTSize when speed matters.