paskvilwiki

up: math & phy

wavelets

image compression with wavelets, a code walkthrough

last updated 2026-12

paskvil-wavelets is a small wavelet image compression demo in plain TypeScript - transform an image with a wavelet, keep only the N% most important coefficients, zero the rest, transform back, and see what's left. it does four wavelet families (Haar, CDF 5/3, CDF 9/7, Daubechies D4), in colour, with PSNR as the measure, and JPEG's 8×8 DCT at the same budget for comparison. the code was written to be read, not to be fast - every lifting step is a short loop that maps line by line onto its formula

the demo runs live, with the ideas behind it and no code, on paskvil.com/projects/wavelets - try it first, it makes the code below easier to follow

this page walks through that code in the order the data goes through it. all the snippets and links are from the v1.0.0 tag, so the line numbers stay put

why wavelets compress

a wavelet transform rewrites an image as a coarse, small version of itself plus details - how far each finer scale is from what the coarser one would guess. in smooth regions the guess is good and the details are near zero, and natural images are mostly smooth regions. so most coefficients are tiny, and dropping them changes the image very little - until, at some budget, it suddenly does

the coefficients that survive cluster along edges - the outline of a beak, an eye, a feather - which is where the guess fails

the lifting scheme

all four wavelets here are written as lifting steps (Sweldens). one level of a 1D transform:

  1. split the signal into even and odd samples
  2. predict - guess each odd sample from its even neighbours, and keep only the miss: di=oddi−P(even)id_i = \text{odd}_i - P(\text{even})_i. that's the detail
  3. update - correct the even samples from the details around them, so they become a smooth half-length version of the signal: si=eveni+U(d)is_i = \text{even}_i + U(d)_i. that's the approximation
  4. scale (optional) - multiply both halves by constants, e.g. to make the transform orthonormal

the step every wavelet shares:

src/wavelets/lifting.ts, lines 25-50

export function split(x: Float64Array): { even: Float64Array; odd: Float64Array } {
  if (x.length % 2 !== 0) {
    throw new Error(`split: the signal length must be even, got ${x.length}`)
  }
  const half = x.length / 2
  const even = new Float64Array(half)
  const odd = new Float64Array(half)
  for (let i = 0; i < half; i++) {
    even[i] = x[2 * i]
    odd[i] = x[2 * i + 1]
  }
  return { even, odd }
}

/** the inverse of `split`: interleave the even and odd samples back into one signal */
export function merge(even: Float64Array, odd: Float64Array): Float64Array {
  if (even.length !== odd.length) {
    throw new Error(`merge: halves of different lengths, ${even.length} and ${odd.length}`)
  }
  const x = new Float64Array(2 * even.length)
  for (let i = 0; i < even.length; i++) {
    x[2 * i] = even[i]
    x[2 * i + 1] = odd[i]
  }
  return x
}

the trick is in what lifting doesn't need: each step changes one half using only the other half, so the inverse can recompute the very same correction and subtract it. run the steps backwards with the signs flipped, and you're back - whatever PP and UU are. the wavelet families differ only in their predict and update

Haar

the simplest one: predict "the odd sample equals its even neighbour", update "the even sample becomes the pair's average", then scale by 2\sqrt 2 to make it orthonormal - s=(a+b)/2s = (a + b)/\sqrt 2, d=(b−a)/2d = (b - a)/\sqrt 2

src/wavelets/haar.ts, lines 20-40

forward(x) {
  const { even, odd } = split(x)
  const n = even.length

  // predict: each odd sample is guessed to equal its even neighbour
  for (let i = 0; i < n; i++) {
    odd[i] -= even[i]
  }
  // update: each even sample becomes the average of its pair
  for (let i = 0; i < n; i++) {
    even[i] += odd[i] / 2
  }
  // scale to orthonormal
  for (let i = 0; i < n; i++) {
    even[i] *= SQRT2
    odd[i] /= SQRT2
  }

  return concat(even, odd)
},

it looks only at disjoint pairs, so it needs no boundary handling. it predicts constants exactly (one vanishing moment) - a constant signal leaves zero detail. anything sloped leaves some, and when those details are dropped, the image falls apart into blocks

CDF 5/3

the wavelet of lossless JPEG 2000. predict an odd sample as the average of both even neighbours - a straight line through them - and update with a quarter of the neighbouring details:

