Blog · updated 19 Nov 2026 · 88 min read

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
  1. Notation and conventions
  2. 1. One 2 × 2 block, by hand
  3. 2. Why exactly three detail bands
  4. 3. The 8 × 8 patch, by hand and live
  5. 4. Names and layouts, settled
  6. 5. More levels: two different 2-D transforms
  7. 6. Compression
  8. 7. Denoising images
  9. 8. Implementation, for real
  10. One level in NumPy
  11. On a GPU: one strided convolution
  12. What the library returns
  13. Traps
  14. 9. What separable 2-D wavelets get wrong
  15. Direction
  16. Shifts
  17. The fixes
  18. 10. Where to use them
  19. 11. Wavelets in modern machine learning
  20. A layer that downsamples without losing anything
  21. Large receptive fields from small kernels
  22. Fixed features: the scattering transform
  23. Neural operators: learning maps between functions
  24. Learned compression that keeps the wavelet structure
  25. Beyond images: graphs
  26. Self-check
  27. 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 φ\varphi and wavelet ψ\psi, the low-pass filter hh and high-pass filter g[n]=(−1)nh[L−1−n]g[n] = (-1)^nh[L-1-n], and the spaces Vj⊂Vj+1V_j \subset V_{j+1}, with larger jj finer. New here:

SymbolMeaning
xx, yyhorizontal and vertical position
X[m,n]X[m, n]pixel in row mm (counted downward) and column nn
Vj=Vj⊗Vj\mathbf V_j = V_j\otimes V_j2-D approximation space
AA, HH, VV, DDone level’s four outputs, computed by hand
cA, cH, cV, cDthe same four, as PyWavelets names them
ξx\xi_x, ξy\xi_yfrequency 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, (a+b)/2(a + b)/2 and (a−b)/2(a - b)/2, so the numbers stay in the range of the pixels. PyWavelets uses the orthonormal version, (a+b)/2(a + b)/\sqrt2 and (a−b)/2(a - b)/\sqrt2, 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:

[abcd].\begin{bmatrix} a & b \\ c & d \end{bmatrix}.

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:

[a+b2a−b2c+d2c−d2].\begin{bmatrix} \frac{a+b}{2} & \frac{a-b}{2} \\[4pt] \frac{c+d}{2} & \frac{c-d}{2} \end{bmatrix}.

Then apply the same step to each column of the result:

[AVHD]=14[a+b+c+da−b+c−da+b−c−da−b−c+d].\begin{aligned} &\begin{bmatrix} A & V \\ H & D \end{bmatrix}\\ &\quad = \frac14\begin{bmatrix} a+b+c+d & a-b+c-d \\ a+b-c-d & a-b-c+d \end{bmatrix}. \end{aligned}

Each of the four numbers answers a question about the block:

  • AA (top-left): the average.
  • VV (top-right): left column minus right column. It is large when the block straddles a vertical edge.
  • HH (bottom-left): top row minus bottom row. It is large at a horizontal edge.
  • DD (bottom-right): one diagonal minus the other, a checkerboard detector.
Example 1 (One block)

For [9735]\begin{bmatrix} 9 & 7 \\ 3 & 5 \end{bmatrix}:

A=9+7+3+54=6,V=9−7+3−54=0,H=9+7−3−54=2,D=9−7−3+54=1.\begin{aligned} A &= \tfrac{9 + 7 + 3 + 5}{4} = 6,\\ V &= \tfrac{9 - 7 + 3 - 5}{4} = 0,\\ H &= \tfrac{9 + 7 - 3 - 5}{4} = 2,\\ D &= \tfrac{9 - 7 - 3 + 5}{4} = 1. \end{aligned}

The block is brighter at the top (H=2H = 2), balanced left to right (V=0V = 0), with a little checker (D=1D = 1). To go back, add and subtract the four formulas:

a=A+V+H+D,b=A−V+H−D,c=A+V−H−D,d=A−V−H+D.\begin{aligned} a &= A + V + H + D, \\ b &= A - V + H - D,\\ c &= A + V - H - D, \\ d &= A - V - H + D. \end{aligned}

