---
title: The discrete cosine transform and compression
heading: The DCT, energy compaction, transform coding gain, bit allocation and block coders like JPEG
eyebrow: S7 · Lesson 28 · The discrete cosine transform and compression
xp: 50
---

::: hook
JPEG images, MPEG and H.264 video, AAC and MP3 audio all start the same way: transform a block of samples so that most of its energy lands in a few coefficients, then spend bits only on those. The transform they use isn't the DFT but its cousin, the discrete cosine transform. Treating the block as if it were mirrored at its ends avoids the jump a DFT sees between a block's last and first samples, so smooth signals compact into very few coefficients. How much that compaction is worth, in decibels of SNR or bits per sample, follows from the coefficients' variances.
:::

::: play
- The curves are the transform coding gain for a first-order autoregressive (AR(1)) signal with correlation ρ between neighboring samples: for a 2-point transform, $1/\sqrt{1 - \rho^2}$, and in the limit of long blocks, $1/(1 - \rho^2)$.
- Strongly correlated signals (ρ near 1, as in images and speech) gain the most.
- Most of the long-block gain is reached with blocks of 8 to 16 samples.
:::

```sim plot
view: graph
x: p = 0..0.99
y: G = 0..20 dB
plot: 10*log(1/sqrt(1 - p^2)) | label: 2-point transform
plot: 10*log(1/(1 - p^2)) | dashed | label: long-block limit
```

::: predict
## A ramp 0, 1, …, 7 is transformed by an 8-point orthonormal DCT. What fraction of its energy lands in the first two coefficients?

- [ ] About 25%
- [ ] About 60%
- [x] About 99.6%
- [ ] All of it

::: reveal
The coefficients are 9.90, −6.44, 0, −0.67, 0, −0.20, 0, −0.05: the total energy is 140, and the first two carry $(9.90^2 + 6.44^2)/140 = 99.6\%$. A DFT of the same ramp would see a jump from 7 back to 0 at the block's edge and spread energy into every bin.
:::
:::

::: nameit
## The DCT

The orthonormal **DCT-II** of a block of N samples is
$$X[k] = c_k\sum_{n=0}^{N-1}x[n]\cos\frac{\pi k(2n + 1)}{2N}, \qquad c_0 = \sqrt{1/N},\ c_k = \sqrt{2/N}\ (k > 0)$$
and its inverse uses the same basis. Basis function k is a cosine of k/(2N) cycles per sample. It equals a DFT of the block extended by its mirror image, so the periodic extension has no jumps, and for smooth or strongly correlated signals it approaches the optimal (Karhunen–Loève) transform. Being orthonormal, it preserves energy: $\sum X^2 = \sum x^2$.

## Coding gain and bit allocation

Quantizing coefficient k with $b_k$ bits leaves error proportional to $\sigma_k^22^{-2b_k}$. With an average of $\bar b$ bits, the optimal allocation is
$$b_k = \bar b + \frac12\log_2\frac{\sigma_k^2}{\left(\prod_j\sigma_j^2\right)^{1/N}}$$
and the improvement over quantizing samples directly is the **coding gain**, the ratio of the arithmetic to the geometric mean of the coefficient variances:
$$G = \frac{\frac1N\sum\sigma_k^2}{\left(\prod\sigma_k^2\right)^{1/N}}$$
For an AR(1) signal with correlation ρ, a 2-point transform's variances are 1 ± ρ, so $G = 1/\sqrt{1 - \rho^2}$; long blocks approach $1/(1 - \rho^2)$.

## Block coders

**JPEG** splits an image into 8 × 8 blocks, takes a 2D DCT, divides each coefficient by a step from a quantization table (coarser for high frequencies, where the eye is less sensitive), and entropy-codes the zigzag-ordered result, most of which is zero. Coarse steps cause **blocking artifacts** at block edges. Audio coders use the **MDCT**, overlapping blocks by half with windows chosen so the overlaps cancel their aliasing (time-domain aliasing cancellation), which avoids block edges altogether while staying critically sampled.
:::

::: example
## An AR(1) signal has ρ = 0.9. What gain does a 2-point transform give, and the long-block limit?

::: solution
1. **Two-point variances.** The two coefficients have variances 1.9 and 0.1.
2. **Means.** Their arithmetic mean is 1, and their geometric mean is
   $$\sqrt{0.19} = 0.436$$
3. **Coding gain.**
   $$\begin{aligned} G &= \frac{1}{0.436} \\ &= 2.29 \end{aligned}$$
   or 3.6 dB.
4. **Long-block limit.**
   $$\begin{aligned} G_\infty &= \frac{1}{1 - 0.81} \\ &= 5.26 \end{aligned}$$
   which is 7.2 dB, worth 1.2 bits per sample at the same distortion: half of it comes from just pairing samples.