di=oddi−12(eveni+eveni+1),si=eveni+14(di−1+di)d_i = \text{odd}_i - \tfrac12(\text{even}_i + \text{even}_{i+1}), \qquad s_i = \text{even}_i + \tfrac14(d_{i-1} + d_i)

src/wavelets/cdf53.ts, lines 25-40

forward(x) {
  const { even, odd } = split(x)
  const n = even.length

  // predict: the line through the two even neighbours
  for (let i = 0; i < n; i++) {
    odd[i] -= (even[i] + evenSymmetric(even, i + 1)) / 2
  }
  // update: a quarter of the neighbouring details
  for (let i = 0; i < n; i++) {
    even[i] += (oddSymmetric(odd, i - 1) + odd[i]) / 4
  }

  return concat(even, odd)
},

a line is predicted exactly, so lines leave no detail - 2 vanishing moments. evenSymmetric and oddSymmetric decide what the step sees past the ends of the signal - below. no scaling, as in JPEG 2000 - so it isn't orthonormal, which comes back when deciding what to keep

integer to integer

the same steps with each correction rounded down - integers in, integers out, and still exactly invertible, because the inverse computes the very same rounded value from the very same inputs:

src/wavelets/cdf53.ts, lines 60-75

forward(x) {
  const { even, odd } = split(x)
  const n = even.length

  // the same steps, each correction rounded down - the inverse computes the very same
  // rounded value from the very same inputs, and subtracts it back
  for (let i = 0; i < n; i++) {
    odd[i] -= Math.floor((even[i] + evenSymmetric(even, i + 1)) / 2)
  }
  for (let i = 0; i < n; i++) {
    even[i] += Math.floor((oddSymmetric(odd, i - 1) + odd[i] + 2) / 4)
  }

  return concat(even, odd)
},

after compression it looks the same as the float version - its point is elsewhere. the coefficients are integers, so they can be stored losslessly, which is why lossless JPEG 2000 uses it. the demo has no entropy coding, so it's in the code and the tests (a bit-exact round trip), not in the UI

the range still grows a little: the detail filter (−1,2,−1)/2(-1, 2, -1)/2 can at most double a value (1 extra bit per pass, ~2 for the diagonal band in 2D), the approximation filter (−1,2,6,2,−1)/8(-1, 2, 6, 2, -1)/8 at most ×1.5, on sharp edges only - JPEG 2000 reserves guard bits for that

the original integer Haar, in Python

this page used to be just this - an integer-to-integer Haar, the 5/3's simpler ancestor. not optimized in any way, it creates too many temporaries and duplicates. the length of d (list or numpy.array) has to be a power of 2, and the result typically uses 1 more bit than the input - values in [0,N)[0, N) come out in (−N,N)(-N, N)

1D, using lists:

def haar_int_fwd_1d(d):
    if len(d) == 1:
        return d
    even = d[::2]
    odd = d[1::2]
    hp = [j - i for i, j in zip(even, odd)]
    lp = [i + (w >> 1) + (w % 2) for i, w in zip(even, hp)]
    return haar_int_fwd_1d(lp) + hp
    
def haar_int_inv_1d(d):
    if len(d) == 1:
        return d
    even = haar_int_inv_1d(d[:len(d) >> 1])
    odd = d[len(d) >> 1:]
    lp = [i - (j >> 1) - (j % 2) for i, j in zip(even, odd)]
    hp = [i + j for i, j in zip(lp, odd)]
    return [x for t in zip(lp, hp) for x in t]

1D, using numpy arrays:

import numpy as np

def haar_int_fwd_1d_np(d):
    if len(d) == 1:
        return d
    hp = d[1::2] - d[::2]
    lp = d[::2] + (hp >> 1) + (hp % 2)
    return np.concatenate((haar_int_fwd_1d_np(lp), hp))

def haar_int_inv_1d_np(d):
    if len(d) == 1:
        return d
    lp = haar_int_inv_1d_np(d[:len(d) >> 1]) 
    hp = d[len(d) >> 1:] 
    even = lp - (hp >> 1) - (hp % 2)
    return np.ravel(np.column_stack((even, even + hp)))