Indeed 6+0+2+1=96 + 0 + 2 + 1 = 9, 6−0+2−1=76 - 0 + 2 - 1 = 7, 6+0−2−1=36 + 0 - 2 - 1 = 3 and 6−0−2+1=56 - 0 - 2 + 1 = 5. Four numbers in, four out, nothing lost.

PyWavelets divides by 2\sqrt2 at each step instead of by 22, 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 2ℓ2^\ell after ℓ\ell 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 MM be the matrix of one level of a 1-D wavelet transform on NN samples. One level of the separable 2-D transform of an N×NN\times N image XX is Y=MXM⊤Y = MXM^\top, in whichever order the passes are done. If MM is orthogonal, so is the 2-D transform, and X=M⊤YMX = M^\top YM.

Proof

Step 1. Rows. Transforming a row rr replaces it by (Mr⊤)⊤=rM⊤(Mr^\top)^\top = rM^\top. For all rows at once, X↦XM⊤X\mapsto XM^\top.

Step 2. Columns. Transforming a column cc replaces it by McMc. For all columns at once, X↦MXX\mapsto MX.

Step 3. Order. Rows then columns gives M(XM⊤)M(XM^\top); columns then rows gives (MX)M⊤(MX)M^\top. Matrix multiplication is associative, so both equal MXM⊤MXM^\top.

Step 4. Orthogonality. Stack the columns of XX into one vector: vec⁡(MXM⊤)=(M⊗M)vec⁡(X)\operatorname{vec}(MXM^\top) = (M\otimes M)\operatorname{vec}(X). Then (M⊗M)⊤(M⊗M)=(M⊤M)⊗(M⊤M)=I(M\otimes M)^\top(M\otimes M) = (M^\top M)\otimes(M^\top M) = I, so energy is preserved and the inverse is X=M⊤YMX = M^\top YM.

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 2×22\times2 block BB, one level of 2-D Haar with averages is a quarter of its 2-D DFT, laid out the same way: [AVHD]=14DFT⁡(B)\begin{bmatrix} A & V \\ H & D\end{bmatrix} = \frac14\operatorname{DFT}(B). The orthonormal version is 12DFT⁡(B)\frac12\operatorname{DFT}(B).

Proof

The 2-point DFT matrix is F2=[111−1]F_2 = \begin{bmatrix} 1 & 1 \\ 1 & -1\end{bmatrix}, since e−2πi kn/2=(−1)kne^{-2\pi i\,kn/2} = (-1)^{kn}, and the 2-D DFT of BB is F2BF2⊤F_2BF_2^\top (Part 2, Section 5). The averaging Haar step on two samples is 12F2\frac12F_2, so by the previous proposition one 2-D level is 12F2 B 12F2⊤=14F2BF2⊤\frac12F_2\,B\,\frac12F_2^\top = \frac14F_2BF_2^\top. The orthonormal step is F2/2F_2/\sqrt2, which gives 12\frac12.

Check it on the block above: np.fft.fft2([[9, 7], [3, 5]]) is [24084]=4[6021]\begin{bmatrix} 24 & 0 \\ 8 & 4\end{bmatrix} = 4\begin{bmatrix} 6 & 0 \\ 2 & 1\end{bmatrix}. 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 {Vj}\{V_j\} with scaling function φ\varphi, the 2-D approximation spaces are

Vj=Vj⊗Vj=span⁡‾{φj,k(x) φj,l(y)}k,l∈Z.\begin{aligned} \mathbf V_j &= V_j\otimes V_j\\ &= \overline{\operatorname{span}}\big\{\varphi_{j,k}(x)\,\varphi_{j,l}(y)\big\}_{k, l\in\mathbb Z}. \end{aligned}

For Haar, Vj\mathbf V_j is exactly what a camera with square pixels of side 2−j2^{-j} sees: images that are constant on each pixel. The question is what Vj+1\mathbf V_{j+1} adds to Vj\mathbf V_j.

Theorem 1 (One approximation and three details)

Let WjW_j be the 1-D detail space, so that Vj+1=Vj⊕WjV_{j+1} = V_j\oplus W_j. Then