**Answer:** a 2-point transform gives 2.29 (3.6 dB), and the long-block limit is 5.26 (7.2 dB).
:::
:::

::: example
## Allocate an average of 4 bits per coefficient between those two coefficients.

::: solution
1. **Allocation rule.**
   $$b_k = 4 + \frac12\log_2\frac{\sigma_k^2}{0.436}$$
2. **The variance-1.9 coefficient.**
   $$\begin{aligned} b_0 &= 4 + 1.06 \\ &= 5.06\ \text{bits} \end{aligned}$$
3. **The variance-0.1 coefficient.**
   $$\begin{aligned} b_1 &= 4 - 1.06 \\ &= 2.94\ \text{bits} \end{aligned}$$
4. **Why this split.** Both then have equal quantization error, which is what minimizes the total; in practice the bits are rounded and the residue entropy-coded.

**Answer:** 5.06 bits for the variance-1.9 coefficient and 2.94 bits for the variance-0.1 one.
:::
:::

::: example
## A JPEG block of 64 8-bit pixels ends up with 10 nonzero coefficients, each costing about 6 bits with its position, plus a 4-bit end-of-block code. What is the compression ratio?

::: solution
1. **Raw size.** 64 pixels of 8 bits is 512 bits.
2. **Coded size.**
   $$\begin{aligned} b &= 10 \times 6 + 4 \\ &= 64\ \text{bits} \end{aligned}$$
3. **Ratio.** 512 to 64 is 8 : 1.
4. **Other blocks.** Smooth regions code to even fewer coefficients, busy textures to more; the quantization table's coarseness sets the trade between size and visible error.

**Answer:** about 8 : 1.
:::
:::

::: check
kind: parts
given: N = 4 | 8 | 16; a = 1 | 2.5

## A block of N = {N} samples, all equal to {a}, is transformed by the orthonormal DCT.

::: part
answer: sqrt(N)*a
tolerance: 0.5%

### What is X[0]?

::: misses
- [N*a] The orthonormal scale is $\sqrt{1/N}$: $X[0] = \sqrt N\,a$.
- [any] $\sqrt{1/N}\sum x[n]$.
:::
:::

::: part
answer: N*a^2
tolerance: 0.5%

### What is the total energy of its coefficients?

::: misses
- [any] The DCT preserves energy.
:::
:::
:::

::: check
kind: parts
given: a = 3 | 5; b = 1 | 4

## A 2-point orthonormal DCT transforms the pair [{a}, {b}].

::: part
answer: (a + b)/sqrt(2)
tolerance: 0.5%

### What is X[0]?

::: misses
- [any] $(x_0 + x_1)/\sqrt2$.
:::
:::

::: part
answer: (a - b)/sqrt(2)
tolerance: 0.5%

### What is X[1]?

::: misses
- [any] $(x_0 - x_1)/\sqrt2$.
:::
:::
:::

::: check
kind: parts
given: r = 0.5 | 0.8 | 0.95

## An AR(1) signal has neighbor correlation ρ = {r}.

::: part
answer: 10*log(1/sqrt(1 - r^2))
unit: dB
tolerance: 0.5%

### What coding gain does a 2-point transform give?

::: misses
- [any] Arithmetic over geometric mean of 1 ± ρ.
:::
:::

::: part
answer: 10*log(1/(1 - r^2))
unit: dB
tolerance: 0.5%

### What is the long-block limit?

::: misses
- [any] $1/(1 - \rho^2)$.
:::
:::
:::

::: check
kind: parts
given: s = 4 | 9; t = 0.25 | 1; b = 3 | 6

## Two coefficients have variances {s} and {t}; the average budget is {b} bits each.

::: part
answer: b + 0.5*log(s/sqrt(s*t))/log(2)
unit: bits
tolerance: 0.5%

### How many bits go to the larger one?

::: misses
- [any] $\bar b + \frac12\log_2(\sigma_k^2/\text{geometric mean})$.
:::
:::

::: part
answer: 10*log((s + t)/2/sqrt(s*t))
unit: dB
tolerance: 0.5%

### What coding gain does that allocation achieve?

::: misses
- [any] Arithmetic over geometric mean.
:::
:::
:::

::: check
kind: parts
given: p = 64 | 256; d = 8 | 12; c = 6 | 12 | 20; e = 5 | 7

## A block of {p} pixels of {d} bits codes to {c} nonzero coefficients at {e} bits each, plus a 4-bit end-of-block code.

::: part
answer: p*d/(c*e + 4)
tolerance: 0.5%

### What compression ratio is that?

::: misses
- [any] Raw bits over coded bits.
:::
:::
:::

::: check
kind: parts
given: N = 8 | 16 | 32; k = 1 | 3 | 7

