Wavelets, from first principles
Windows that shrink as frequency grows; when such a transform can be inverted; Haar by hand; multiresolution analysis and the two-scale equation; the fast wavelet transform as a filter bank, and lifting; perfect reconstruction; vanishing moments and why they make signals sparse; Daubechies-4 solved by hand; denoising with a proof of the universal threshold; and what the discrete transform gets wrong. Part 3 of Seeing in frequencies.
Contents
- Notation and conventions
- 1. Let the window scale with the frequency
- 2. When can you invert it?
- 3. Too many coefficients
- 4. Haar, by hand
- 5. Multiresolution analysis
- 6. From functions to filters: the fast wavelet transform
- 7. Theory meets code
- Which way do the levels count?
- Why one filter is low-pass and the other high-pass
- Four filters, one list of numbers
- PyWavelets, rebuilt in NumPy
- Where do the samples enter?
- Where is each coefficient?
- 8. The lifting scheme
- 9. Perfect reconstruction
- 10. Vanishing moments: why wavelets make signals sparse
- 11. Daubechies-4, by hand
- 12. Where the filter numbers come from
- 13. Denoising
- 14. What the discrete transform gets wrong
- 15. Images, briefly
- 16. Choosing a tool
- 17. Implementation and caveats
- 18. Where it is used, and what is open
- Self-check
- References
Seeing in frequencies, part 3 of 4. Fourier analysis → the discrete Fourier world → wavelets → wavelets for images.
This is the picture most people meet first: an image split into a half-size approximation and three images of detail, then the approximation split again, and again.
It is beautiful, and it hides almost everything: which numbers produce each quadrant, why there are three detail images, why the transform loses nothing, and why most of it is black. This post builds the 1-D machinery behind it and connects it, line by line, to the code that draws it. Part 4 then does the 2-D picture by hand.
Part 2 ended at a wall. A spectrogram looks at a signal through one window, and the uncertainty principle forbids any window from being sharp in both time and frequency, so the song’s chord and its click could not both be seen clearly. Here is the same song through a different lens: a window that shrinks as the frequency grows.
Low frequencies get long windows, so the chord’s two tones separate (the band ripples because the tones beat against each other 16 times a second, but a slice through it, or its average over the chord, has two peaks, at 40 and 56 Hz); high frequencies get short windows, so the click stays a click; and the chirp climbs as a bright diagonal. Each wavelet still obeys the uncertainty principle, but it is spent differently at every scale. This post builds that idea from the ground up, and then makes it fast, exact and compact: the discrete wavelet transform, which costs less than an FFT, reconstructs perfectly, and represents piecewise-smooth signals with very few numbers.
The route: Sections 1 to 3 define the continuous transform and prove when it can be inverted. Section 4 does the simplest wavelet, Haar, by hand. Sections 5 and 6 build the machinery: multiresolution analysis and the fast algorithm. Section 7 connects that theory to the code you will actually run: which way the levels count, why one filter is low-pass and the other high-pass, how libraries store the four filters, and where the samples enter. Sections 8 and 9 cover lifting and perfect reconstruction. Sections 10 to 12 explain what makes a wavelet good, construct Daubechies’ famous one by hand, and show where the numbers in every wavelet library come from. Section 13 uses all of it to remove noise, with a proof of the standard threshold, Section 14 is honest about what goes wrong, and Section 17 collects the traps. Images get their own post, Part 4.
Notation and conventions
| Symbol | Meaning |
|---|---|
| continuous wavelet family | |
| continuous wavelet transform | |
| , | scaling function, wavelet |
| discrete family; larger is finer | |
| , | approximation and detail spaces |
| , | low-pass and high-pass filters |
| frequency response, in radians per sample | |
| , | approximation and detail coefficients |
Filter responses use radians per sample, , because every wavelet book does; continuous transforms keep the of Parts 1 and 2. Daubechies and Strang count levels upward (, larger finer), as here; Mallat’s book counts the other way, and libraries count the number of splits. Section 7 translates between all three.
1. Let the window scale with the frequency
Pick one function , a short oscillation with zero mean, and make a family from it by stretching and sliding:
The scale stretches it (large , long and slow; small , short and fast) and slides it to time . The factor keeps .
Definition 1 (Continuous wavelet transform)
Two wavelets are worth knowing by name. The Morlet wavelet is a Gaussian-windowed complex wave, , the one in the figure above. The Mexican hat is the negative second derivative of a Gaussian, up to normalisation, the 1-D case of the Laplacian of a Gaussian that computer vision uses to find blobs (see the Laplacian post).
What does do in frequency? By Plancherel, , and by the shift and scaling rules of Part 1, . So
For each scale, is passed through a band-pass filter centred at , where is the centre frequency of . Doubling halves the centre frequency and halves the bandwidth: every filter has the same ratio of bandwidth to centre frequency (engineers call this “constant-Q”). That is the difference from the spectrogram, whose filters all have the same bandwidth.
The figure uses this directly. It labels each row by its centre frequency and gives each wavelet a fixed number of cycles : its envelope has standard deviation in time and in frequency, so the ratio of bandwidth to frequency is at every scale. These Gaussians meet the uncertainty bound of Part 2 exactly: the spreads of and are and , whose product is . What changes from row to row is only how the fixed area is shared between time and frequency.
2. When can you invert it?
A transform that cannot be undone is a feature extractor, not a representation. When does determine ?
Theorem 1 (Admissibility and the resolution of the identity)
Let be real with . Then for every ,
and (in the weak sense: inner products with any agree).
Proof
Step 1. Fix the scale and integrate over . By Section 1, is the inverse Fourier transform of . Plancherel gives .
Step 2. Integrate over and swap (everything is non-negative, so Tonelli allows it): .
Step 3. The inner integral does not depend on . For substitute , so : it equals . For substitute and use , true because is real (Part 1): again .
Step 4. Plancherel once more. What remains is .
Step 5. Inversion. Applying Steps 1 to 4 to and (polarisation) gives for all . The left side is , which is the claimed formula tested against .
Question 1
Why must a wavelet have zero mean?
Answer
Because must be finite. If , then by continuity on some interval , and . So : the wavelet must oscillate, which is where the name (“small wave”) comes from. A wavelet responds to change, never to a constant.
The Morlet wavelet is not quite admissible: its Gaussian spectrum is centred at but leaks a little to zero frequency, so the classical definition subtracts a tiny correction term. In practice it is negligible. For the 8-cycle wavelets in the figure the spectrum at zero is of its peak.
3. Too many coefficients
The continuous transform turns a function of one variable into a function of two. It is extremely redundant: nearby give almost the same number, which is why the scalogram looks smooth. For analysis by eye, redundancy is a gift. For storage, compression or fast computation, it is waste.
Keep only a grid: scales and, at each scale, positions , spaced in proportion to the wavelet’s width. Fine scales get many positions, coarse scales few. On this dyadic grid the family becomes
For a general this family is a frame: it is redundant but stable, and every can be rebuilt from using a dual family. The remarkable fact is that for special it is an orthonormal basis of : no redundancy at all, the three facts of Part 1 (coefficients are inner products, the sum rebuilds, energy is preserved) hold exactly, and the coefficients can be computed faster than an FFT. The simplest such is a hundred years older than the word “wavelet”.
4. Haar, by hand
In 1910 Alfréd Haar used the function that is on and on . Here is what it does to eight numbers.
Example 1 (Eight numbers, three steps)
Start with (the first four are the example of Stollnitz, DeRose and Salesin’s primer).
Step 1. Pair them up, , and replace each pair by its average and half-difference : averages , details . Nothing is lost, since and .
Step 2. Repeat on the averages only: and . Averages , details .
Step 3. .
Result: . One overall mean, then details at three scales, coarsest first. Setting the two details of size 1 to zero changes the rebuilt signal by at most 1 anywhere, while keeping 5 of 8 numbers: compression, in miniature.
Averages and half-differences are easy to compute but do not preserve energy. Dividing by instead of does: . That is the orthonormal Haar transform, and its coefficients are the averaging ones multiplied by at level : here , exactly what PyWavelets returns (Section 17).
Proposition 1 (The Haar system is an orthonormal basis)
On , the constant and the functions , , , with , form an orthonormal basis of .
Proof
Step 1. Unit length. equals on an interval of length , so .
Step 2. Two different Haar functions are orthogonal. Their supports are dyadic intervals, which are either disjoint (product zero) or nested. If nested and different, the coarser function is constant on the finer one’s support, and the finer one has integral zero there. The constant is orthogonal to every for the same reason.
Step 3. Completeness. By induction on , the span of and with is all functions that are constant on each interval : it has the right dimension, , and Step 1 of the example shows how to reach any such function. Step functions on dyadic intervals are dense in , so nothing is orthogonal to all of them.
Haar is perfect for steps and poor for smooth curves: it approximates a sine wave by a staircase. Can we find wavelets that are orthonormal like Haar but smooth? The framework that answers yes is the next section.
5. Multiresolution analysis
The Haar example had a structure worth naming: a sequence of ever-finer approximations, each adding detail to the last.
Definition 2 (Multiresolution analysis (Mallat, Meyer))
A sequence of closed subspaces of such that
- nested: ;
- self-similar: if and only if ;
- complete: the union of all is dense in , and their intersection is ;
- generated by one function: there is a scaling function whose integer shifts form an orthonormal basis of .
For Haar, is the functions constant on intervals of length and . Read as “what a camera with pixels wide can see”. Each sits inside , and the difference is a detail space , the orthogonal complement: .
Everything else follows from axiom 4 combined with nesting.
Proposition 2 (The two-scale equation)
There are numbers with
Proof
Step 1. A basis of . By axiom 4, is orthonormal in ; by axiom 2 and the substitution , is orthonormal and spans (the restores unit length).
Step 2. Expand in it. , so with , by fact 1 of Part 1.
Step 3. The sum of the . Normalise (one can show from axiom 3). Integrate both sides: , so .
Step 4. Orthogonality of shifts. Shift Step 2 by : . The inner product of with is, by orthonormality of the , , and by axiom 4 it is if and otherwise.
For Haar, , so . The whole multiresolution analysis is encoded in this short list of numbers, and so is the wavelet.
Proposition 3 (The wavelet from the scaling function)
Let and . Then the shifts are orthonormal, and each is orthogonal to every .
Proof
Step 1. Reduce to sums of filter coefficients. As in Step 4 above, both functions are combinations of the orthonormal , so and .
Step 2. against . Write the terms of as (using ). The substitution gives . The map is its own inverse and has no fixed point (that would need , impossible for integers), so the terms cancel in pairs and the sum is .
Step 3. against its shifts. , since the signs . Substituting , the sum becomes , which is if and otherwise, by the two-scale proposition.
One more fact, which we state without its longer proof: the shifts of span all of (see Daubechies, Ten Lectures, ch. 5). Then over all is an orthonormal basis of , and .
Question 2
What is the scaling function for, if the wavelet does the work?
Answer
The scaling function is the camera; the wavelet records what the camera misses. A finite transform never uses all scales: it stops at some coarsest level, and everything coarser is summarised by the coefficients , the low-resolution image that the details refine. That is the in the Haar example. Without , a finite transform would throw away the signal’s mean and slow trends.
6. From functions to filters: the fast wavelet transform
We never need or themselves to compute the coefficients. Write , and let and .
Proposition 4 (Mallat’s algorithm)
Proof
Step 1. The two-scale equation at level . Substitute in it and multiply by : , with . The same with gives .
Step 2. Take inner products with . The inner product is linear and the filters are real: , and likewise .
Step 3. The inverse. is an orthonormal basis of . Expanding in it, the coefficients are (Step 1) and . Taking the inner product of that expansion with gives the third formula.
Read the first line as signal processing: correlate the fine coefficients with the filter , then keep every second output. The second line does the same with . That is a two-channel filter bank, and repeating it on the approximation gives every level.
Cost. Each level does two filterings of length on the current approximation and halves it: multiply-adds. That is , cheaper than an FFT’s .
Question 3
Where is the wavelet in the code?
Answer
Nowhere. A discrete wavelet transform is two short filters, a downsampling and a loop. The functions and appear only if you ask what the filters converge to when the loop is run backwards forever (Section 11’s cascade algorithm). Choosing a wavelet means choosing four, eight or twelve numbers.
Boundaries. A finite signal needs values beyond its ends, and libraries differ. Periodisation wraps around: exactly coefficients per level, but a jump wherever the ends differ. Symmetric extension mirrors the signal: no jump, but more coefficients than samples. Measured with PyWavelets: Daubechies-4 (db2) on 8 samples gives 4 coefficients per band with periodisation and 5 with symmetric extension; Daubechies-8 (db4) on 256 samples gives 128 and 131.
7. Theory meets code
Most of the confusion around wavelets lives neither in the theory nor in the code, but in the translation between them. When I first learned this material, the proofs were clear and the library calls were easy; what I could not see was how one became the other. This section is that translation, point by point.
Which way do the levels count?
Three conventions are in common use, and they disagree about the direction of the index:
- This post (Daubechies, Strang): , so a larger is finer, and has width . The data sit in some finest space , and each split moves down: .
- Mallat’s book: , so a larger is coarser, and has width . The data sit in and each split moves up: . This matches how code counts.
- Libraries (PyWavelets, MATLAB): “level” counts how many splits have been done.
cD1is the first, finest detail;wavedec(x, w, level=n)returns[cA_n, cD_n, ..., cD_1], coarsest first.
The dictionary: Mallat’s is this post’s , and with data at this post’s level , the library’s level is this post’s . So cD1 , cD2 , and cA_n . Neither theory nor code is wrong: theory counts resolution upward from coarse, code counts the operations it has performed. When reading anything about wavelets, first check whether grows or shrinks with .
Why one filter is low-pass and the other high-pass
Nothing in the two-scale equation says “filter”. The names come from two facts already proved:
- (Section 5): a constant signal passes through with gain , the orthonormal version of averaging.
- (one vanishing moment, Section 10): the fastest possible signal, , is blocked.
So passes slow signals and stops fast ones: low-pass. The alternating flip gives , so does the opposite, and : high-pass. Orthonormality, (Section 9), says that together they split the energy at every frequency exactly. For Haar, and ; the wavelet zoo in Section 11 plots both for every wavelet. In one line: low-pass = scaling function = averages = approximation; high-pass = wavelet = differences = detail.
Four filters, one list of numbers
A library stores four filters per orthogonal wavelet, and every one of them is the single list rearranged. With taps:
| Library name | Is |
|---|---|
rec_lo | |
dec_lo | reversed |
rec_hi | , with |
dec_hi | reversed |
For Daubechies-4 in PyWavelets: rec_lo , dec_lo , rec_hi and dec_hi (all four checked). Why reversed? Mallat’s formula is a correlation with . Libraries implement every filter as a convolution, and convolving with the reversed filter is correlating with the original. So analysis (“decomposition”) uses the reversed filters, and synthesis (“reconstruction”), which really is a convolution after inserting zeros, uses and as they are.
Two smaller differences you will meet. Section 5 used , the convention of most books; libraries use . These are the same filter shifted by places, an even number, so the detail coefficients move by positions and nothing else changes. And some texts flip the sign of , which negates every detail coefficient. Magnitudes always agree.
PyWavelets, rebuilt in NumPy
Here is pywt.dwt in periodisation mode, written out with nothing but the numbers above:
import numpy as np, pywt
w = pywt.Wavelet('db2'); h = np.array(w.rec_lo); L = len(h)
g = np.array([(-1)**n * h[L - 1 - n] for n in range(L)]) # the alternating flip
x = np.array([9, 7, 3, 5, 6, 10, 2, 6.]); N = len(x)
s = L // 2 - 1 # PyWavelets centres each window
a = np.array([sum(h[n] * x[(2*k + n - s) % N] for n in range(L)) for k in range(N // 2)])
d = np.array([sum(g[n] * x[(2*k + n - s) % N] for n in range(L)) for k in range(N // 2)])
cA, cD = pywt.dwt(x, 'db2', mode='periodization')
print(np.allclose(a, cA), np.allclose(d, cD)) # True True
The textbook formula starts the -th window at sample ; PyWavelets starts it at , which centres it. I checked this offset for Haar, Daubechies-4, 6 and 8, Symlet-8 and Coiflet-12. Two correct implementations can therefore differ by a shift of the coefficients. Compare reconstructions or magnitudes, never raw arrays from different libraries. The default boundary mode, symmetric, is the same recipe on a mirrored signal: pad mirrored samples (edge repeated) on each side, convolve with dec_lo, and keep every second output starting at index . That yields coefficients per band, which is where the 5 (for , ) and the 131 (for , ) of Section 6 come from.
Where do the samples enter?
This is the gap that confused me longest. The theory says the finest coefficients are inner products, . The code is handed samples, , and treats them as the . Gilbert Strang calls this “the wavelet crime”. How wrong is it?
Proposition 5 (Samples are scaling coefficients, shifted)
Let be the centroid of (with ). For smooth ,
Proof
Step 1. Substitute : .
Step 2. Taylor-expand around : .
Step 3. Integrate against . , and by the definition of . Only survives, plus the remainder, which is .
So a sample is, up to the factor , a scaling coefficient at a shifted position. For Daubechies-4, . Measured on a smooth signal at : using the samples directly as scaling coefficients is 10% off; using samples taken at the shifted positions, 0.02% off. Coiflets are designed so that the higher moments of also vanish about its centre, which makes the shifted samples an excellent approximation.
Three consequences, worth stating plainly:
- Perfect reconstruction never depends on this. The discrete transform is an exact orthonormal change of basis of whatever vector you give it.
- Interpretation does. Reading the finest detail coefficients as samples of continuous wavelet coefficients is right only up to this shift and a slight smoothing.
- The factor explains a common surprise: for a constant signal, each level of the orthonormal transform multiplies the approximation coefficients by (Section 4’s ).
Where is each coefficient?
A detail coefficient at library level depends on a window of about samples, starting near (plus the library’s offset). To plot coefficients against time, place coefficient of level near sample . Daubechies filters are minimum phase: their energy is concentrated at the start of the filter, so their coefficients lag the features that cause them. Symlets were designed to reduce exactly this lag.
8. The lifting scheme
There is a second way to compute the same transform, faster, in place, and able to map integers to integers. Split the signal into even and odd samples, then alternately use each half to predict and update the other.
Example 2 (Haar by lifting)
Same eight numbers: evens , odds .
Predict each odd sample by its even neighbour and keep the error: .
Update the evens so that they become averages: .
These are the averages of Section 4, and is times the half-differences (lifting conventions differ by such factors). To invert, run the ladder backwards with flipped signs: , then . Each step is undone exactly, whatever was computed inside it.
That last remark is the point. Because each step adds a function of one half to the other, it can be inverted even if the function rounds. JPEG 2000’s lossless mode uses the 5/3 integer wavelet this way:
Example 3 (5/3 by hand)
With symmetric extension (, ) on :
- , , , ;
- , , , .
Integers in, integers out, and running the steps backwards recovers exactly (checked).
Daubechies and Sweldens (1998) proved that every two-channel perfect-reconstruction filter bank with finite filters factors into such lifting steps, so lifting is not a special trick but a universal way to implement wavelets, typically with about half the arithmetic.
9. Perfect reconstruction
When do analysis filters followed by synthesis filters return the input exactly? The answer is two equations in the frequency domain, and the key is what “keep every second sample, then put zeros back” does to a spectrum.
Lemma 1 (Downsampling then upsampling)
If has transform , the sequence that keeps at even and puts at odd has transform .
Proof
That sequence is , and . Multiplying by shifts a spectrum by (the modulation rule of Part 1, in radians), so the transform is .
The term is aliasing, the folding of Part 2. Push through both channels with the lemma, and the output is
Perfect reconstruction needs the second bracket (aliasing) to vanish and the first (distortion) to equal . Each channel aliases on its own; the two aliases cancel.
Proposition 6 (Orthonormal filters reconstruct perfectly)
For real , the orthonormality condition is equivalent to
With , (analysis filters reversed in time) and (the alternating flip of Section 5), both conditions of perfect reconstruction hold.
Proof
Step 1. Autocorrelation. Let . Then .
Step 2. Add the shifted copy. : odd lags cancel.
Step 3. Equivalence. This equals the constant for all exactly when , by uniqueness of Fourier coefficients. That is the orthonormality condition.
Step 4. No aliasing. The alias bracket is . Using , the second product is , which cancels the first.
Step 5. No distortion. by Step 3.
In words: the low-pass and the high-pass responses are mirror images about and their energies add to a constant. These are the “quadrature mirror” and “conjugate quadrature” filters of 1970s and 1980s speech coding, which turned out to be wavelets in disguise.
10. Vanishing moments: why wavelets make signals sparse
Haar is orthonormal, but it approximates smooth curves with staircases. What makes a better wavelet? Not smoothness of , primarily, but this:
Definition 3 (Vanishing moments)
has vanishing moments if for .
A wavelet with vanishing moments is blind to polynomials of degree below . Where the signal is smooth it looks like a polynomial at fine scales, so the wavelet coefficients there are tiny.
Theorem 2 (Decay away from singularities)
Let have vanishing moments and support in an interval . If has continuous derivatives on the support of , then
Proof
Step 1. Taylor’s theorem around : , with a polynomial of degree and .
Step 2. The polynomial is invisible. : after the substitution , it is a combination of the moments with , all zero.
Step 3. Bound the remainder. .
Step 4. Substitute , so and : the integral becomes .
So on smooth stretches, each finer level shrinks the coefficients by a factor . Measured on a smooth periodic signal: per level for Haar (), for Daubechies-4 () and for Daubechies-8 (), matching to three digits. At a jump no number of moments helps: the coefficients shrink only like . Every jump leaves a trail of a few large coefficients down the scales, and everything else is small. That is sparsity, and it is why wavelets compress and denoise piecewise-smooth signals so well. More moments are not free, though: they need longer filters, and a longer filter overlaps each singularity at more positions. In the figure below, coefficients larger than 0.01 number 134 of 240 for Haar, 33 for Daubechies-4 and 42 for Daubechies-8. The best wavelet balances the smoothness of the signal between its singularities against how many singularities there are. (Compare Part 1: Fourier coefficients of a single jump decay like everywhere in the spectrum. Wavelets confine the damage to the jump’s neighbourhood.)
Vanishing moments are easy to read off the filter.
Proposition 7 (Moments from the filter)
has vanishing moments if and only if has a zero of order at , that is, for .
Proof
Step 1. Moments are derivatives at zero. By Part 1’s rule for multiplication by , . So vanishing moments means vanishes to order at .
Step 2. The wavelet equation in frequency. Transforming with the scaling and shift rules gives , where .
Step 3. Only matters. , so by the product rule vanishes to order at exactly when does at .
Step 4. Move to . for the alternating flip, so has a zero of order at exactly when has one at .
Step 5. Derivatives of at . .
11. Daubechies-4, by hand
Now design a wavelet. Ask for the shortest filter with two vanishing moments. Haar’s two taps can give only one, so try four, .
Example 4 (Solving for the Daubechies-4 filter)
The conditions:
- (normalisation, Section 5);
- (first vanishing moment, );
- (second, ; the term is zero);
- (orthogonal to its shift by two).
(The condition follows: square 1 and 2 and add to get , then use 4.)
Step 1. Adding and subtracting 1 and 2: , with .
Step 2. Write everything in terms of : . Equation 3 becomes , so , and then .
Step 3. Substitute into 4: , which expands to , that is, .
Step 4. The quadratic formula gives . Take the minus sign (the plus sign gives the same filter reversed in time), and :
This is exactly PyWavelets’ db2 reconstruction low-pass filter (checked).
What scaling function does this filter define? Run the two-scale equation as an iteration, starting from a box: the cascade algorithm.
The result is jagged at every scale: continuous, but rough (its Hölder exponent is only about 0.55, so it has corners at every scale, Daubechies 1992). The zoo below runs the same iteration for other filters.
Question 4
Why are Daubechies wavelets so ugly?
Answer
Because beauty was not the specification. They are the shortest orthonormal filters with a given number of vanishing moments, which is what makes them fast and sparse. Smoothness comes along slowly, and symmetry not at all. For analysis that needs smooth shapes, use more taps (D8, Symlets) or give up orthonormality (next answer).
There is a theorem behind the lopsidedness. No real, compactly supported, orthonormal wavelet is symmetric or antisymmetric, except Haar (Daubechies, Ten Lectures, Theorem 8.1.4; we state it without proof). Symmetry matters for images, because an asymmetric filter shifts edges differently on their two sides. The way out is biorthogonal wavelets: use one filter pair to analyse and a different pair to synthesise. The perfect-reconstruction conditions of Section 9 still hold, orthonormality is given up, and both pairs can be symmetric. The Cohen–Daubechies–Feauveau 9/7 pair (four vanishing moments on each side) is the lossy wavelet of JPEG 2000, and 5/3 is the lossless one of Section 8.
12. Where the filter numbers come from
Every wavelet library contains tables of numbers like . Where do they come from? Except for Haar, the filter is designed first, from conditions on ; the functions and are whatever the cascade algorithm then produces.
Haar is the exception: the function comes first. Start from the box . It is the sum of two half-width boxes, , so by the formula of Section 5, for . The alternating flip gives : sum and difference, scaled.
Daubechies wavelets: spectral factorisation. Section 11 solved four equations by hand. That does not scale to longer filters; Daubechies’ construction does.
Proposition 8 (The Daubechies construction)
A real filter with vanishing moments and orthonormal shifts has , where for a polynomial with
The lowest-degree solution is : ; ; ; ; and so on.
Proof
Step 1. Vanishing moments are zeros at (Section 10): has a zero of order at , so it factors as times a constant; and the factor equals at , so the constant is and .
Step 2. Magnitudes. . Write , so . Because is real, is a real, even trigonometric polynomial, hence a polynomial in , hence a polynomial . So .
Step 3. Orthonormality. Replacing by swaps and , that is, . The condition of Section 9 becomes .
Step 4. Check the solution for . . (For general this is Bézout’s theorem; see Daubechies, Ten Lectures, §6.1.)
The last step, spectral factorisation, finds from . For : . Try : then , so and , with . The solution is , (swapping them reverses the filter). Multiply out with : the coefficients are : the same D4 filter as Section 11, by a second route.
For larger , has pairs of roots and , and building means choosing one root from each pair. That choice is what separates the families:
- Daubechies (
dbN): every root inside the unit circle (minimum phase). The energy is front-loaded and the filter is as asymmetric as possible. - Symlets (
symN): the combination of roots whose filter is closest to symmetric (linear phase). Same length, same moments, less lag. - Coiflets (
coifN): a different polynomial, chosen so that also has vanishing moments, which is what makes samples good scaling coefficients (Section 7). - Biorthogonal (
biorN.M, CDF): split the factors between two different filters, analysis and synthesis, so that both can be symmetric. The 9/7 and 5/3 filters of JPEG 2000 come from this.
The construction fits in a few lines, and it reproduces the library’s tables:
from math import comb
import numpy as np, pywt
def daubechies(p):
"""Low-pass filter with p vanishing moments, by spectral factorisation."""
y = np.poly1d([-0.25, 0.5, -0.25]) # z * sin^2(w/2), z = e^{iw}
Q = sum(comb(p - 1 + k, k) * y**k * np.poly1d([1] + [0] * (p - 1 - k)) for k in range(p)) # z^(p-1) P(y)
r = Q.r # roots come in pairs r, 1/r
L = np.real(np.poly(r[np.abs(r) < 1])) # keep those inside the unit circle
L /= L.sum() # so that L = 1 at w = 0
return np.sqrt(2) * np.convolve((np.poly1d([1, 1])**p).c / 2**p, L) # sqrt2 ((1 + z)/2)^p L(z)
for p in (2, 3, 4):
print(np.allclose(daubechies(p), pywt.Wavelet(f'db{p}').rec_lo)) # True True True
Libraries ship these numbers as precomputed tables (PyWavelets) or compute them with the same factorisation (MATLAB’s dbaux). Nothing about them is arbitrary: each table is the solution of a short list of conditions, normalisation, orthogonality and vanishing moments, plus a choice of roots.
13. Denoising
Now the payoff. Observe , with piecewise smooth and white Gaussian noise. Three facts make wavelet denoising work, and each has a short proof.
Proposition 9 (Three facts behind wavelet denoising)
- Noise stays white. If is an orthonormal transform and , then : in wavelet coordinates the noise is spread evenly over every coefficient.
- Soft thresholding is the best shrinkage under an penalty. minimises over .
- The universal threshold catches pure noise. For independent values, .
Proof
Fact 1. A linear map of a Gaussian vector is Gaussian, with covariance because is orthonormal.
Fact 2. For the objective is a parabola with minimum at , valid if . For the minimum is at , valid if . Otherwise () the objective increases away from on both sides, since its slopes there are with the right signs, so .
Fact 3, a Gaussian tail bound. For , , so .
Fact 3, the union bound. . With , , leaving .
The bound goes to zero, but slowly: measured on 4,000 trials, pure noise of length 1,024 exceeds the threshold somewhere 19% of the time (the bound says at most 21%). In practice the occasional surviving noise coefficient is small. The noise level itself is estimated from the finest details, which are mostly noise: , since is the median of (measured on samples: ).
The recipe (Donoho and Johnstone, 1994): transform, estimate , soft-threshold every detail coefficient at , transform back.
A Fourier low-pass filter (the Gaussian blur) treats every place alike, so it must choose one width that suits the smooth wave, the jumps and the spike at once. The figure gives it an unfair advantage, the best possible width chosen by looking at the true signal. The wavelet methods see only the noisy data. Measured (RMS error for soft thresholding, hard thresholding and the oracle blur):
| Noise σ | Soft | Hard | Best blur |
|---|---|---|---|
| 0.05 | 0.046 | 0.023 | 0.038 |
| 0.12 | 0.087 | 0.056 | 0.064 |
| 0.20 | 0.118 | 0.082 | 0.083 |
| 0.40 | 0.161 | 0.148 | 0.116 |
Hard thresholding beats even the oracle blur at low and moderate noise, keeping the jumps and the spike sharp. Soft thresholding at the universal threshold, the classical “VisuShrink”, is the most conservative: the threshold is designed so that essentially no noise survives, and soft thresholding also pulls every surviving coefficient toward zero, so it over-smooths. At heavy noise the jumps are buried, and an ideally tuned blur wins. Data-driven thresholds, such as Stein’s unbiased risk estimate per level (“SureShrink”; Donoho and Johnstone, 1995), close most of the gap for soft thresholding. Part 4 repeats the comparison on images.
14. What the discrete transform gets wrong
It is not shift-invariant. The discrete transform samples positions on a dyadic grid, so moving the input by one sample does not move the coefficients by one place: they change. Try the shift slider in the vanishing-moments figure and watch the finest-level energy change. Even the decay measurement at a jump shows it: for Haar, the ratio between successive levels at one jump came out instead of a steady , because the answer depends on where the jump sits relative to the grid. The cause is the one from Part 2: every level downsamples, and each band aliases a little.
Three remedies, in increasing sophistication:
- Cycle spinning (Coifman and Donoho, 1995): denoise every shifted copy, shift back, average. Simple and effective.
- The undecimated (stationary) transform: skip the downsampling and dilate the filters instead. Exactly shift-invariant, at times the storage for levels.
- The dual-tree complex wavelet transform (Kingsbury): two real trees whose filters form approximate Hilbert-transform pairs, giving complex coefficients whose magnitudes barely change under shifts, at only twice the storage in 1-D.
It knows nothing about direction. In 1-D there is none to know. In 2-D, Part 4 shows that the separable construction sees only horizontal, vertical and a “diagonal” that cannot tell / from \.
15. Images, briefly
Everything here extends to images by doing the 1-D transform along rows and then along columns. Each level then produces one approximation and three detail images. Part 4 derives why three, does a and a example by hand and an one live, settles the confusing naming of the bands, and shows compression, denoising and the shift problem on my sketches.
16. Choosing a tool
17. Implementation and caveats
import numpy as np, pywt
x = np.array([9, 7, 3, 5, 6, 10, 2, 6], float)
cA, cD = pywt.dwt(x, 'haar') # one level, orthonormal: (a + b)/sqrt2, (a - b)/sqrt2
print(cA / np.sqrt(2), cD / np.sqrt(2)) # [8. 4. 8. 4.] [ 1. -1. -2. -2.] -- Section 4
coeffs = pywt.wavedec(x, 'haar', level=3) # [cA3, cD3, cD2, cD1]: coarsest first (Section 7)
print(pywt.waverec(coeffs, 'haar')) # [ 9. 7. 3. 5. 6. 10. 2. 6.]
print(pywt.dwt_coeff_len(256, pywt.Wavelet('db4').dec_len, 'symmetric')) # 131, not 128
Run as written; the outputs are in the comments. The traps:
- Levels count in opposite directions. A library’s level is this post’s , and Mallat’s is this post’s ;
cD1is the finest detail (Section 7). - Two correct implementations can disagree by a shift. PyWavelets centres each filter window; a textbook formula starts it at . For D4 the coefficients differ by one position. Compare reconstructions or magnitudes, never raw arrays across libraries (Section 7).
- Samples are not scaling coefficients. Feeding samples in place of shifts everything by the centroid of (0.634 samples for D4). Reconstruction is unaffected; interpretation is not (Section 7).
- Coefficient counts. The default boundary mode is symmetric extension, which returns more coefficients than samples. Use
mode='periodization'for exactly per level (and accept the wrap-around jump). - Which filter is which.
rec_lois the of this post,dec_lois reversed,rec_hiis anddec_hiis reversed. Books and libraries differ in the sign and shift of ; magnitudes do not (Section 7). - Order of the output.
wavedecreturns the coarsest approximation first, then details from coarse to fine. - How many levels. Each level needs the signal to be longer than the filter;
pywt.dwt_max_level(256, 'db4')is 5 while Haar allows 8. Past that, the coefficients are dominated by boundary effects. - Thresholding the approximation by mistake. Threshold the details only; the coarsest approximation carries the signal’s mean and slow trends.
- Continuous-transform scales are not frequencies. Convert with the wavelet’s centre frequency (
pywt.scale2frequency), and check whether the library normalises for energy (, as here) or for amplitude (), which changes how the scalogram’s rows compare. - Edges of a scalogram. Near the ends of the record, long wavelets hang off the data; that region (the “cone of influence”) should not be interpreted.
- Shift sensitivity. If features must not depend on alignment, use the stationary transform, cycle spinning or complex wavelets.
- Odd lengths. With periodisation, a level halves the length only if it is even; PyWavelets rounds up (9, 10 and 11 samples give 5, 5 and 6 coefficients per band). For several levels, pad to a multiple of .
- Approximations grow. Each orthonormal level multiplies a constant by in 1-D (a constant 1 becomes after three Haar levels) and by in 2-D. Divide by that gain before displaying an approximation as an image.
18. Where it is used, and what is open
| Use wavelets when | Prefer something else when |
|---|---|
| the signal is piecewise smooth: edges, transients, spikes | it is stationary and periodic: Fourier is simpler and exact |
| you need a compact, invertible, fast representation | you need shift-invariant features: use undecimated or complex transforms |
| events of very different durations matter at once | you need fine direction in images: steerable or complex wavelets (Part 4) |
In current work. Image compression (JPEG 2000, used in digital cinema and medical imaging); denoising in imaging, spectroscopy and astronomy; transient detection in ECG, EEG and seismic records; Morlet scalograms as the standard time–frequency tool in neuroscience; multiscale solvers and adaptive grids for PDEs; the scattering transform (Bruna and Mallat, 2013), a fixed cascade of wavelet transforms and moduli whose features are stable to small deformations and which explains part of why convolutional networks work; wavelet neural operators for learning PDE solution maps (Tripura and Chakraborty, 2023); and random wavelet features for scalable non-stationary Gaussian processes.
Open questions.
- Learned filter banks with guarantees. Learning the filters of a wavelet transform from data is easy; keeping perfect reconstruction, stability and vanishing moments while doing so is not. Lifting gives a route. Which guarantees matter for downstream learning?
- Wavelets off the line. On graphs, meshes and point clouds there is no dilation, and graph wavelets are defined through the spectrum of a Laplacian. Which properties of the Euclidean theory (fast transforms, vanishing moments, sparsity theorems) survive, and at what cost?
- Adaptive bases. Wavelet packets and best-basis search pick a tiling of the time–frequency plane per signal. When does that adaptivity pay off inside a learning pipeline, compared with a fixed transform followed by a learned model?
- Resolution independence in neural operators. Wavelet-based operators promise to work across discretisations. Under which conditions on the data and the architecture can this be proved, rather than observed?
Note (Shoulders to stand on)
- Artem Kirsanov, Wavelets: a mathematical microscope (YouTube, 2022). The best visual introduction to the continuous wavelet transform.
- Eric Stollnitz, Tony DeRose, David Salesin, Wavelets for Computer Graphics: A Primer (IEEE CG&A, 1995). Haar by hand in 1-D and 2-D; our eight numbers start from their example.
- Gilbert Strang, Truong Nguyen, Wavelets and Filter Banks (Wellesley-Cambridge, 1996). The filter-bank view that makes implementation obvious.
- Stéphane Mallat, A Wavelet Tour of Signal Processing (3rd ed., Academic Press, 2008). The definitive reference, for the full theory.
Self-check
Question 5
A wavelet has 3 vanishing moments. On a smooth stretch, by what factor do its detail coefficients shrink from one level to the next finer one?
Answer
(Section 10).
Question 6
Show that the Haar filter satisfies .
Answer
, so . Then , and the sum is .
Question 7
How many vanishing moments does Haar have, and why not two?
Answer
One: , but . In filter terms, .
Question 8
A signal of samples has noise . What is the universal threshold?
Answer
.
Question 9
Why does the fast wavelet transform cost while the FFT costs ?
Answer
Each level of the wavelet transform works only on the approximation of the previous level, which halves every time: samples in total, each touched by a fixed number of filter taps. The FFT does work at every one of its stages (Part 2, Section 8).
Question 10
Why can the lifting steps of the 5/3 transform round to integers and still be inverted exactly?
Answer
Each step adds to one half of the samples a function of the other half only. Undoing it subtracts the same function of the same, unchanged half, so whatever the function computed, including any rounding, is subtracted exactly.
References
- A. Haar. Zur Theorie der orthogonalen Funktionensysteme. Mathematische Annalen 69, 1910.
- A. Grossmann, J. Morlet. Decomposition of Hardy functions into square integrable wavelets of constant shape. SIAM Journal on Mathematical Analysis 15(4), 1984.
- S. Mallat. A theory for multiresolution signal decomposition: the wavelet representation. IEEE TPAMI 11(7), 1989.
- I. Daubechies. Orthonormal bases of compactly supported wavelets. Communications on Pure and Applied Mathematics 41(7), 1988; and Ten Lectures on Wavelets, SIAM, 1992.
- A. Cohen, I. Daubechies, J.-C. Feauveau. Biorthogonal bases of compactly supported wavelets. CPAM 45(5), 1992.
- W. Sweldens. The lifting scheme: a custom-design construction of biorthogonal wavelets. Applied and Computational Harmonic Analysis 3(2), 1996.
- I. Daubechies, W. Sweldens. Factoring wavelet transforms into lifting steps. Journal of Fourier Analysis and Applications 4(3), 1998.
- D. L. Donoho, I. M. Johnstone. Ideal spatial adaptation by wavelet shrinkage. Biometrika 81(3), 1994.
- D. L. Donoho, I. M. Johnstone. Adapting to unknown smoothness via wavelet shrinkage. JASA 90(432), 1995.
- R. R. Coifman, D. L. Donoho. Translation-invariant de-noising. In Wavelets and Statistics, Springer, 1995.
- I. W. Selesnick, R. G. Baraniuk, N. G. Kingsbury. The dual-tree complex wavelet transform. IEEE Signal Processing Magazine 22(6), 2005.
- J. Bruna, S. Mallat. Invariant scattering convolution networks. IEEE TPAMI 35(8), 2013.
- 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.
- 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.
- G. Strang, T. Nguyen. Wavelets and Filter Banks. Wellesley-Cambridge Press, 1996.
- 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.