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.

  1. The tiny imageAn 8×8 matrix you can edit, as numbers and as 3D bars
  2. One row, by handThe 1D DFT as a table of multiply-and-add
  3. One spectrum cellClick any F(u, v) and see the exact sum that made it
  4. Rows, then columnsWhy a 2D transform is two passes of 1D
  5. What cv2.dft returnsThe (H, W, 2) array and its NumPy twin
  6. fftshift and the swapQuadrants, and what goes wrong without axes=(0, 1)
  7. The mask and its radiusDistance matrix, square vs circle vs Gaussian
  8. Back with cv2.idftWhat DFT_SCALE and DFT_REAL_OUTPUT each do
  9. Low, high and the 127Why the high-pass has negatives and what the offset is for
  10. Function aliasesThe same operations in OpenCV, NumPy and PyTorch
  11. 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.

Pattern
f(y, x), the image. Click to paint.
Same matrix as height. Drag to rotate.
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?

\[ F[k] \;=\; \sum_{n=0}^{7} f[n]\, e^{-2\pi i\,kn/8} \;=\; \underbrace{\sum_{n} f[n]\cos\!\Big(\tfrac{2\pi kn}{8}\Big)}_{\text{real part}} \;-\; i\,\underbrace{\sum_{n} f[n]\sin\!\Big(\tfrac{2\pi kn}{8}\Big)}_{\text{minus the imaginary part}} \]

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.

The row (bars) and the cosine it’s compared with (line).

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.

\[ F(u,v) \;=\; \sum_{y=0}^{7}\sum_{x=0}^{7} f(y,x)\, e^{-2\pi i\left(\frac{uy}{8}+\frac{vx}{8}\right)}, \qquad \theta = 2\pi\Big(\tfrac{uy}{8}+\tfrac{vx}{8}\Big) \]

Click any cell of the spectrum to see the cosine and sine patterns it uses, the 64 products, and their sums.

|F(u, v)|, unshifted, as cv2.dft returns it. Click a cell.
cos θ for this (u, v)
sin θ for this (u, v)
f · cos θ, element by element
−f · sin θ, element by element
negativepositivestronger colour = larger magnitude

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:

\[ F(u,v) \;=\; \sum_{y} e^{-2\pi i\,uy/8}\;\underbrace{\sum_{x} f(y,x)\,e^{-2\pi i\,vx/8}}_{\text{1D DFT of row } y} \]
f
→
Row DFT, real part (each row transformed alone)
→
Then column DFT, real part = Re F

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[:, :, 0] = Re F
dft[:, :, 1] = Im F
The (8, 8, 2) array as two stacked layers. Drag to rotate.
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.

\[ F_{\text{shift}}[a,b] \;=\; F\big[(a-4) \bmod 8,\; (b-4) \bmod 8\big] \]
Before: frequency (u, v) stored at each index
→
After fftshift: the four quadrants trade places diagonally
log |F|, unshifted
→
log |F|, shifted: the big value moves to the centre

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.

Call
dft_shift[:, :, 0]
dft_shift[:, :, 1]

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 * mask

The 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:

\[ D(a,b)=\sqrt{(a-4)^2+(b-4)^2}, \qquad G(a,b) = H(a,b)\,F_{\text{shift}}(a,b) \]
\[ H_{\text{ideal}} = \begin{cases}1 & D\le r\\ 0 & D>r\end{cases} \qquad H_{\text{Gaussian}} = e^{-D^2/(2r^2)} \qquad H_{\text{your square}} = \mathbb{1}\big[\,|a-4|
Mask
D, distance from the centre in cycles per image
→
H, the mask
×
|F_shift|
=
|G|, what survives
log |F_shift| as bars, coloured by the mask: bright = kept, dark = removed. Drag to rotate.

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:

\[ g(y,x) \;=\; \frac{1}{8\cdot 8}\sum_{u}\sum_{v} G(u,v)\, e^{+2\pi i\left(\frac{uy}{8}+\frac{vx}{8}\right)} \]

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.

Flags
f, the original
Output
Output channel 1 (imaginary)
The low-pass result as bars. Drag to rotate.

high = image − low # shown as high + 127

Low, 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.

\[ f_{\text{high}} = f - f_{\text{low}}, \qquad \frac{1}{64}\sum f_{\text{high}} = \bar f - \bar f_{\text{low}} \approx 0 \]
f
−
low (from step 8)
=
high, signed: blue below zero, orange above
+127
high + 127, ready to display as an image

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.fft2

Function 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.

OperationOpenCVNumPyPyTorch
Forward 2D transformcv2.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 spectrumcv2.dft(f32) (packed format)np.fft.rfft2(img) → (H, W//2+1)torch.fft.rfft2(t)
Centre zero frequencynp.fft.fftshift(F, axes=(0, 1))np.fft.fftshift(F)torch.fft.fftshift(F, dim=(-2, -1))
Undo the centringnp.fft.ifftshift(F, axes=(0, 1))np.fft.ifftshift(F)torch.fft.ifftshift(F, dim=(-2, -1))
Inverse transform to an imagecv2.idft(F, flags=cv2.DFT_SCALE | cv2.DFT_REAL_OUTPUT)np.fft.ifft2(F).realtorch.fft.ifft2(F).real
Magnitudecv2.magnitude(re, im)np.abs(F)F.abs()
Phasecv2.phase(re, im)np.angle(F)F.angle()
Rebuild from magnitude and phasecv2.polarToCart(mag, ph)mag * np.exp(1j * ph)torch.polar(mag, ph)
Multiply two spectracv2.mulSpectrums(A, B, 0) (conjB=True for correlation)A * B, A * np.conj(B)A * B
Fast transform sizecv2.getOptimalDFTSize(n)scipy.fft.next_fast_len(n)(pad manually)
Cosine transform (JPEG’s)cv2.dct(f32), cv2.idctscipy.fft.dctn(build from fft)
Edge-tapering windowcv2.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

TaskWhat the Fourier view does thereIn practice
Edge detectionEdges 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 trackingCorrelation-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 matchingSliding a template over an image is a correlation, which becomes a multiply of spectra.cv2.matchTemplate switches to the DFT for large inputs
Registration, stabilisationA 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 filteringConvolution 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 networksCNN 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 checksMeasure 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()