Vj+1=(Vj⊕Wj)⊗(Vj⊕Wj)=Vj⊗Vj⏟Vj⊕Wj⊗Vj⏟WjV⊕Vj⊗Wj⏟WjH⊕Wj⊗Wj⏟WjD,\begin{aligned} \mathbf V_{j+1} &= (V_j\oplus W_j)\otimes(V_j\oplus W_j)\\ &= \underbrace{V_j\otimes V_j}_{\mathbf V_j} \oplus \underbrace{W_j\otimes V_j}_{\mathbf W_j^{V}}\\ &\qquad \oplus \underbrace{V_j\otimes W_j}_{\mathbf W_j^{H}} \oplus \underbrace{W_j\otimes W_j}_{\mathbf W_j^{D}}, \end{aligned}

and the four pieces are mutually orthogonal. The three detail spaces have orthonormal bases made of shifts and dilations of

ψV(x,y)=ψ(x) φ(y),ψH(x,y)=φ(x) ψ(y),ψD(x,y)=ψ(x) ψ(y),\begin{aligned} \psi^{V}(x, y) &= \psi(x)\,\varphi(y),\\ \psi^{H}(x, y) &= \varphi(x)\,\psi(y),\\ \psi^{D}(x, y) &= \psi(x)\,\psi(y), \end{aligned}

namely ψj,k,lb(x,y)=2j ψb(2jx−k, 2jy−l)\psi^{b}_{j,k,l}(x, y) = 2^j\,\psi^{b}(2^jx - k,\ 2^jy - l).

Proof

Step 1. Every piece lies in Vj+1\mathbf V_{j+1}. Both VjV_j and WjW_j are inside Vj+1V_{j+1}, so every product of their functions is a product of functions in Vj+1V_{j+1}.

Step 2. Together the pieces span Vj+1\mathbf V_{j+1}. A generator of Vj+1\mathbf V_{j+1} is φj+1,k(x)φj+1,l(y)\varphi_{j+1,k}(x)\varphi_{j+1,l}(y). Split each factor with the 1-D decomposition, φj+1,k=vk+wk\varphi_{j+1,k} = v_k + w_k with vk∈Vjv_k\in V_j and wk∈Wjw_k\in W_j, and multiply out:

(vk+wk)(x) (vl+wl)(y)=vk(x)vl(y)+wk(x)vl(y)+vk(x)wl(y)+wk(x)wl(y).\begin{aligned} &\big(v_k + w_k\big)(x)\,\big(v_l + w_l\big)(y)\\ &\quad = v_k(x)v_l(y) + w_k(x)v_l(y)\\ &\quad\quad + v_k(x)w_l(y) + w_k(x)w_l(y). \end{aligned}

There is one term in each piece. This is what ”⊗\otimes distributes over ⊕\oplus” means.

Step 3. The pieces are orthogonal. The inner product of two products factorises (Fubini):

⟨f1(x)g1(y), f2(x)g2(y)⟩=⟨f1,f2⟩ ⟨g1,g2⟩.\begin{aligned} &\big\langle f_1(x)g_1(y),\ f_2(x)g_2(y)\big\rangle\\ &\qquad = \langle f_1, f_2\rangle\,\langle g_1, g_2\rangle. \end{aligned}

Two different pieces differ in at least one factor, where one function comes from VjV_j and the other from WjW_j. Those are orthogonal, so the product is zero.

Step 4. Bases. By the same factorisation, products of orthonormal functions are orthonormal: ⟨ψj,kφj,l, ψj,k′φj,l′⟩=δkk′δll′\langle\psi_{j,k}\varphi_{j,l},\ \psi_{j,k'}\varphi_{j,l'}\rangle = \delta_{kk'}\delta_{ll'}. They span each piece by Step 2. Finally, ψj,k(x)φj,l(y)=2j/2ψ(2jx−k)⋅2j/2φ(2jy−l)\psi_{j,k}(x)\varphi_{j,l}(y) = 2^{j/2}\psi(2^jx - k)\cdot2^{j/2}\varphi(2^jy - l), which is the stated formula, because 2j/2⋅2j/2=2j2^{j/2}\cdot2^{j/2} = 2^j.