## Basis function k = {k} of an N = {N}-point DCT.

::: part
answer: k/(2*N)
tolerance: 0.5%

### What frequency is it, in cycles per sample?

::: misses
- [k/N] The DCT's basis steps in half cycles per block.
- [any] k/(2N).
:::
:::
:::

::: check
kind: choice

## Why do image and audio coders use the DCT rather than the DFT on each block?

- [ ] The DCT is faster to compute
- [x] The DFT treats the block as periodic, so the jump between its last and first samples spreads energy into many coefficients; the DCT implicitly mirrors the block, removing that jump, so smooth content compacts into a few low-order coefficients
- [ ] The DCT has more coefficients
- [ ] The DFT can't be inverted exactly

::: misses
- [1] Both have fast algorithms of similar cost.
- [3] Both give N coefficients for N samples (the DCT's are real).
- [4] Both are exactly invertible.
:::
:::

::: check
kind: derivation
vars: a = 0.01..10, b = 0.01..10, r = 0..0.99

## Two transform coefficients have variances a and b; separately, an AR(1) signal has correlation r.

::: step
answer: (a + b)/2/sqrt(a*b)

### What coding gain do the two coefficients give?
:::

::: step
answer: 0.5*log(a/b)/log(2)

### How many more bits does the first get than the second?
:::

::: step
answer: 1/sqrt(1 - r^2)

### What gain does a 2-point transform give the AR(1) signal?
:::

::: right
Right. Each factor of four in variance is worth one bit.
:::
:::

::: check
kind: python

## Write `dct(x)` and `idct(X)`: the orthonormal DCT-II and its inverse by direct sums, and `energy_in_first(x, m)`: the fraction of the DCT's energy in its first m coefficients.

```python starter
def dct(x):
    return list(x)

def idct(X):
    return list(X)

def energy_in_first(x, m):
    return 0.0
```

```python solution
import math

def _c(k, N):
    return math.sqrt(1 / N) if k == 0 else math.sqrt(2 / N)

def dct(x):
    N = len(x)
    return [_c(k, N) * sum(x[n] * math.cos(math.pi * k * (2 * n + 1) / (2 * N)) for n in range(N)) for k in range(N)]

def idct(X):
    N = len(X)
    return [sum(_c(k, N) * X[k] * math.cos(math.pi * k * (2 * n + 1) / (2 * N)) for k in range(N)) for n in range(N)]

def energy_in_first(x, m):
    X = dct(x)
    return sum(v * v for v in X[:m]) / sum(v * v for v in X)
```

```python tests
r = list(range(8))
assert max(abs(a - b) for a, b in zip(idct(dct(r)), r)) < 1e-12, "The inverse recovers the block."
assert abs(sum(v * v for v in dct(r)) - 140) < 1e-9, "Energy is preserved: 140."
assert abs(energy_in_first(r, 2) - 0.9965) < 1e-4, "The ramp: 99.6% in two coefficients."
assert abs(dct([1] * 8)[0] - 8 ** 0.5) < 1e-12, "A constant block: only X[0] = √8."
```

::: right
Right. Fast DCTs compute the same numbers in O(N log N) through an FFT of the mirrored block.
:::
:::

::: explain
## Why does a transform let a coder use fewer bits for the same distortion?

::: model
Neighboring samples of images and audio are strongly correlated, so a block of them carries much less information than its raw size suggests. A transform like the DCT rotates the block into coefficients that are nearly uncorrelated and whose energy is concentrated in a few of them, typically the low frequencies. Giving more bits to the large-variance coefficients and few or none to the small ones achieves the same total quantization error with fewer bits than quantizing every sample equally. The saving, the coding gain, equals the ratio of the arithmetic to the geometric mean of the coefficients' variances, and it's largest for the most strongly correlated signals.
:::
:::

::: practice
::: check
given: N = 8 | 64; a = 0.5 | 3
answer: sqrt(N)*a
tolerance: 0.5%

## Orthonormal DCT X[0] of a constant block of {a}, N = {N}?

::: misses
- [any] $\sqrt N\,a$.
:::
:::

::: check
given: r = 0.5 | 0.7 | 0.8 | 0.9 | 0.95 | 0.98
answer: 10*log(1/(1 - r^2))
unit: dB
tolerance: 0.5%

## Long-block coding gain for ρ = {r}?

::: misses
- [any] $1/(1 - \rho^2)$.
:::
:::

::: check
given: s = 2 | 16; t = 0.5 | 1
answer: 10*log((s + t)/2/sqrt(s*t))
unit: dB
tolerance: 0.5%

## Coding gain of variances {s} and {t}?

::: misses
- [any] Arithmetic over geometric mean.
:::
:::
:::