2D, numpy - highly un-optimized, a copy for each step, and np.apply_along_axis builds the new array row by row. note that this one transforms all the way down along each axis first (the standard decomposition), not level by level like the pyramid below

def haar_int_fwd_2d_np(d):
    tmp = np.apply_along_axis(haar_int_fwd_1d_np, 0, d)
    return np.apply_along_axis(haar_int_fwd_1d_np, 1, tmp)

def haar_int_inv_2d_np(d):
    tmp = np.apply_along_axis(haar_int_inv_1d_np, 1, d)
    return np.apply_along_axis(haar_int_inv_1d_np, 0, tmp)

CDF 9/7

the wavelet of lossy JPEG 2000, and the demo's default. two rounds of the 5/3 shape - look at the two neighbours, add a multiple of their sum - with other weights, then scaling:

src/wavelets/cdf97.ts, lines 34-57

forward(x) {
  const { even, odd } = split(x)
  const n = even.length

  for (let i = 0; i < n; i++) {
    odd[i] += ALPHA * (even[i] + evenSymmetric(even, i + 1))
  }
  for (let i = 0; i < n; i++) {
    even[i] += BETA * (oddSymmetric(odd, i - 1) + odd[i])
  }
  for (let i = 0; i < n; i++) {
    odd[i] += GAMMA * (even[i] + evenSymmetric(even, i + 1))
  }
  for (let i = 0; i < n; i++) {
    even[i] += DELTA * (oddSymmetric(odd, i - 1) + odd[i])
  }
  for (let i = 0; i < n; i++) {
    even[i] *= ZETA
    odd[i] /= ZETA
  }

  return concat(even, odd)
},

the constants α,β,γ,δ\alpha, \beta, \gamma, \delta come from factoring the 9- and 7-tap filters into lifting steps (Daubechies & Sweldens). the result predicts cubics exactly - 4 vanishing moments, so smooth regions leave almost nothing. the scaling ζ=2/K\zeta = \sqrt 2 / K (KK = the lowpass gain of the unscaled steps) gives both halves the gain of an orthonormal transform, so 9/7 is nearly orthonormal

why a round trip can't catch a wrong constant

lifting inverts anything - change γ\gamma from 0.8829 to 0.88, and forward + inverse still give back the signal exactly. the transform is just no longer the 9/7: it stops predicting cubics, and compresses worse

so the tests that matter aren't round trips, but vanishing moments: a polynomial below the wavelet's degree must give exactly zero detail (away from the ends), and the next degree up mustn't - Haar 1, 5/3 2, 9/7 4, D4 2. checked by sabotage: with the nudged γ\gamma, every round trip passes, and the cubic and constant-image tests fail

it caught a real bug, too - D4 below, first written with its first two steps in the wrong order, inverted perfectly

Daubechies D4

orthogonal like Haar, with 2 vanishing moments like 5/3. its lifting factorization starts with an update, not a predict - the steps can come in either order, as long as the inverse undoes them backwards:

src/wavelets/d4.ts, lines 26-46

forward(x) {
  const { even, odd } = split(x)
  const n = even.length

  for (let i = 0; i < n; i++) {
    even[i] += SQRT3 * odd[i]
  }
  for (let i = 0; i < n; i++) {
    odd[i] -= (SQRT3 / 4) * even[i] + ((SQRT3 - 2) / 4) * periodic(even, i - 1)
  }
  for (let i = 0; i < n; i++) {
    even[i] -= periodic(odd, i + 1)
  }
  for (let i = 0; i < n; i++) {
    even[i] *= SCALE_EVEN
    odd[i] *= SCALE_ODD
  }

  return concat(even, odd)
},

the price of orthogonality: its filters aren't symmetric, so its basis functions are lopsided - compressed, it smears to one side, where 5/3 and 9/7 blur evenly

the edges

a predict step at the last odd sample wants the even sample after it, an update at the first even sample wants the odd one before it. neither exists, so the signal is extended - and how matters: a jump at the edge makes big details, and dropping them smears the edge, which looks just like a compression artifact

src/wavelets/boundaries.ts, lines 25-44

export function evenSymmetric(even: Float64Array, i: number): number {
  return i < even.length ? even[i] : even[2 * even.length - 1 - i]
}