Applying the theorem repeatedly gives the whole mosaic: VJ=V0⊕⨁j=0J−1(WjH⊕WjV⊕WjD)\mathbf V_J = \mathbf V_0\oplus\bigoplus_{j=0}^{J-1}\big(\mathbf W_j^{H}\oplus\mathbf W_j^{V}\oplus\mathbf W_j^{D}\big). That is one small approximation, plus three detail bands per level.

The names follow from the products.

  • ψ(x)φ(y)\psi(x)\varphi(y) oscillates along xx and is smooth along yy, so it matches intensity that changes from left to right: vertical edges (VV, cV).
  • φ(x)ψ(y)\varphi(x)\psi(y) is its transpose: horizontal edges (HH, cH).
  • ψ(x)ψ(y)\psi(x)\psi(y) oscillates along both directions, with four lobes of alternating sign: a checker (DD, cD).

Here they are as surfaces. I used the smoother Daubechies-8 because Daubechies-4 is too jagged to read as a surface.

The 2-D Daubechies-8 scaling function φ(x)φ(y) and the three wavelets φ(x)ψ(y), ψ(x)φ(y) and ψ(x)ψ(y), as surfaces; amber is positive, violet negative.
one level in 2-D: ⊗ distributes over ⊕V₁ ⊗ V₁ = (V₀ ⊕ W₀) ⊗ (V₀ ⊕ W₀)first factor: along x (columns) · second factor: along y (rows)V₀ ⊗ V₀φ(x) φ(y)approximation · cA++++W₀ ⊗ V₀ψ(x) φ(y)changes along x: vertical edges · cV+−+−V₀ ⊗ W₀φ(x) ψ(y)changes along y: horizontal edges · cH++−−W₀ ⊗ W₀ψ(x) ψ(y)changes along both: checker · cD+−−+oneapproximationthreedetailsin d dimensions: 2ᵈ − 1 detail bands per level (7 for a volume)

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 2×2=42\times2 = 4 fine pixels under it, and four numbers take four numbers to describe: one average and three details. In dd dimensions, (V⊕W)⊗d(V\oplus W)^{\otimes d} multiplies out into 2d2^d terms, exactly one of which is all VV, so there are 2d−12^d - 1 detail bands per level: 7 for a volume.

The general rule is that a multiresolution analysis with dilation matrix DD needs ∣det⁡D∣−1\lvert\det D\rvert - 1 wavelets (Kovačević and Vetterli, 1992). Doubling both axes has det⁡=4\det = 4, hence three. The quincunx dilation, which rotates by 45° and scales by 2\sqrt2, has ∣det⁡∣=2\lvert\det\rvert = 2 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 HH and VV more than DD, 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 DD.

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:

X=[8880880080000000].X = \begin{bmatrix} 8 & 8 & 8 & 0 \\ 8 & 8 & 0 & 0 \\ 8 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 \end{bmatrix}.

Level 1. Cut the image into four 2 × 2 blocks and apply the four formulas to each:

  • The top-left block is all 8: A=8A = 8 and V=H=D=0V = H = D = 0.
  • The top-right block is [8000]\begin{bmatrix} 8 & 0 \\ 0 & 0 \end{bmatrix}: A=V=H=D=8/4=2A = V = H = D = 8/4 = 2.
  • The bottom-left block is the same: A=V=H=D=2A = V = H = D = 2.
  • The bottom-right block is all 0, so everything is 0.

Each number goes into its quarter, at the position of its block:

[A1V1H1D1]=[8202202002022020].\begin{bmatrix} A_1 & V_1 \\ H_1 & D_1 \end{bmatrix} = \left[\begin{array}{cc|cc} 8 & 2 & 0 & 2 \\ 2 & 0 & 2 & 0 \\ \hline 0 & 2 & 0 & 2 \\ 2 & 0 & 2 & 0 \end{array}\right].

Level 2. Apply the same formulas to the averages A1=[8220]A_1 = \begin{bmatrix} 8 & 2 \\ 2 & 0\end{bmatrix}:

