Wavelets for images: 2-D, by hand and in code
The 2-D wavelet transform that courses skip. One 2 × 2 block by hand, and why it is a tiny Fourier transform; why there are exactly three detail bands; a worked 4 × 4 example and a live 8 × 8 one; the band names settled; pyramid and standard decompositions; compression against the 8 × 8 DCT and denoising against an oracle blur, reported honestly; NumPy and PyTorch code checked against PyWavelets; what separable wavelets get wrong about direction and shifts; and where wavelets live in modern machine learning. Part 4 of Seeing in frequencies.
Contents
- Notation and conventions
- 1. One 2 × 2 block, by hand
- 2. Why exactly three detail bands
- 3. The 8 × 8 patch, by hand and live
- 4. Names and layouts, settled
- 5. More levels: two different 2-D transforms
- 6. Compression
- 7. Denoising images
- 8. Implementation, for real
- One level in NumPy
- On a GPU: one strided convolution
- What the library returns
- Traps
- 9. What separable 2-D wavelets get wrong
- Direction
- Shifts
- The fixes
- 10. Where to use them
- 11. Wavelets in modern machine learning
- A layer that downsamples without losing anything
- Large receptive fields from small kernels
- Fixed features: the scattering transform
- Neural operators: learning maps between functions
- Learned compression that keeps the wavelet structure
- Beyond images: graphs
- Self-check
- References
Seeing in frequencies, part 4 of 4. Fourier analysis → the discrete Fourier world → wavelets → wavelets for images.
Below is an 8 × 8 patch with a vertical edge, bright on the left and dark on the right, after one level of the 2-D Haar transform. All 48 detail numbers are zero.
The transform is not broken. The edge sits exactly on the boundary between two columns of 2 × 2 blocks, and one level of Haar only compares pixels inside a block. Press shift right: the edge moves one pixel into the blocks, and a column of four numbers lights up. Or go to level 2: the coarser blocks straddle the edge, and it appears there. This one figure already shows two facts that matter in practice. A single level can be blind to a feature, and moving the image by one pixel changes the coefficients completely.
Part 3 built wavelets in 1-D and promised images. Most courses stop at “apply it to the rows, then to the columns”. This post does the rest:
- Section 1 computes one 2 × 2 block by hand and shows that it is a tiny Fourier transform.
- Section 2 proves why there are exactly three detail bands.
- Section 3 works a 4 × 4 example by hand and an 8 × 8 one live.
- Section 4 settles the names of the bands, which disagree from book to book.
- Section 5 shows that “the 2-D wavelet transform” is really two different transforms.
- Sections 6 and 7 compress and denoise my sketches, and report where wavelets win and where they do not.
- Section 8 implements everything in NumPy and PyTorch, checked against PyWavelets, and lists the traps.
- Section 9 covers what separable wavelets get wrong (direction and shifts) and the transforms that fix it.
- Section 10 says where to use them, and Section 11 shows where they live in modern machine learning: as layers inside networks, as fixed features, inside neural operators and in learned compression.
Notation and conventions
Everything from Part 3 carries over: the scaling function and wavelet , the low-pass filter and high-pass filter , and the spaces , with larger finer. New here:
| Symbol | Meaning |
|---|---|
| , | horizontal and vertical position |
| pixel in row (counted downward) and column | |
| 2-D approximation space | |
| , , , | one level’s four outputs, computed by hand |
cA, cH, cV, cD | the same four, as PyWavelets names them |
| , | frequency in cycles per pixel |
A horizontal edge is a boundary that runs horizontally, like the horizon; the image changes as you move vertically across it. By hand I use averages and half-differences, and , so the numbers stay in the range of the pixels. PyWavelets uses the orthonormal version, and , which preserves energy. In 2-D the two differ by a factor of 2 per level.
1. One 2 × 2 block, by hand
Take four pixels:
Apply Part 3’s Haar step to each row: the top row becomes its average and its half-difference, and so does the bottom row:
Then apply the same step to each column of the result:
Each of the four numbers answers a question about the block:
- (top-left): the average.
- (top-right): left column minus right column. It is large when the block straddles a vertical edge.
- (bottom-left): top row minus bottom row. It is large at a horizontal edge.
- (bottom-right): one diagonal minus the other, a checkerboard detector.
Example 1 (One block)
For :
The block is brighter at the top (), balanced left to right (), with a little checker (). To go back, add and subtract the four formulas:
Indeed , , and . Four numbers in, four out, nothing lost.
PyWavelets divides by at each step instead of by , so each of its numbers is twice as large: pywt.dwt2([[9, 7], [3, 5]], 'haar') returns cA = 12 and (cH, cV, cD) = (4, 0, 2). Note the order: H comes before V. The factor of 2 per level also explains why approximations get brighter with every level, and why a display has to divide by after levels.
Two facts about this little computation are worth proving. The first holds for every wavelet; the second holds only for Haar.
Proposition 1 (Rows then columns equals columns then rows)
Let be the matrix of one level of a 1-D wavelet transform on samples. One level of the separable 2-D transform of an image is , in whichever order the passes are done. If is orthogonal, so is the 2-D transform, and .
Proof
Step 1. Rows. Transforming a row replaces it by . For all rows at once, .
Step 2. Columns. Transforming a column replaces it by . For all columns at once, .
Step 3. Order. Rows then columns gives ; columns then rows gives . Matrix multiplication is associative, so both equal .
Step 4. Orthogonality. Stack the columns of into one vector: . Then , so energy is preserved and the inverse is .
So the order in which a library runs the two passes never matters. Nor does it matter that some libraries filter both directions at once with 2-D kernels (Section 8).
Proposition 2 (On one block, Haar is the 2 × 2 Fourier transform)
For a block , one level of 2-D Haar with averages is a quarter of its 2-D DFT, laid out the same way: . The orthonormal version is .
Proof
The 2-point DFT matrix is , since , and the 2-D DFT of is (Part 2, Section 5). The averaging Haar step on two samples is , so by the previous proposition one 2-D level is . The orthonormal step is , which gives .
Check it on the block above: np.fft.fft2([[9, 7], [3, 5]]) is . Part 2 promised exactly this. The 2-D Haar transform is a 2 × 2 Fourier transform, done on every block, then again on the averages, at every scale. This is true only for Haar. A longer filter reaches into the neighbouring blocks, so the image no longer splits into independent blocks and the link to the DFT is lost. The idea survives, though: the approximation keeps the lowest frequency of each neighbourhood, and the three details keep the rest.
2. Why exactly three detail bands
In 1-D, one level splits a signal into two halves. In 2-D it gives four quarters, and the reason is one line of algebra.
Definition 1 (Separable 2-D multiresolution)
Given a 1-D multiresolution analysis with scaling function , the 2-D approximation spaces are
For Haar, is exactly what a camera with square pixels of side sees: images that are constant on each pixel. The question is what adds to .
Theorem 1 (One approximation and three details)
Let be the 1-D detail space, so that . Then
and the four pieces are mutually orthogonal. The three detail spaces have orthonormal bases made of shifts and dilations of
namely .
Proof
Step 1. Every piece lies in . Both and are inside , so every product of their functions is a product of functions in .
Step 2. Together the pieces span . A generator of is . Split each factor with the 1-D decomposition, with and , and multiply out:
There is one term in each piece. This is what ” distributes over ” means.
Step 3. The pieces are orthogonal. The inner product of two products factorises (Fubini):
Two different pieces differ in at least one factor, where one function comes from and the other from . Those are orthogonal, so the product is zero.
Step 4. Bases. By the same factorisation, products of orthonormal functions are orthonormal: . They span each piece by Step 2. Finally, , which is the stated formula, because .
Applying the theorem repeatedly gives the whole mosaic: . That is one small approximation, plus three detail bands per level.
The names follow from the products.
- oscillates along and is smooth along , so it matches intensity that changes from left to right: vertical edges (,
cV). - is its transpose: horizontal edges (,
cH). - oscillates along both directions, with four lobes of alternating sign: a checker (,
cD).
Here they are as surfaces. I used the smoother Daubechies-8 because Daubechies-4 is too jagged to read as a surface.
Why three, and not two or four? Counting gives the same answer without any algebra. One level halves the resolution in both directions, so every coarse pixel has fine pixels under it, and four numbers take four numbers to describe: one average and three details. In dimensions, multiplies out into terms, exactly one of which is all , so there are detail bands per level: 7 for a volume.
The general rule is that a multiresolution analysis with dilation matrix needs wavelets (Kovačević and Vetterli, 1992). Doubling both axes has , hence three. The quincunx dilation, which rotates by 45° and scales by , has and needs only one wavelet per level. It is not separable, and the common libraries do not offer it.
Question 1
If there are three detail bands, why does the diagonal band look nearly black in most pictures of the 2-D transform?
Answer
Natural images contain few checker-like structures. Edges and smooth shading excite and more than , which responds only to change along both directions at once. On the Eye with D4, the finest cD holds about a third of the energy of the finest cH. Section 3 shows that even a diagonal edge excites all three bands, not just .
3. The 8 × 8 patch, by hand and live
Example 2 (Two levels on a 4 × 4 image)
Take a 4 × 4 image with a diagonal edge, bright above and dark below:
Level 1. Cut the image into four 2 × 2 blocks and apply the four formulas to each:
- The top-left block is all 8: and .
- The top-right block is : .
- The bottom-left block is the same: .
- The bottom-right block is all 0, so everything is 0.
Each number goes into its quarter, at the position of its block:
Level 2. Apply the same formulas to the averages :
The top-left quarter becomes . As a check, is the mean of the whole image: six pixels of 8, so .
In PyWavelets, level-1 numbers are twice these and level-2 numbers four times these: wavedec2(X, 'haar', level=2) gives cA2 = 12, (cH2, cV2, cD2) = (8, 8, 4), and every level-1 band equal to (checked).
Notice what the diagonal edge did. On a pixel grid it is a staircase, and every block on the stair is a corner, which lights up all three detail bands equally. So cD is not “the diagonal-edge band”. It is the checker band, and diagonal edges spread over all three. Section 9 makes this precise.
Now the same idea on an 8 × 8 patch, live. Step through rows, columns and level 2. Click any output number to see its block and its arithmetic, paint your own image, or pick a preset. Try diagonal to see the staircase effect. Then try checkerboard: it is the one pattern whose detail lives entirely in .
4. Names and layouts, settled
In my experience this is the most common source of bugs in 2-D wavelet code, so here it is once, carefully.
- What each band detects.
cV(left − right) responds to vertical edges,cH(top − bottom) to horizontal edges, andcDto checker-like structure. The letter names the edge, not the direction in which the filter takes differences. - The order of the output.
pywt.dwt2(x, w)returnscA, (cH, cV, cD).wavedec2returns[cA_n, (cH_n, cV_n, cD_n), …, (cH_1, cV_1, cD_1)], coarsest first, and level 1 is the finest, just as in 1-D (Part 3, Section 7). - Where each band is drawn.
pywt.coeffs_to_arrayputscVtop-right andcHbottom-left, as in every figure in this post. - The n-dimensional keys.
pywt.dwtnlabels each band with one letter per axis,afor approximation anddfor detail, axis 0 first. Axis 0 of an image array is the row index, so the first letter describes the vertical direction.'ad'is smooth down the columns and detailed along the rows, which iscV;'da'iscH. - The letters L and H. Many texts write LL, LH, HL and HH, for low-pass and high-pass. Some put the horizontal filter first, others the vertical one, so “LH” is
cHin one source andcVin another. Do not trust the letters. Check what the band detects with a test image. - Signs. PyWavelets’ Haar detail is (first − second)/√2. Other libraries, and other wavelets, may flip the sign of , which negates every detail coefficient (Part 3, Section 7). The magnitudes agree.
The test takes three lines. Put a horizontal edge inside a row of blocks (not on a block boundary, as the opening figure warned), and see which band lights up:
import numpy as np, pywt
x = np.zeros((8, 8)); x[:3] = 1 # bright top three rows: a horizontal edge between rows 2 and 3
cA, (cH, cV, cD) = pywt.dwt2(x, 'haar')
print([round(float(np.abs(b).sum()), 12) for b in (cH, cV, cD)]) # [4.0, 0.0, 0.0]
print(sorted(pywt.dwtn(x, 'haar'))) # ['aa', 'ad', 'da', 'dd']
print(np.allclose(pywt.dwtn(x, 'haar')['da'], cH)) # True: 'da' is cH
5. More levels: two different 2-D transforms
There are two natural ways to continue past one level, and “the 2-D wavelet transform” can mean either.
- The pyramid (or non-standard) decomposition, used in every figure so far: after each level, recurse on the approximation only. This is what
pywt.wavedec2computes. - The standard decomposition: run the complete 1-D transform, all levels, on every row, and then the complete 1-D transform on every column of the result. PyWavelets calls it
pywt.fswavedecn, for “fully separable”.
The names come from Beylkin, Coifman and Rokhlin (1991), who used both forms to compress integral operators; Stollnitz, DeRose and Salesin (1995) explain both for images. Both are orthonormal bases of the same space (Section 1’s proof works for any orthogonal , including the full 1-D transform), but they are different bases:

