Inside apply_ft, one matrix at a time
Your function runs five lines of OpenCV on an 853×853 photo. Here the same five lines run on an 8×8 image small enough to print every number, so you can follow each pixel from the image into the spectrum and back.
dft = cv2.dft(np.float32(image), flags=cv2.DFT_COMPLEX_OUTPUT)steps 2–5
6dft_shift = np.fft.fftshift(dft)step 6
7fshift = dft_shift * maskstep 7
6f_ishift = np.fft.ifftshift(fshift)step 6, undone
8image_back = cv2.idft(f_ishift, flags=cv2.DFT_SCALE | cv2.DFT_REAL_OUTPUT)step 8
- The tiny imageAn 8×8 matrix you can edit, as numbers and as 3D bars
- One row, by handThe 1D DFT as a table of multiply-and-add
- One spectrum cellClick any F(u, v) and see the exact sum that made it
- Rows, then columnsWhy a 2D transform is two passes of 1D
- What cv2.dft returnsThe (H, W, 2) array and its NumPy twin
- fftshift and the swapQuadrants, and what goes wrong without
axes=(0, 1) - The mask and its radiusDistance matrix, square vs circle vs Gaussian
- Back with cv2.idftWhat DFT_SCALE and DFT_REAL_OUTPUT each do
- Low, high and the 127Why the high-pass has negatives and what the offset is for
- Function aliasesThe same operations in OpenCV, NumPy and PyTorch
- Where else it’s usedEdges, tracking, matching, registration, deep learning
image = cv2.imread(path, 0) # (8, 8)The tiny image
An image is just a matrix of brightness values: row y goes down, column x goes across, 0 is black and 255 is white. Pick a pattern, or click cells to paint your own. Each click brightens a cell by one step.
F[k] = Σ_n f[n] · e^(−2πi·kn/8)One row, by hand
Start in 1D with one row of 8 numbers. The DFT asks, for each frequency k, how strongly does this row match a wave that completes k cycles across it?
The exponential is just a compact way to carry two waves at once, using Euler’s formula \( e^{-i\theta} = \cos\theta - i\sin\theta \). The cosine part measures how much of the wave lines up with crests at n = 0; the sine part measures the part shifted by a quarter cycle. Each is a dot product: multiply element by element, then add.
Try k = 0: the cosine is all ones and the sine all zeros, so F[0] is just the sum of the row. Then notice F[8 − k] is the complex conjugate of F[k]: same real part, opposite imaginary part. Frequencies 5, 6 and 7 are really −3, −2 and −1. For a real image they’re mirror copies, which is why every spectrum is symmetric.
F[u, v] = Σ_y Σ_x f[y, x] · e^(−iθ)One spectrum cell, every multiplication
In 2D each spectrum cell F(u, v) compares the whole image with one striped pattern: u cycles down, v cycles across.
Click any cell of the spectrum to see the cosine and sine patterns it uses, the 64 products, and their sums.
That’s the whole forward transform: 64 cells, each one a sum of 64 products, so 64 × 64 = 4096 multiply-adds for an 8×8 image. For your 853×853 photo the direct formula would need about 5 × 1011. The FFT gets the identical numbers with far fewer by reusing shared work, and it’s what cv2.dft runs under the hood.
F = DFT_y( DFT_x( f ) )Rows, then columns
The 2D exponential splits into a horizontal part times a vertical part, so the 2D DFT is a 1D DFT on every row followed by a 1D DFT on every column of the result:
This is the dft2_separable function in your from-scratch script. It’s also why the cost drops from about N⁴ to N³ before the FFT even gets involved.
dft = cv2.dft(np.float32(image), flags=cv2.DFT_COMPLEX_OUTPUT)What cv2.dft actually returns
NumPy stores the spectrum as one complex array of shape (8, 8). OpenCV has no complex dtype, so DFT_COMPLEX_OUTPUT gives a float32 array of shape (8, 8, 2): two stacked 8×8 matrices, channel 0 for the real parts and channel 1 for the imaginary parts.
dft = cv2.dft(np.float32(img), flags=cv2.DFT_COMPLEX_OUTPUT) # (8, 8, 2) float32 Fnp = np.fft.fft2(img) # (8, 8) complex128 np.allclose(dft[..., 0] + 1j * dft[..., 1], Fnp) # True mag = cv2.magnitude(dft[..., 0], dft[..., 1]) # = np.abs(Fnp) phase = cv2.phase(dft[..., 0], dft[..., 1]) # = np.angle(Fnp) wrapped to [0, 2π)
The top-left cell, F(0, 0), is always the largest: it’s the sum of all 64 pixels, with an imaginary part of zero. Look for the mirror pairs too: Re F(u, v) = Re F(−u, −v) and Im F(u, v) = −Im F(−u, −v). The imaginary layer is antisymmetric, which is what lets the inverse come back purely real.
dft_shift = np.fft.fftshift(dft)fftshift, and what gets swapped
cv2.dft puts zero frequency in the top-left corner, and the negative frequencies at the far end of each axis. Indices 5, 6 and 7 mean −3, −2 and −1. fftshift rolls each axis by half its length so zero frequency sits in the middle, with negatives above and to the left. That’s purely a rearrangement: no value changes, and nothing is computed.
The swap: fftshift without axes=(0, 1)
np.fft.fftshift(dft) with no axes argument shifts every axis, including the last one, the size-2 channel axis. Rolling an axis of length 2 by 1 swaps its two entries. So channel 0 ends up holding the imaginary parts, and channel 1 the real parts.
In your function the swap is harmless by luck: the mask multiplies both channels identically, and ifftshift without axes swaps them back. It stops being harmless the moment you treat the channels differently, for example by calling cv2.magnitude(dft_shift[..., 0], dft_shift[..., 1]) (fine, since magnitude doesn’t care about the order), cv2.phase(...) (wrong), or building a complex number from them (wrong, it’s conjugated and rotated).
fshift = dft_shift * maskThe mask and its radius
After the shift, distance from the centre is frequency. The distance matrix D holds, for every cell, how many cycles per image that cell’s wave has. A mask is just a rule turning D into a keep-weight between 0 and 1, and filtering is an element-by-element multiply:
Reading the radius
A wave with D cycles across an image of width N has a wavelength of N / D pixels. So radius r keeps everything with wavelength longer than about N / r and removes finer detail. Here N = 8, so r = 2 keeps patterns 4 pixels or larger. On your 853-pixel photo, r = 40 keeps detail coarser than about 21 pixels.
A bigger radius keeps more frequencies, which means less blur. The comment in your code has this backwards.
image_back = cv2.idft(f_ishift, flags=cv2.DFT_SCALE | cv2.DFT_REAL_OUTPUT)Back to pixels with cv2.idft
The inverse uses the same formula with the sign of the exponent flipped, plus a division by the number of pixels:
Each output pixel is a weighted sum of all the surviving waves. The two flags control two parts of that formula. DFT_SCALE is the 1/64. DFT_REAL_OUTPUT returns only the real part: if the mask is symmetric, the imaginary part is zero up to rounding, because mirror pairs cancel.
high = image − low # shown as high + 127Low, high and the 127
The high-pass is what the low-pass took away: high = f − low. Wherever a pixel is brighter than its blurred neighbourhood, the difference is positive. Where it’s darker, the difference is negative. Blurring keeps the average brightness, so these signed values average out to zero.
A uint8 image can’t show −60. Adding 127 moves zero to mid-grey, so “darker than its surroundings” becomes darker than grey and “brighter” becomes lighter. That’s a display convention only. When you combine, the low-pass of the other image already supplies the brightness, so the high-pass should go in signed: low_A + high_B, or low_A + (shown_high_B − 127) if you stored the offset version.
cv2.dft ≈ np.fft.fft2 ≈ torch.fft.fft2Function aliases
The same operations under their three common names. OpenCV is usually fastest on the CPU for float32 images. NumPy is the easiest to read. PyTorch runs on the GPU and can be differentiated through.
| Operation | OpenCV | NumPy | PyTorch |
|---|---|---|---|
| Forward 2D transform | cv2.dft(f32, flags=cv2.DFT_COMPLEX_OUTPUT) → (H, W, 2) | np.fft.fft2(img) → complex (H, W) | torch.fft.fft2(t) |
| Real-input transform, half the spectrum | cv2.dft(f32) (packed format) | np.fft.rfft2(img) → (H, W//2+1) | torch.fft.rfft2(t) |
| Centre zero frequency | np.fft.fftshift(F, axes=(0, 1)) | np.fft.fftshift(F) | torch.fft.fftshift(F, dim=(-2, -1)) |
| Undo the centring | np.fft.ifftshift(F, axes=(0, 1)) | np.fft.ifftshift(F) | torch.fft.ifftshift(F, dim=(-2, -1)) |
| Inverse transform to an image | cv2.idft(F, flags=cv2.DFT_SCALE | cv2.DFT_REAL_OUTPUT) | np.fft.ifft2(F).real | torch.fft.ifft2(F).real |
| Magnitude | cv2.magnitude(re, im) | np.abs(F) | F.abs() |
| Phase | cv2.phase(re, im) | np.angle(F) | F.angle() |
| Rebuild from magnitude and phase | cv2.polarToCart(mag, ph) | mag * np.exp(1j * ph) | torch.polar(mag, ph) |
| Multiply two spectra | cv2.mulSpectrums(A, B, 0) (conjB=True for correlation) | A * B, A * np.conj(B) | A * B |
| Fast transform size | cv2.getOptimalDFTSize(n) | scipy.fft.next_fast_len(n) | (pad manually) |
| Cosine transform (JPEG’s) | cv2.dct(f32), cv2.idct | scipy.fft.dctn | (build from fft) |
| Edge-tapering window | cv2.createHanningWindow((W, H), cv2.CV_32F) | np.outer(np.hanning(H), np.hanning(W)) | torch.hann_window |
The OpenCV window is the square root of the outer product of 1D Hann windows. The NumPy line above is the plain outer product, close but not identical.
for task in (edges, tracking, matching, registration, …):Where else these functions show up
| Task | What the Fourier view does there | In practice |
|---|---|---|
| Edge detection | Edges are high frequencies. Sobel and Laplacian are fixed high-pass and band-pass masks; a frequency-domain high-pass is the same idea with a cutoff you choose. Canny blurs first, a low-pass, so noise doesn’t become fake edges. | cv2.Sobel, cv2.Laplacian, cv2.Canny; Fourier masks when you need a specific cutoff |
| Object tracking | Correlation-filter trackers learn a filter that peaks on the target, solved and applied as an element-wise division and multiplication of spectra, so each frame costs only a few FFTs. | MOSSE and KCF trackers in opencv-contrib |
| Template matching | Sliding a template over an image is a correlation, which becomes a multiply of spectra. | cv2.matchTemplate switches to the DFT for large inputs |
| Registration, stabilisation | A shift between frames only changes phase. Normalise the cross-power spectrum and transform back to get a sharp peak at the offset. | cv2.phaseCorrelate |
| Large-kernel filtering | Convolution becomes multiplication, so the cost no longer grows with kernel size. | cv2.filter2D uses the DFT for kernels around 11×11 and up |
| Object detection networks | CNN first layers learn edge- and stripe-like filters, close to Gabor patterns, which are band-pass filters. FFT convolution is one of the algorithms cuDNN can pick. Fourier features and frequency-domain augmentation are used to make detectors robust to blur and to domain shift. | Mostly inside the framework, via torch.fft |
| Quality checks | Measure how much energy sits in high frequencies to score focus, or to reject motion-blurred frames. | A radius mask on cv2.dft output, or cv2.Laplacian(img, cv2.CV_64F).var() |