A2=8+2+2+04=3,V2=8−2+2−04=2,H2=8+2−2−04=2,D2=8−2−2+04=1.\begin{aligned} A_2 &= \tfrac{8 + 2 + 2 + 0}{4} = 3,\\ V_2 &= \tfrac{8 - 2 + 2 - 0}{4} = 2,\\ H_2 &= \tfrac{8 + 2 - 2 - 0}{4} = 2,\\ D_2 &= \tfrac{8 - 2 - 2 + 0}{4} = 1. \end{aligned}

The top-left quarter becomes [3221]\begin{bmatrix} 3 & 2 \\ 2 & 1\end{bmatrix}. As a check, A2=3A_2 = 3 is the mean of the whole image: six pixels of 8, so 48/1648/16.

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 [0440]\begin{bmatrix} 0 & 4 \\ 4 & 0\end{bmatrix} (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 DD.

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.

where each band sits, and what it is calledcA'aa'average++++cV'ad'left − right+−+−cH'da'top − bottom++−−cD'dd'checker+−−+pywt.coeffs_to_array, MATLAB, most figurescV responds to vertical edges,cH to horizontal ones.pywt.dwt2 returns cA, (cH, cV, cD).dwtn keys: first letter = axis 0 = rows (y);'ad' = smooth down, detail across = cV.'LH' and 'HL' mean opposite bandsin different books and libraries.Name a band by what it detects.
  • What each band detects. cV (left − right) responds to vertical edges, cH (top − bottom) to horizontal edges, and cD to 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) returns cA, (cH, cV, cD). wavedec2 returns [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_array puts cV top-right and cH bottom-left, as in every figure in this post.
  • The n-dimensional keys. pywt.dwtn labels each band with one letter per axis, a for approximation and d for 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 is cV; 'da' is cH.
  • 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 cH in one source and cV in 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 gg, 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.wavedec2 computes.
  • 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 MM, including the full 1-D transform), but they are different bases:

Two 8 by 8 grids of tiles. Each tile is the 8 by 8 image obtained by inverting a single coefficient. Left, the pyramid decomposition: every tile has the same scale in both directions, so its blocks are squares. Right, the standard decomposition: horizontal and vertical scales are independent, so many tiles are made of long thin rectangles.

In the pyramid, every basis image has the same scale in xx and in yy: 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 k%k\% 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):

KeepEyePortraitSunset
2%28.9 vs 26.923.7 vs 22.121.6 vs 19.9
5%31.7 vs 31.126.2 vs 25.625.0 vs 25.0
10%34.7 vs 34.429.1 vs 28.728.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.

JPEG 2000: the wavelet codeccolourRGB → YCbCr(or an integer version)2-D DWTusually 5 levelsCDF 9/7 or 5/3quantisedead-zone(lossy path only)code blocksbit-planes, EBCOT+ arithmetic coderstreamembedded:cut it anywherelossy: CDF 9/7, floating pointlossless: Le Gall 5/3, integer lifting, exactly invertibleno 8 × 8 blocks; one file serves every resolution (drop the finest bands)and every quality (drop the last bit-planes)

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 σ2ln⁡N\sigma\sqrt{2\ln N} 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 σ\sigma (pixel values in [0,1][0, 1]) 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
noisy26.020.014.0
oracle blur28.425.122.5
universal, soft22.521.220.1
universal, hard24.222.120.8
BayesShrink28.324.722.3
BayesShrink + 16 shifts29.425.722.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.

  1. 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.
  2. Adapt the threshold to each band. BayesShrink (Chang, Yu and Vetterli, 2000) treats the coefficients of one band as having a Laplacian-like spread σx\sigma_x and picks the threshold T=σ2/σxT = \sigma^2/\sigma_x. 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, σ^\hat\sigma comes from the median of the finest diagonal band. And σ^x2=max⁡(y2‾−σ^2,0)\hat\sigma_x^2 = \max(\overline{y^2} - \hat\sigma^2, 0), 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.
  3. 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.
  4. 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 10−1610^{-16}. 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 L/2−1L/2 - 1 pixels on each side reproduces PyWavelets’ mode='periodization' exactly. I checked D4 and D8; the error is below 2×10−152\times10^{-15}.

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

  1. Band names. dwt2 returns H before V; cV is left − right; and “LH” means different bands in different books (Section 4). Test with an image of horizontal stripes.
  2. 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.
  3. 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 2ℓ2^\ell before showing it. Scale each detail band separately too, since they are small and signed, or they will all look black.
  4. 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. Use periodization for 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).
  5. Odd sizes. With periodisation, a 255 × 255 image gives 128 × 128 bands. For several levels, pad to a multiple of 2levels2^{\text{levels}}.
  6. How many levels. pywt.dwtn_max_level((256, 256), 'db4') is 5, while Haar allows 8. Beyond the maximum, boundary effects dominate.
  7. 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.
  8. Precision. A round trip through five levels of D8 is exact to 1.4×10−151.4\times10^{-15} in float64, and to 7.9×10−77.9\times10^{-7} in float32, the precision of most GPU pipelines. Make the reconstruction error a unit test.
  9. 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.
  10. Thresholding the approximation. Threshold the details only. The approximation holds the image’s mean and its slow shading.
  11. Pyramid or standard. wavedec2 gives 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 cos⁡(2π(ξxn+ξym)+θ)\cos\big(2\pi(\xi_xn + \xi_ym) + \theta\big) with one level of the separable transform, and write ωx=2πξx\omega_x = 2\pi\xi_x and ωy=2πξy\omega_y = 2\pi\xi_y. Unless both ξx\xi_x and ξy\xi_y are among 00, ±14\pm\frac14 and 12\frac12 cycles per pixel, its energy splits as