/** whole-sample symmetric extension, the odd samples' left end: x[-1] = x[1], i.e. odd[-1] = odd[0] */
export function oddSymmetric(odd: Float64Array, i: number): number {
  return i >= 0 ? odd[i] : odd[-1 - i]
}

/**
 * periodic extension - the signal repeats, so past the right end is the left end again
 *
 * for D4: periodic keeps it exactly orthonormal (energy preserved), at the price of a jump
 * where the ends meet. symmetric would be invertible too, but D4's filters aren't symmetric,
 * so it stops being orthonormal (~3% energy off on a random signal)
 */
export function periodic(samples: Float64Array, i: number): number {
  const n = samples.length
  return samples[((i % n) + n) % n]
}
  • CDF 5/3 and 9/7 - whole-sample symmetric, mirrored around the end sample without repeating it (x−1=x1x_{-1} = x_1, xN=xN−2x_N = x_{N-2}). no jump, and their filters are symmetric, so the edge looks like any other place in the signal. a ramp leaves edge details < 2
  • D4 - periodic, the signal wraps around. that keeps it exactly orthonormal, at the price of a jump where the ends meet - the same ramp leaves edge details > 10 (63 joins back to 0)
  • Haar - none needed
why whole-sample, and not repeating the end sample

back to the rule that makes lifting invertible - a step corrects one half using only the other half. so an extended even sample must come from the even samples, an extended odd one from the odd ones

whole-sample mirroring (xN=xN−2x_N = x_{N-2}) maps even to even and odd to odd. half-sample mirroring - repeating the end sample, xN=xN−1x_N = x_{N-1} - would hand the predict step the very odd sample it's correcting, and the round trip breaks (an error of ~15 on 8-bit data)

for D4, symmetric extension would still invert - it just stops being orthonormal (~3% energy off on a random signal), because D4's filters aren't symmetric. hence periodic

2D - the pyramid