In the pyramid, every basis image has the same scale in and in : squares. In the standard decomposition the two scales are independent, so long thin rectangles appear, at every pair of scales. The standard form suits images stretched along one axis, and it is what you get by calling a 1-D library function along each axis in turn. The pyramid treats both directions alike at every scale, which suits most natural images, and it is what nearly every library and paper means. If two implementations disagree completely, check that they compute the same decomposition.
6. Compression
Part 3 showed why wavelets make piecewise-smooth signals sparse: vanishing moments cancel the smooth parts, and only coefficients near edges survive. Images are where this pays off. The experiment below is the simplest possible codec: transform, keep the largest of the numbers, set the rest to zero, and invert. Both transforms are orthonormal, so the squared error is exactly the energy of the dropped numbers. The competitor is the 8 × 8 block DCT inside JPEG (Part 2, Section 9).
Measured on three of my sketches, with D8 wavelets against the DCT (PSNR in dB, higher is better; the figure computes the same numbers):
| Keep | Eye | Portrait | Sunset |
|---|---|---|---|
| 2% | 28.9 vs 26.9 | 23.7 vs 22.1 | 21.6 vs 19.9 |
| 5% | 31.7 vs 31.1 | 26.2 vs 25.6 | 25.0 vs 25.0 |
| 10% | 34.7 vs 34.4 | 29.1 vs 28.7 | 28.6 vs 28.9 |
What the numbers say:
- At small budgets the wavelets win clearly, by 1.6 to 2.0 dB at 2%. The DCT has to spend its numbers block by block, so the 8 × 8 grid shows. The wavelet image has no fixed grid: its errors are smudges of many sizes around the edges. Zoom into the figure to compare.
- With budget to spare, the gap closes. On the Sunset, which is mostly oscillating texture (the waves), the DCT’s cosines catch up and then win slightly.
- Haar is the weakest wavelet at every budget. On the Eye at 2% it gives 27.8 dB, against 28.4 for D4 and 28.9 for D8: with one vanishing moment, smooth shading costs it more coefficients.
- This counts numbers, not bits. A real codec must also record which coefficients it kept, and store their values with a finite number of bits. Wavelet coefficients cluster: the large ones sit near edges, at every scale, roughly above one another in the tree of levels. Coding that structure well is most of what makes a wavelet codec good. Examples are Shapiro’s zerotrees (1993), Said and Pearlman’s SPIHT (1996), and EBCOT in JPEG 2000 (Taubman, 2000).
JPEG 2000 turns this idea into a standard.
It uses biorthogonal wavelets (Part 3, Section 12) because they can be symmetric. The CDF 9/7 pair is used for lossy coding. The Le Gall 5/3 pair, computed by integer lifting (Part 3, Section 8), is used for exactly lossless coding. Because the transform is a pyramid, one file holds every resolution: decode only the coarse levels to get a thumbnail. Because the coefficients are coded bit-plane by bit-plane, one file also holds every quality: stop reading early to get a coarser image. JPEG 2000 never replaced JPEG on the web. It is, however, the image format of digital cinema, and it is common in medical imaging and archives.
7. Denoising images
Part 3 proved the universal threshold and found that, on a 1-D signal, hard thresholding beat an ideally tuned blur. Images are harder. Here is the comparison on the Portrait and the Eye, with Gaussian noise of standard deviation (pixel values in ) and D4 wavelets over four levels:
On the Portrait (PSNR in dB; the figure uses a different noise draw, so its numbers can differ by about 0.1):
| Method | σ = 0.05 | σ = 0.1 | σ = 0.2 |
|---|---|---|---|
| noisy | 26.0 | 20.0 | 14.0 |
| oracle blur | 28.4 | 25.1 | 22.5 |
| universal, soft | 22.5 | 21.2 | 20.1 |
| universal, hard | 24.2 | 22.1 | 20.8 |
| BayesShrink | 28.3 | 24.7 | 22.3 |
| BayesShrink + 16 shifts | 29.4 | 25.7 | 22.9 |
On the Eye the pattern is the same: the oracle blur gives 30.7, 28.0 and 25.9 dB, and BayesShrink with 16 shifts gives 31.5, 28.6 and 26.2. Four lessons follow.
- The universal threshold is too harsh for images. At σ = 0.05 its soft version is worse than doing nothing (22.5 dB against 26.0). The threshold is designed so that, with high probability, no pure-noise coefficient survives (Part 3, Section 13). In an image, a vast number of small but real coefficients (the texture of the pencil and the paper) sit below it, and they are removed along with the noise.
- Adapt the threshold to each band. BayesShrink (Chang, Yu and Vetterli, 2000) treats the coefficients of one band as having a Laplacian-like spread and picks the threshold . That is small where a band holds a lot of signal, and large where it holds little. Both quantities are estimated from the data. As in Part 3, comes from the median of the finest diagonal band. And , because a band’s mean square is its signal variance plus the noise variance. This alone gains 2 to 6 dB over the universal threshold here.
- Average over shifts. The decimated transform is not shift-invariant (Part 3, Section 14), so thresholding leaves artefacts that depend on where the image sits on the grid. Cycle spinning (Coifman and Donoho, 1995) shifts the noisy image by every offset in a small range, denoises each copy, shifts it back, and averages. With 16 shifts it adds 0.6 to 1.2 dB.
- Only then do wavelets beat the oracle blur, and only by 0.3 to 1.0 dB, although the blur was given its best width by peeking at the clean image. Low-pass filtering is a strong baseline for images whose energy is mostly at low frequencies. What wavelets add is that edges stay sharp, which PSNR rewards only a little.
These are the classical methods, and they are here for the mechanism, not the leaderboard. Better wavelet-domain denoisers model the dependence between neighbouring coefficients across position and scale, such as the Gaussian scale mixtures of Portilla and colleagues (2003). Non-local methods such as BM3D (Dabov and colleagues, 2007), and trained networks, do better again.
8. Implementation, for real
One level in NumPy
The four formulas of Section 1, applied to whole arrays with strided slicing, are a complete one-level 2-D Haar transform. This is the orthonormal version, matching PyWavelets:
import numpy as np, pywt
x = np.random.default_rng(0).random((256, 256))
a, b = x[0::2, 0::2], x[0::2, 1::2] # top-left and top-right pixel of every 2 x 2 block
c, d = x[1::2, 0::2], x[1::2, 1::2] # bottom-left and bottom-right
A = (a + b + c + d) / 2
H = (a + b - c - d) / 2 # top - bottom: horizontal edges (cH)
V = (a - b + c - d) / 2 # left - right: vertical edges (cV)
D = (a - b - c + d) / 2 # checker (cD)
cA, (cH, cV, cD) = pywt.dwt2(x, 'haar')
print(max(np.abs(p - q).max() for p, q in [(A, cA), (H, cH), (V, cV), (D, cD)])) # 6.7e-16
y = np.empty_like(x) # the inverse: Section 1's formulas, divided by 2
y[0::2, 0::2], y[0::2, 1::2] = (A + H + V + D) / 2, (A + H - V - D) / 2
y[1::2, 0::2], y[1::2, 1::2] = (A - H + V - D) / 2, (A - H - V + D) / 2
print(np.abs(y - x).max()) # 2.2e-16
For more levels, apply the same step to A.
On a GPU: one strided convolution
A convolution with four 2 × 2 kernels and stride 2 is one level of 2-D Haar, for a whole batch of images at once. In PyTorch it matches PyWavelets to . Because the four kernels are orthonormal, conv_transpose2d with the same kernels inverts it exactly:
import torch, torch.nn.functional as F
k = torch.tensor([[[1, 1], [1, 1]], # cA
[[1, 1], [-1, -1]], # cH: top - bottom
[[1, -1], [1, -1]], # cV: left - right
[[1, -1], [-1, 1]]], # cD: checker
dtype=torch.float64)[:, None] / 2
x = torch.rand(8, 1, 256, 256, dtype=torch.float64) # a batch of 8 grey images
y = F.conv2d(x, k, stride=2) # (8, 4, 128, 128): cA, cH, cV, cD
x_back = F.conv_transpose2d(y, k, stride=2) # the exact inverse
For longer filters, the kernels are outer products of the 1-D filters, and the image must be extended at its borders. Periodic extension by pixels on each side reproduces PyWavelets’ mode='periodization' exactly. I checked D4 and D8; the error is below .
import pywt
def dwt2_torch(x, wavelet): # x: (B, C, H, W) with H, W even
h = torch.tensor(pywt.Wavelet(wavelet).rec_lo, dtype=x.dtype); L = len(h); s = L // 2 - 1
g = torch.stack([(-1) ** n * h[L - 1 - n] for n in range(L)])
k = torch.stack([torch.outer(p, q) for p, q in ((h, h), (g, h), (h, g), (g, g))])[:, None]
B, C, H, W = x.shape
x = x.reshape(B * C, 1, H, W) # every channel separately
if s: x = F.pad(x, (s, s, s, s), mode='circular')
return F.conv2d(x, k, stride=2).reshape(B, C, 4, H // 2, W // 2) # cA, cH, cV, cD
The first index of each kernel runs along . So torch.outer(g, h) is high-pass down the columns and low-pass along the rows, which is cH. The inverse is the transpose, because the transform is orthogonal: apply conv_transpose2d, then fold the padded border back onto the opposite side. The libraries pytorch_wavelets and ptwt provide both directions with gradients and several boundary modes, and pytorch_wavelets also has the dual-tree transform of Section 9.
What the library returns
img = np.random.default_rng(1).random((64, 64))
c = pywt.wavedec2(img, 'db2', level=2, mode='periodization')
# c[0]: cA2, 16 x 16; c[1]: (cH2, cV2, cD2), each 16 x 16; c[2]: (cH1, cV1, cD1), each 32 x 32
arr, slices = pywt.coeffs_to_array(c) # the mosaic, 64 x 64
rec = pywt.waverec2(c, 'db2', mode='periodization') # back again, to about 1e-15
Traps
- Band names.
dwt2returns H before V;cVis left − right; and “LH” means different bands in different books (Section 4). Test with an image of horizontal stripes. - Edges on the grid. One level of Haar cannot see an edge that lies on a block boundary (the first figure). Longer wavelets and coarser levels can. Never conclude “no edge here” from one level of Haar.
- Display gain. Each orthonormal level multiplies the approximation by 2 in 2-D, so after three levels a constant image of 1 has
cA3 = 8. Divide the approximation by before showing it. Scale each detail band separately too, since they are small and signed, or they will all look black. - Boundary modes. The default,
mode='symmetric', returns more coefficients than there are pixels. For a 256 × 256 image with D8, level 1 gives bands of 131 × 131, not 128 × 128. Useperiodizationfor exact halving, but remember that it wraps the right border onto the left, which creates a false edge if the two sides differ. This is the same cause as the ”+” in image spectra (Part 2, Section 7). - Odd sizes. With periodisation, a 255 × 255 image gives 128 × 128 bands. For several levels, pad to a multiple of .
- How many levels.
pywt.dwtn_max_level((256, 256), 'db4')is 5, while Haar allows 8. Beyond the maximum, boundary effects dominate. - Comparing libraries. Two correct implementations can differ by a shift of the coefficients (Part 3, Section 7) and by the sign of the details. Compare reconstructions or magnitudes.
- Precision. A round trip through five levels of D8 is exact to in float64, and to in float32, the precision of most GPU pipelines. Make the reconstruction error a unit test.
- Colour. Transform each channel separately, or first convert to a luminance–chrominance space, as JPEG and JPEG 2000 do; the eye tolerates more loss in the chrominance.
- Thresholding the approximation. Threshold the details only. The approximation holds the image’s mean and its slow shading.
- Pyramid or standard.
wavedec2gives the pyramid. Applying a full 1-D transform along each axis gives the standard decomposition (fswavedecn). Both have the same number of coefficients but different bases (Section 5).
9. What separable 2-D wavelets get wrong
Direction
There are three bands for three directions: horizontal, vertical and “diagonal”. But which diagonal? Drag the angle in the figure below. It shows a grating (stripes) of a single frequency, its two frequency dots in the plane, and where one level of the transform puts the grating’s energy.
Select D8. At 45° (/), 93.8% of the energy goes to cD. At 135° (\) it is also 93.8%, and every other band agrees to the last digit. A diagonal band built from separable filters cannot tell / from \. The reason takes two lines.
Proposition 3 (Band energies of a grating)
Analyse the grating with one level of the separable transform, and write and . Unless both and are among , and cycles per pixel, its energy splits as
for every phase . In particular, all four shares are unchanged by : the mirror image of a grating has the same band energies.
Proof
Step 1. Filtering. A grating is the sum of two complex exponentials, at . A separable filter multiplies an exponential by , because exponentials are eigenfunctions of every shift-invariant operator (Part 1, Section 5). The filters are real, so , and both exponentials are scaled by the same . The output is again a grating, with its amplitude multiplied by that factor.
Step 2. Keeping every second row and column. The filtered grating has mean square . Keeping one sample in four leaves a grating of frequency , whose mean square is still , as long as its square, which contains , averages out. That fails only when and are both multiples of , which are the excluded frequencies. The kept samples are a quarter of the total, so the band’s share of the energy is .
Step 3. The four bands take , , and , with acting along : cH is high-pass along . Since and are even functions, replacing by changes nothing.
The figure and my checks agree with these formulas to . The excluded case is not academic. My first test used stripes with , exactly on the band boundary, and the share in cD changed from 0% to 50% with the phase of the stripes. It looked like a contradiction until I worked out Step 2.
So the transform loses no information: it is invertible, and the signs of the coefficients differ between / and \. But any feature built from band energies, such as the texture descriptors of classical image analysis, sees one texture where there are two. The shares are also only rough. At 30° and 0.45 cycles per pixel, D8 puts 66% in cH and 33% in cD. The “horizontal” band really means “anything closer to horizontal than to the diagonals”, and the “diagonal” band means “near the diagonals, or at the highest frequencies”.
Shifts
The first figure already showed this: move an edge by one pixel, and the level-1 coefficients change from all zeros to a column of fours. On a whole image the effect partly averages out, but not entirely. Shifting the Eye right by 0 to 8 pixels changes the energy of its coarsest vertical-edge band (D4, three levels) by up to 25%, although the image’s content is the same. The cause is the one from Part 2: every level keeps every second sample, so the bands alias.
The fixes
- The undecimated (stationary) transform. Skip the downsampling and dilate the filters instead (the “à trous” algorithm). It is exactly shift-invariant, but it still has only three orientations. It stores full-size images for levels: 851,968 numbers for four levels of a 256 × 256 image, 13 times the number of pixels.
- Dual-tree complex wavelets (Kingsbury, 2001; Selesnick, Baraniuk and Kingsbury, 2005). Two real wavelet trees are designed so that one wavelet is approximately the Hilbert transform of the other. Then is approximately analytic: its spectrum lives on positive frequencies only. So has its spectrum in one quadrant, and its real part in that quadrant and the opposite one: one diagonal. Its partner, , takes the other two quadrants, which is the other diagonal. With the same trick on the other two bands there are six bands per level, oriented at about ±15°, ±45° and ±75°. Their magnitudes are nearly shift-invariant, and the redundancy is only 4:1 in 2-D.
- The steerable pyramid (Simoncelli and Freeman, 1995). It offers any number of orientations, with filters that can be “steered” to any angle by combining a few fixed ones. It is its own inverse, and it is overcomplete by a factor of about for orientations. It is a workhorse of texture analysis and synthesis.
- Curvelets (Candès and Donoho, 2004) and shearlets (Kutyniok and Labate, 2012). Their elements get thinner faster than they get shorter (width ≈ length²), at many orientations. For images that are smooth apart from smooth curved edges, the squared error of the best -term approximation decays like , against for wavelets and for Fourier. Shearlets use shears instead of rotations, which suits the pixel grid.
10. Where to use them
| Use 2-D wavelets when | Prefer something else when |
|---|---|
| images are piecewise smooth: edges between smooth regions | the content is oscillating texture: local cosines or Fourier |
| you need a compact, invertible, fast representation at every scale | features must be stable under shifts: undecimated, complex or scattering transforms |
| one file must serve many resolutions and qualities | you need many orientations: steerable pyramids, curvelets, shearlets |
The classical uses.
- JPEG 2000, in digital cinema, medical imaging and archives.
- Denoising and image fusion. Fusion merges images of the same scene, focused at different depths or taken by different sensors, by keeping the strongest detail coefficients from each.
- Texture features from subband energies, with the caveat of Section 9.
- Multiscale measures of image quality, such as MS-SSIM (Wang, Simoncelli and Bovik, 2003), which compare images scale by scale.
11. Wavelets in modern machine learning
Everything in this post reappears inside today’s networks. The bridge is Section 8: one level of 2-D Haar is a stride-2 convolution with four fixed kernels. So it drops into any network as a layer, gradients flow through it like through any other convolution, and its inverse is the transposed convolution. In practice a wavelet transform turns up in one of four roles.
A layer that downsamples without losing anything
Start with a fact that is easy to check. 2 × 2 average pooling is the Haar approximation divided by 2: . Pooling is therefore a Haar transform that throws three of its four bands away, and with them all the edges and texture at that scale. A strided convolution keeps every second output of a learned filter: the decimation of Part 2, with its aliasing (Part 2, Section 3). Blurring before subsampling (Zhang, 2019) reduces the aliasing, but still discards the detail.
A Haar layer keeps all four bands, as channels:
import torch, torch.nn as nn, torch.nn.functional as F
class HaarDown(nn.Module):
"""(B, C, H, W) -> (B, 4C, H/2, W/2): cA, cH, cV, cD of every channel. Orthonormal: nothing is lost."""
def __init__(self, channels):
super().__init__()
k = torch.tensor([[[1, 1], [1, 1]], [[1, 1], [-1, -1]],
[[1, -1], [1, -1]], [[1, -1], [-1, 1]]], dtype=torch.float32) / 2
self.register_buffer('k', k[:, None].repeat(channels, 1, 1, 1)) # (4C, 1, 2, 2), fixed
self.c = channels
def forward(self, x):
return F.conv2d(x, self.k, stride=2, groups=self.c)
class HaarUp(HaarDown):
"""The exact inverse: (B, 4C, H/2, W/2) -> (B, C, H, W)."""
def forward(self, y):
return F.conv_transpose2d(y, self.k, stride=2, groups=self.c)
x = torch.randn(2, 3, 64, 64)
down, up = HaarDown(3), HaarUp(3)
y = down(x) # (2, 12, 32, 32)
print(tuple(y.shape), (up(y) - x).abs().max().item()) # (2, 12, 32, 32), about 5e-7 (float32)
print((y.square().sum() / x.square().sum()).item()) # 1.0 up to float32 rounding: energy is preserved
print((F.avg_pool2d(x, 2) - y[:, 0::4] / 2).abs().max().item()) # 0.0: average pooling is cA / 2
There is a second way to see this layer. Rearranging every 2 × 2 block of pixels into four channels is PyTorch’s pixel_unshuffle. One Haar level is exactly pixel_unshuffle followed by a fixed 1 × 1 convolution whose 4 × 4 matrix is Section 1’s sums and differences, divided by 2 (checked: identical outputs). That matrix is orthogonal. So a network with pixel_unshuffle and a learned 1 × 1 convolution could learn the Haar layer. The wavelet version fixes it, guarantees that it is invertible and well conditioned, and sorts the channels by frequency, which lets the next layers treat the bands differently.
The idea goes back at least to wavelet pooling (Williams and Li, 2018), which replaced max pooling with a fixed Haar decomposition. Today it is used in four kinds of network:
- Restoration. The multi-level wavelet CNN (MWCNN; Liu and colleagues, 2018) is a U-Net whose encoder downsamples with the DWT and whose decoder upsamples with the inverse DWT. Because nothing is lost on the way down, the decoder can rebuild fine detail. It was applied to denoising, super-resolution and the removal of JPEG artefacts.
- Robust classification. WaveCNet (Li and colleagues, 2020) replaces max pooling, strided convolution and average pooling in VGG, ResNet and DenseNet with the DWT, and drops the detail bands at inference. Those bands carry most of the noise, and the networks became more robust on ImageNet-C, a corrupted version of ImageNet.
- Segmentation. Haar wavelet downsampling (HWD; Xu and colleagues, 2023) keeps every band, because boundaries are exactly what a segmentation must not lose.
- Attention. Vision transformers often shrink the keys and values with average pooling to make attention affordable. Wave-ViT (Yao and colleagues, 2022) shrinks them with the DWT instead, which loses nothing, and uses the inverse DWT to add local context back to the output.
Two cautions carry over from Section 9. An invertible layer is not a shift-invariant one: move the input by one pixel and the four bands still change, as in the first figure. And dropping the detail bands, as WaveCNet does, buys robustness with detail. Check the band order of whichever library you use, too (Section 4).
Large receptive fields from small kernels
A 3 × 3 kernel sees three pixels in each direction. Apply the same 3 × 3 kernel to the coefficients at level of a Haar decomposition, where each coefficient summarises a block, and it sees pixels: 24 at level 3, 48 at level 4. That is the idea of wavelet convolutions (WTConv; Finder and colleagues, 2024). Decompose, apply a small depthwise kernel to the bands of every level, invert, and add. The reach grows exponentially with the number of levels, while each level adds only one small kernel; the authors show that the number of parameters grows only logarithmically with the size of the receptive field. The layer drops into ConvNeXt and MobileNetV2 in place of their depthwise convolutions, and the authors report better robustness to corrupted images and a greater reliance on shape than on texture. Dilated convolutions enlarge the reach too, but they sample the input on a sparse grid; the wavelet version sees every pixel, through the averages.
Fixed features: the scattering transform
Not every layer has to be learned. The scattering transform (Bruna and Mallat, 2013) convolves the image with complex wavelets at several scales and orientations, takes the modulus, does the same again, and averages. Nothing is learned, and the result is provably stable: a small deformation of the image changes the features only a little. Two choices come straight from Section 9. The wavelets are complex and oriented, because separable real wavelets cannot tell the diagonals apart. And the modulus discards the phase, which is exactly what a shift changes.
Its main use today is as the first layers of a hybrid network. Oyallon, Belilovsky and Zagoruyko (2017) put a scattering front end before a 10-layer ResNet and matched ResNet-18 on ImageNet (11.4% single-crop top-5 error). With little training data, on subsets of CIFAR-10 and on STL-10, the hybrids beat networks trained end to end. The Kymatio library (Andreux and colleagues, 2020) computes scattering transforms on GPUs inside PyTorch and TensorFlow.
Neural operators: learning maps between functions
In scientific machine learning, a network often has to learn an operator: the map from, say, the coefficients of a PDE to its solution, for any resolution of the grid. The Fourier neural operator (FNO; Li and colleagues, 2021) does this in the language of Parts 1 and 2: take the FFT of the field, multiply its lowest modes by learned weights, and transform back. That is global, and it suits smooth solutions. The wavelet neural operator (WNO; Tripura and Chakraborty, 2023) does the same with the DWT. The learned weights act on the coefficients at the coarsest level, which are localised in space, so the layer suits solutions with sharp, local structure. Multiwavelet operators (Gupta, Xiao and Bogdan, 2021) compress the operator’s kernel in a multiwavelet basis. In all three, the learned weights act on a few coarse transform coefficients rather than on every pixel, so the number of parameters does not grow with the fine grid.
Learned compression that keeps the wavelet structure
Section 6’s codec used fixed wavelets. iWave (Ma, Liu, Xiong and Wu, 2020) keeps the lifting structure of Part 3, Section 8, and replaces the predict step with a trained CNN. Because every lifting step can be undone exactly, the transform still reconstructs perfectly and is still multiresolution, whatever the network computes. On the Kodak images it reduced the bit rate by 4.4% on average against JPEG 2000 at the same quality, and by up to 14%.
Beyond images: graphs
On a graph there is no dilation and no grid. Graph wavelets are defined through the graph’s Laplacian instead, and the graph wavelet neural network (GWNN; Xu and colleagues, 2019) uses them in place of the Laplacian’s eigenvectors as the basis for graph convolution. The wavelets are local and sparse, and a fast algorithm computes them without an eigendecomposition.
When to reach for a wavelet layer. When downsampling must not throw information away (restoration, segmentation and other dense prediction); when you need a large receptive field without large kernels; when there is little training data and a fixed, stable front end helps; and when the fields you learn have sharp, local structure.
Note (Shoulders to stand on)
- Eric Stollnitz, Tony DeRose, David Salesin, Wavelets for Computer Graphics: A Primer (IEEE CG&A, 1995). Haar in 2-D by hand, with both decompositions side by side.
- Antonio Torralba, Phillip Isola, William Freeman, Foundations of Computer Vision (MIT Press, 2024). Image pyramids and multiscale filtering, taught on images.
- Ivan Selesnick, Richard Baraniuk, Nick Kingsbury, The dual-tree complex wavelet transform (IEEE Signal Processing Magazine, 2005). The clearest account of why separable wavelets lack direction and shift-invariance, and how two trees fix both.
- Stéphane Mallat, A Wavelet Tour of Signal Processing (3rd ed., Academic Press, 2008). The 2-D theory in full, from separable bases to bandlets.
Self-check
Question 2
Compute one level of 2-D Haar, with averages, for the block . What does PyWavelets return?
Answer
, , and . PyWavelets doubles each one: cA = 6 and (cH, cV, cD) = (0, 4, -2).
Question 3
An image consists of horizontal stripes: rows alternate between 1 and 0. Which level-1 band holds the stripes, and what do the other two detail bands contain?
Answer
Every 2 × 2 block is , so , and . The stripes are entirely in cH (in PyWavelets, every cH is 1). cV and cD are zero.
Question 4
How many detail bands does a three-level wavelet transform of a 3-D volume have?
Answer
per level, so 21.
Question 5
Why does cA of a constant image double at every level of the orthonormal 2-D transform?
Answer
Each level computes , which is when all four pixels are equal to . Equivalently, per direction, twice.
Question 6
Two textures are stripes at 30° and at 150°. Can a classifier that uses only the energies of the separable wavelet bands tell them apart?
Answer
No. The two are mirror images, , and every band energy is unchanged by that (Section 9). It would need the coefficients themselves (their signs and the correlations between bands), or complex wavelets, whose bands separate the two diagonals.
Question 7
How many numbers does a four-level undecimated 2-D transform of a 256 × 256 image store?
Answer
Three full-size detail images per level and one final approximation: , 13 times the pixels.
Question 8
A network downsamples with 2 × 2 average pooling. In wavelet terms, what does it keep, what does it throw away, and how would you keep everything?
Answer
It keeps , which is the Haar approximation cA divided by 2, and throws away cH, cV and cD: all the edges and texture at that scale. A Haar layer (Section 11) keeps all four bands as channels, so the map goes from to channels at half the resolution, and the transposed convolution with the same kernels inverts it exactly.
References
- S. Mallat. A theory for multiresolution signal decomposition: the wavelet representation. IEEE TPAMI 11(7), 1989.
- G. Beylkin, R. Coifman, V. Rokhlin. Fast wavelet transforms and numerical algorithms I. Communications on Pure and Applied Mathematics 44(2), 1991.
- J. Kovačević, M. Vetterli. Nonseparable multidimensional perfect reconstruction filter banks and wavelet bases for ℝⁿ. IEEE Transactions on Information Theory 38(2), 1992.
- E. J. Stollnitz, T. D. DeRose, D. H. Salesin. Wavelets for computer graphics: a primer, part 1. IEEE Computer Graphics and Applications 15(3), 1995.
- A. Cohen, I. Daubechies, J.-C. Feauveau. Biorthogonal bases of compactly supported wavelets. CPAM 45(5), 1992.
- D. Le Gall, A. Tabatabai. Sub-band coding of digital images using symmetric short kernel filters and arithmetic coding techniques. ICASSP 1988.
- J. M. Shapiro. Embedded image coding using zerotrees of wavelet coefficients. IEEE Transactions on Signal Processing 41(12), 1993.
- A. Said, W. A. Pearlman. A new, fast, and efficient image codec based on set partitioning in hierarchical trees. IEEE Transactions on Circuits and Systems for Video Technology 6(3), 1996.
- D. Taubman. High performance scalable image compression with EBCOT. IEEE Transactions on Image Processing 9(7), 2000.
- D. L. Donoho, I. M. Johnstone. Ideal spatial adaptation by wavelet shrinkage. Biometrika 81(3), 1994.
- R. R. Coifman, D. L. Donoho. Translation-invariant de-noising. In Wavelets and Statistics, Springer, 1995.
- S. G. Chang, B. Yu, M. Vetterli. Adaptive wavelet thresholding for image denoising and compression. IEEE Transactions on Image Processing 9(9), 2000.
- J. Portilla, V. Strela, M. J. Wainwright, E. P. Simoncelli. Image denoising using scale mixtures of Gaussians in the wavelet domain. IEEE Transactions on Image Processing 12(11), 2003.
- K. Dabov, A. Foi, V. Katkovnik, K. Egiazarian. Image denoising by sparse 3-D transform-domain collaborative filtering. IEEE Transactions on Image Processing 16(8), 2007.
- N. Kingsbury. Complex wavelets for shift invariant analysis and filtering of signals. Applied and Computational Harmonic Analysis 10(3), 2001.
- I. W. Selesnick, R. G. Baraniuk, N. G. Kingsbury. The dual-tree complex wavelet transform. IEEE Signal Processing Magazine 22(6), 2005.
- E. P. Simoncelli, W. T. Freeman. The steerable pyramid: a flexible architecture for multi-scale derivative computation. ICIP 1995.
- E. J. Candès, D. L. Donoho. New tight frames of curvelets and optimal representations of objects with piecewise C² singularities. CPAM 57(2), 2004.
- G. Kutyniok, D. Labate (eds.). Shearlets: Multiscale Analysis for Multivariate Data. Birkhäuser, 2012.
- Z. Wang, E. P. Simoncelli, A. C. Bovik. Multiscale structural similarity for image quality assessment. Asilomar Conference on Signals, Systems and Computers, 2003.
- J. Bruna, S. Mallat. Invariant scattering convolution networks. IEEE TPAMI 35(8), 2013.
- R. Zhang. Making convolutional networks shift-invariant again. ICML 2019.
- Q. Li, L. Shen, S. Guo, Z. Lai. Wavelet integrated CNNs for noise-robust image classification. CVPR 2020.
- T. Williams, R. Li. Wavelet pooling for convolutional neural networks. ICLR 2018.
- P. Liu, H. Zhang, K. Zhang, L. Lin, W. Zuo. Multi-level wavelet-CNN for image restoration. CVPR Workshops 2018.
- G. Xu, W. Liao, X. Zhang, C. Li, X. He, X. Wu. Haar wavelet downsampling: a simple but effective downsampling module for semantic segmentation. Pattern Recognition 143, 2023.
- T. Yao, Y. Pan, Y. Li, C.-W. Ngo, T. Mei. Wave-ViT: unifying wavelet and transformers for visual representation learning. ECCV 2022.
- S. E. Finder, R. Amoyal, E. Treister, O. Freifeld. Wavelet convolutions for large receptive fields. ECCV 2024.
- E. Oyallon, E. Belilovsky, S. Zagoruyko. Scaling the scattering transform: deep hybrid networks. ICCV 2017.
- M. Andreux et al. Kymatio: scattering transforms in Python. JMLR 21(60), 2020.
- Z. Li, N. Kovachki, K. Azizzadenesheli, B. Liu, K. Bhattacharya, A. Stuart, A. Anandkumar. Fourier neural operator for parametric partial differential equations. ICLR 2021.
- G. Gupta, X. Xiao, P. Bogdan. Multiwavelet-based operator learning for differential equations. NeurIPS 2021.
- H. Ma, D. Liu, R. Xiong, F. Wu. iWave: CNN-based wavelet-like transform for image compression. IEEE Transactions on Multimedia, 2020.
- B. Xu, H. Shen, Q. Cao, Y. Qiu, X. Cheng. Graph wavelet neural network. ICLR 2019.
- T. Tripura, S. Chakraborty. Wavelet neural operator for solving parametric partial differential equations in computational mechanics problems. CMAME 404, 2023.
- G. Lee, R. Gommers, F. Wasilewski, K. Wohlfahrt, A. O’Leary. PyWavelets: a Python package for wavelet analysis. JOSS 4(36), 2019.
- A. Torralba, P. Isola, W. T. Freeman. Foundations of Computer Vision. MIT Press, 2024.
- S. Mallat. A Wavelet Tour of Signal Processing: The Sparse Way. 3rd ed., Academic Press, 2008.
Was this useful?
Thanks, that helps me decide what to write next.