cA: 14∣H(ωx)∣2∣H(ωy)∣2,cH: 14∣H(ωx)∣2∣G(ωy)∣2,cV: 14∣G(ωx)∣2∣H(ωy)∣2,cD: 14∣G(ωx)∣2∣G(ωy)∣2,\begin{aligned} \text{cA}&:\ \tfrac14\lvert H(\omega_x)\rvert^2\lvert H(\omega_y)\rvert^2,\\ \text{cH}&:\ \tfrac14\lvert H(\omega_x)\rvert^2\lvert G(\omega_y)\rvert^2,\\ \text{cV}&:\ \tfrac14\lvert G(\omega_x)\rvert^2\lvert H(\omega_y)\rvert^2,\\ \text{cD}&:\ \tfrac14\lvert G(\omega_x)\rvert^2\lvert G(\omega_y)\rvert^2, \end{aligned}

for every phase θ\theta. In particular, all four shares are unchanged by ξx↦−ξx\xi_x\mapsto-\xi_x: 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 ±(ωx,ωy)\pm(\omega_x, \omega_y). A separable filter u[m] v[n]u[m]\,v[n] multiplies an exponential by U(ωy)V(ωx)U(\omega_y)V(\omega_x), because exponentials are eigenfunctions of every shift-invariant operator (Part 1, Section 5). The filters are real, so ∣U(−ω)∣=∣U(ω)∣\lvert U(-\omega)\rvert = \lvert U(\omega)\rvert, and both exponentials are scaled by the same ∣U(ωy)∣ ∣V(ωx)∣\lvert U(\omega_y)\rvert\,\lvert V(\omega_x)\rvert. 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 12∣U∣2∣V∣2\frac12\lvert U\rvert^2\lvert V\rvert^2. Keeping one sample in four leaves a grating of frequency (2ωx,2ωy)(2\omega_x, 2\omega_y), whose mean square is still 12∣U∣2∣V∣2\frac12\lvert U\rvert^2\lvert V\rvert^2, as long as its square, which contains cos⁡(2(2ωxn′+2ωym′)+2θ′)\cos\big(2(2\omega_xn' + 2\omega_ym') + 2\theta'\big), averages out. That fails only when 4ωx4\omega_x and 4ωy4\omega_y are both multiples of 2π2\pi, which are the excluded frequencies. The kept samples are a quarter of the total, so the band’s share of the energy is 14∣U∣2∣V∣2\frac14\lvert U\rvert^2\lvert V\rvert^2.

Step 3. The four bands take (U,V)=(H,H)(U, V) = (H, H), (G,H)(G, H), (H,G)(H, G) and (G,G)(G, G), with UU acting along yy: cH is high-pass along yy. Since ∣H∣\lvert H\rvert and ∣G∣\lvert G\rvert are even functions, replacing ωx\omega_x by −ωx-\omega_x changes nothing.

The figure and my checks agree with these formulas to 10−1510^{-15}. The excluded case is not academic. My first test used stripes with ξx=ξy=14\xi_x = \xi_y = \frac14, 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

why the diagonal band is ambiguous, and how complex wavelets fix itcAseparable: one diagonal band//\\cHcHcVcVall four corners are cD: / and \ togethercAdual-tree complex: six bands45°45°135°135°15°15°165°165°75°75°105°105°each band keeps one pair of opposite regionsstripe angles as in the orientation figure; ξx to the right, ξy down
  • 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 3J+13J + 1 full-size images for JJ 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 ψc=ψr+iψi\psi_c = \psi_r + i\psi_i is approximately analytic: its spectrum lives on positive frequencies only. So ψc(x)ψc(y)\psi_c(x)\psi_c(y) has its spectrum in one quadrant, and its real part in that quadrant and the opposite one: one diagonal. Its partner, ψc(x)ψc(y)‾\psi_c(x)\overline{\psi_c(y)}, 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 4K/34K/3 for KK 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 nn-term approximation decays like n−2(log⁡n)3n^{-2}(\log n)^3, against n−1n^{-1} for wavelets and n−1/2n^{-1/2} for Fourier. Shearlets use shears instead of rotations, which suits the pixel grid.

10. Where to use them

Use 2-D wavelets whenPrefer something else when
images are piecewise smooth: edges between smooth regionsthe content is oscillating texture: local cosines or Fourier
you need a compact, invertible, fast representation at every scalefeatures must be stable under shifts: undecimated, complex or scattering transforms
one file must serve many resolutions and qualitiesyou 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.

four places a wavelet transform sits inside a network1 · lossless downsamplingC × H × WDWTcAcVcHcD4C channelsH/2 × W/2pooling keeps cA only (divided by 2);the DWT keeps all four bands as channelsMWCNN · WaveCNet · Wave-ViT · HWD2 · large receptive field, small kernelsxDWTℓ = 13×3ℓ = 23×3ℓ = 33×3IDWTa 3 × 3 kernel at level ℓ covers 3 · 2ˡ pixels:reach grows fast, parameters grow slowlyWTConv3 · a fixed front endimage|ψ ∗ |ψ ∗ x||fixedsmallCNNlabelwavelets and moduli, nothing learned:stable to shifts and small deformationsscattering · Kymatio · hybrid networks4 · a neural-operator layeruDWTlearnedweightsIDWT+W u (a 1 × 1 skip)learned weights on a few coarse coefficients,not on every pixelWNO · multiwavelet operators · (FFT: FNO)

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: (a+b+c+d)/4=cA/2(a + b + c + d)/4 = \texttt{cA}/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 ℓ\ell of a Haar decomposition, where each coefficient summarises a 2ℓ×2ℓ2^\ell\times2^\ell block, and it sees 3⋅2ℓ3\cdot2^\ell 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 [4260]\begin{bmatrix} 4 & 2 \\ 6 & 0\end{bmatrix}. What does PyWavelets return?

Answer

A=12/4=3A = 12/4 = 3, V=(4−2+6−0)/4=2V = (4 - 2 + 6 - 0)/4 = 2, H=(4+2−6−0)/4=0H = (4 + 2 - 6 - 0)/4 = 0 and D=(4−2−6+0)/4=−1D = (4 - 2 - 6 + 0)/4 = -1. 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 [1100]\begin{bmatrix} 1 & 1 \\ 0 & 0\end{bmatrix}, so H=2/4=12H = 2/4 = \frac12, V=D=0V = D = 0 and A=12A = \frac12. 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

23−1=72^3 - 1 = 7 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 (a+b+c+d)/2(a + b + c + d)/2, which is 4a/2=2a4a/2 = 2a when all four pixels are equal to aa. Equivalently, 2\sqrt2 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, ξx↦−ξx\xi_x\mapsto-\xi_x, 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: (3⋅4+1)⋅65,536=851,968(3\cdot4 + 1)\cdot65{,}536 = 851{,}968, 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 (a+b+c+d)/4(a + b + c + d)/4, 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 CC to 4C4C 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.