images are 2D, the wavelets 1D - so every row, then every column, of the current square, then the same again on the top-left quarter (Mallat's pyramid):

src/wavelets/pyramid.ts, lines 18-37

export function forward2d(
  image: Float64Array,
  size: number,
  wavelet: Wavelet,
  levels: number,
): Float64Array {
  checkSizes(image, size, levels)
  const out = image.slice()
  let current = size
  for (let level = 0; level < levels; level++) {
    for (let y = 0; y < current; y++) {
      setRow(out, size, y, wavelet.forward(getRow(out, size, y, current)))
    }
    for (let x = 0; x < current; x++) {
      setColumn(out, size, x, wavelet.forward(getColumn(out, size, x, current)))
    }
    current /= 2
  }
  return out
}

after one level, the square holds four subbands:

+-------+-------+      LL - approximation in both directions: a half-size image
|  LL   |  HL   |      HL - detail along the rows: vertical edges
+-------+-------+      LH - detail along the columns: horizontal edges
|  LH   |  HH   |      HH - detail in both: diagonals, texture, noise
+-------+-------+

the next level only transforms LL, so the squares shrink - 512, 256, 128… the demo always works on 512×512 (292^9), so any of its 1-6 levels divides evenly. tested on the obvious cases: vertical stripes land in HL only, a constant image only in LL

colour

each pixel goes from RGB to YCbCr (the JPEG / JPEG 2000 transform, BT.601) - brightness, and how blue / red the colour is compared to a grey of the same brightness. natural images have most of their detail in Y, so Cb and Cr compress far better than R, G, B would. each channel is transformed on its own

real codecs go further, and subsample the colour - Cb and Cr at half the resolution, before any transform, because the eye is much sharper for brightness than for colour. the demo leaves that out, to keep the principle clean - and as it turns out, the global cutoff does a bit of it on its own

all three channels are level-shifted by −128 first, as JPEG does - centred on 0, or the low frequencies carry a huge constant offset that skews the ranking. drop every coefficient and you get flat grey 128

what to keep

the compression itself: rank every coefficient by how much it matters, keep the top N, zero the rest. "how much it matters" is what dropping it would cost - a dropped coefficient cc takes away cc times its synthesis function (what the inverse paints for a lone 1 at that spot), so the damage is c2 ∥synthesis function∥2c^2\,\lVert\text{synthesis function}\rVert^2, and the ranking is by

∣c∣⋅∥synthesis function of c’s subband∥|c| \cdot \lVert\text{synthesis function of } c\text{'s subband}\rVert

for the orthonormal wavelets (Haar, D4) every norm is 1, and this is plain magnitude. for 5/3 the norms differ by over 4× between subbands, for 9/7 they stay within 1.5×. the norm depends only on the level and the band, and the 2D transform is separable, so a 2D norm is the product of two 1D ones - one 1D impulse per level and side is enough:

src/compress/weights.ts, lines 46-78

export function synthesisNorms1d(
  wavelet: Wavelet,
  size: number,
  levels: number,
): { approximation: number[]; detail: number[] } {
  const approximation: number[] = []
  const detail: number[] = []
  for (let level = 1; level <= levels; level++) {
    const bandLength = size / 2 ** level
    // approximation band: [0, bandLength), detail band: [bandLength, 2 · bandLength)
    approximation.push(impulseNorm(wavelet, size, level, Math.floor(bandLength / 2)))
    detail.push(impulseNorm(wavelet, size, level, bandLength + Math.floor(bandLength / 2)))
  }
  return { approximation, detail }
}

/** the norm of what the inverse paints for a lone 1 at `position`, in a `level`-level 1D pyramid */
function impulseNorm(wavelet: Wavelet, size: number, level: number, position: number): number {
  let signal = new Float64Array(size)
  signal[position] = 1
  // the 1D pyramid backwards: each level inverts the first `length` values
  for (let l = level; l >= 1; l--) {
    const length = size / 2 ** (l - 1)
    const restored = wavelet.inverse(signal.subarray(0, length))
    signal = signal.slice()
    signal.set(restored, 0)
  }
  let sumOfSquares = 0
  for (let i = 0; i < size; i++) {
    sumOfSquares += signal[i] * signal[i]
  }
  return Math.sqrt(sumOfSquares)
}

then one ranking over every subband of all three channels - whatever matters least goes first, wherever it is:

src/compress/threshold.ts, lines 21-50

export function rank({ channels, weights }: WeightedCoefficients): Uint32Array {
  const length = weights.length
  const importance = new Float64Array(channels.length * length)
  for (let k = 0; k < channels.length; k++) {
    for (let i = 0; i < length; i++) {
      importance[k * length + i] = Math.abs(channels[k][i]) * weights[i]
    }
  }
  const order = new Uint32Array(importance.length)
  for (let i = 0; i < order.length; i++) {
    order[i] = i
  }
  return order.sort((a, b) => importance[b] - importance[a])
}

/** the channels with only the first `count` coefficients of the ranking kept, the rest zeroed */
export function keepTop(
  channels: readonly Float64Array[],
  order: Uint32Array,
  count: number,
): Float64Array[] {
  const length = channels[0].length
  const kept = channels.map(() => new Float64Array(length))
  for (let n = 0; n < Math.min(count, order.length); n++) {
    const k = Math.floor(order[n] / length)
    const i = order[n] % length
    kept[k][i] = channels[k][i]
  }
  return kept
}

the sort is the slow part, so it runs once per transform - after that, any budget is just "the first N of the ranking", and the slider can move live

why not just the largest coefficients

for 5/3, ranking by raw magnitude keeps the wrong ones - it costs 5-7 dB (at 0.5 / 1 / 2% kept: 23.75 / 27.31 / 31.97 dB, against 31.01 / 33.88 / 37.05 weighted). for the nearly orthonormal 9/7 the difference is under 0.01 dB, for Haar and D4 there's none

why no special case for the low-low band

a common shortcut is "always keep LL, it's tiny". it's only tiny at deep levels - with 1 level, LL is 25% of all coefficients, with 3 levels 1.6%. forcing it in would break a small budget, so it competes like everything else. the same goes for the DCT's DC terms below

one global cutoff over the channels has a nice side effect: Cb and Cr carry little detail, so their coefficients go first. on the test image (a crop of Kodak's parrots), Y gets ~67-74% of the kept coefficients, Cb ~11-15%, Cr ~15-20% - at 1%, the finest level of Cb keeps nothing at all. a bit of chroma subsampling, for free

is one cutoff fair across channels, though? YCbCr isn't orthonormal, but the inverse matrix's columns have norms Y ≈ 1.73, Cb ≈ 1.81, Cr ≈ 1.57 - within ~15%, close enough without weights

the pipeline

the whole thing, in two halves - the slow one once per image and transform, the fast one on every move of the slider:

src/compress/compression.ts, lines 39-59

export function analyze(image: RgbImage, transform: Transform2d): Analysis {
  const planes = toYCbCr(image)
  const channels = [planes.y, planes.cb, planes.cr].map((plane) =>
    transform.forward(shifted(plane, -128), image.size),
  )
  const coefficients = { channels, weights: transform.weights(image.size) }
  return { size: image.size, transform, coefficients, order: rank(coefficients) }
}

/** the image rebuilt from only the `count` most important coefficients */
export function reconstruct(analysis: Analysis, count: number): Reconstruction {
  const { size, transform, coefficients, order } = analysis
  const kept = keepTop(coefficients.channels, order, count)
  const [y, cb, cr] = kept.map((channel) => shifted(transform.inverse(channel, size), +128))
  const [keptY, keptCb, keptCr] = keptPerChannel(order, count, 3)
  return {
    image: fromYCbCr({ y, cb, cr }, size),
    keptCoefficients: kept,
    kept: { total: keptY + keptCb + keptCr, y: keptY, cb: keptCb, cr: keptCr },
  }
}

the numbers

PSNR, 10log⁡10(2552/MSE)10\log_{10}(255^2/\text{MSE}), on the 8-bit RGB result (rounded and clamped - what you'd see), 512×512, 5 levels:

keep Haar D4 CDF 5/3 CDF 9/7
0.5% 28.75 29.60 31.01 31.37
1% 31.30 32.43 33.88 34.23
2% 34.06 35.64 37.05 37.38
5% 38.24 40.22 41.58 41.81
10% 41.96 43.74 44.97 45.16

the order holds at every budget. by eye, at 0.5%: Haar blocky, D4 smeared and lopsided, 5/3 and 9/7 soft but clean

the DCT, for comparison

JPEG cuts the image into 8×8 blocks and transforms each on its own with the discrete cosine transform - 64 weights of 64 fixed cosine patterns, from flat (the DC term) to the finest checkerboard:

src/dct/dct.ts, lines 21-41

export const DCT_MATRIX: readonly Float64Array[] = Array.from({ length: BLOCK }, (_, u) => {
  const row = new Float64Array(BLOCK)
  const scale = u === 0 ? Math.sqrt(1 / BLOCK) : Math.sqrt(2 / BLOCK)
  for (let x = 0; x < BLOCK; x++) {
    row[x] = scale * Math.cos(((2 * x + 1) * u * Math.PI) / (2 * BLOCK))
  }
  return row
})

/** 1D DCT of 8 values: how much of each cosine pattern is in them */
export function dct1d(values: Float64Array): Float64Array {
  const out = new Float64Array(BLOCK)
  for (let u = 0; u < BLOCK; u++) {
    let sum = 0
    for (let x = 0; x < BLOCK; x++) {
      sum += DCT_MATRIX[u][x] * values[x]
    }
    out[u] = sum
  }
  return out
}

orthonormal, so the weights are 1, and the same level shift and top-N rule apply - the same coefficient budget, without inventing a quantizer:

keep DCT CDF 9/7
0.5% 20.63 31.37
1% 26.65 34.23
2% 33.36 37.38
5% 39.95 41.81
10% 44.07 45.16

above ~5% the DCT is within 1-2 dB. below ~1.6% it collapses: the DC terms alone are 1/64 ≈ 1.56% of all coefficients, so some blocks lose even their DC and go flat grey - and where Cb or Cr loses it, the block's colour goes wrong (magenta and green patches). real JPEG keeps every block's DC term - its quantizer rounds coefficients rather than ranking them out. the colour split shows it too: the DCT needs a DC term per block in every channel, so Cb and Cr take ~25% each, where the wavelets get by with a handful of LL coefficients and spend the rest on Y

where the budget is tight, the DCT's blocks know nothing of each other, and the seams show up as a grid. the wavelets' basis functions overlap and come in all sizes, so they blur and ring instead - which is the reason JPEG 2000 exists

what it isn't

not a codec - the budget is a count of coefficients, not bits. a real codec quantizes the coefficients and entropy-codes them, and has to store where the kept ones are, too. so the percentages here aren't compression ratios, they're a fair way to compare transforms

references