TExcelTAD
Home › Fourier Analysis & Signals › The DCT and JPEG

The DCT and JPEG

The discrete cosine transform (DCT) is a real-valued cousin of the DFT that uses only cosines. For natural signals it packs most of the energy into a few coefficients, with no wrap-around jump at the block edges. That property made it the heart of JPEG images, MP3/AAC audio (the MDCT) and most video codecs.

The DCT-II

For x[0..N−1]x[0..N-1], the orthonormal DCT-II is

X[k]=ck∑n=0N−1x[n]cos⁡ ⁣(π(2n+1)k2N),c0=1/N, ck=2/NX[k] = c_k \sum_{n=0}^{N-1} x[n] \cos\!\left(\frac{\pi (2n + 1) k}{2N}\right), \qquad c_0 = \sqrt{1/N},\ c_k = \sqrt{2/N}

It equals the DFT of the signal extended symmetrically (mirrored) to length 2N2N. A mirror extension has no jump at the boundary, so there is no leakage from the edges, and the coefficients decay quickly.

python · try it yourself
import numpy as np

def dct2_matrix(N):
    n = np.arange(N)
    C = np.cos(np.pi * (2 * n[None, :] + 1) * n[:, None] / (2 * N)) * np.sqrt(2 / N)
    C[0] /= np.sqrt(2)
    return C

N = 8
C = dct2_matrix(N)
print("orthonormal (C C^T = I):", np.allclose(C @ C.T, np.eye(N)))

x = np.linspace(10, 30, N)                       # a smooth ramp, like a gradient in an image
dct = C @ x
dft = np.fft.fft(x) / np.sqrt(N)
print("DCT coefficients:", (np.round(dct, 2) + 0.0).tolist())
print("|DFT| coefficients:", np.round(np.abs(dft), 2).tolist())
for name, c in (("DCT", np.abs(dct)), ("DFT", np.abs(dft))):
    print(f"{name}: energy in the 2 largest coefficients {100 * np.sort(c ** 2)[-2:].sum() / np.sum(c ** 2):.2f} %")
orthonormal (C C^T = I): True
DCT coefficients: [56.57, -18.41, 0.0, -1.92, 0.0, -0.57, 0.0, -0.14]
|DFT| coefficients: [56.57, 10.56, 5.71, 4.37, 4.04, 4.37, 5.71, 10.56]
DCT: energy in the 2 largest coefficients 99.89 %
DFT: energy in the 2 largest coefficients 93.47 %

The DFT sees the ramp as a sawtooth (its periodic extension jumps from 30 back to 10), so its coefficients decay slowly. The DCT sees a smooth mirrored ramp and needs only two coefficients for nearly all the energy.

JPEG in five steps

  1. Convert to luminance and colour channels (YCbCr); downsample colour, which the eye resolves poorly.
  2. Cut each channel into 8×88 \times 8 blocks and apply the 2-D DCT (a 1-D DCT on rows, then on columns).
  3. Quantize: divide each coefficient by a step from a table (large steps for high frequencies) and round. This is where information is discarded.
  4. Zigzag-scan the coefficients so the many zeros at high frequencies line up.
  5. Run-length and Huffman encode.
python · try it yourself
import numpy as np

N = 8
n = np.arange(N)
C = np.cos(np.pi * (2 * n[None, :] + 1) * n[:, None] / (2 * N)) * np.sqrt(2 / N)
C[0] /= np.sqrt(2)

i, j = np.mgrid[0:N, 0:N]
block = 128 + 40 * np.cos(np.pi * i / 10) + 25 * np.sin(np.pi * j / 6) + 10 * ((i + j) % 2)   # smooth + fine texture
D = C @ (block - 128) @ C.T                                       # 2-D DCT

Q = 4 + 3 * (i + j)                                               # a simple quantization table: coarser at high frequency
q = np.round(D / Q)
recon = C.T @ (q * Q) @ C + 128
print("nonzero coefficients kept:", int(np.count_nonzero(q)), "of 64")
print(f"max pixel error: {np.max(np.abs(recon - block)):.2f}   RMS error: {np.sqrt(np.mean((recon - block) ** 2)):.2f}")
nonzero coefficients kept: 8 of 64
max pixel error: 7.62   RMS error: 3.58

A handful of integers describes the block to within a few grey levels; the rest are zeros that compress to almost nothing. Coarser tables mean smaller files and visible 8×88 \times 8 "blocking" artifacts.

In software

  • scipy.fft.dct(x, norm="ortho") and dctn for 2-D; Pillow's Image.save(..., quality=q) scales JPEG's quantization tables.
  • Audio codecs use the MDCT on overlapping windows to avoid block edges; video codecs (H.264, HEVC, AV1) use integer DCT approximations on blocks of 4×44 \times 4 to 64×6464 \times 64.

Exercises

Exercise 1: DC coefficient

What is the orthonormal DCT coefficient X[0]X[0] of a constant block of value 100 with N=8N = 8?

Answer

1008≈282.8100\sqrt{8} \approx 282.8.

Solution

X[0]=1/8⋅8⋅100=800/8=1008X[0] = \sqrt{1/8} \cdot 8 \cdot 100 = 800/\sqrt{8} = 100\sqrt{8}; all other coefficients are 0.

Exercise 2: Why 8×88 \times 8?

Why does JPEG use small blocks rather than one DCT of the whole image?

Answer

Image statistics change across the picture; small blocks adapt locally and are cheap to compute.

Solution

Within a small block, pixels are strongly correlated, so a few coefficients suffice; a global transform would spread a local edge's energy over the whole spectrum. Small blocks also keep the computation and memory small, which mattered in 1992 hardware.

Exercise 3: Compare with SciPy (code)

Check that the matrix DCT above matches scipy.fft.dct(x, norm="ortho") for x=[1,2,3,4,4,3,2,1]x = [1, 2, 3, 4, 4, 3, 2, 1].

Answer

They agree.

Solution
python · try it yourself
import numpy as np
from scipy.fft import dct
N = 8
n = np.arange(N)
C = np.cos(np.pi * (2 * n[None, :] + 1) * n[:, None] / (2 * N)) * np.sqrt(2 / N)
C[0] /= np.sqrt(2)
x = np.array([1, 2, 3, 4, 4, 3, 2, 1], dtype=float)
print(np.allclose(C @ x, dct(x, norm="ortho")), (np.round(C @ x, 4) + 0.0).tolist())
True [7.0711, 0.0, -3.1543, 0.0, 0.0, 0.0, -0.2242, 0.0]

The symmetric input has zero coefficients at all odd kk.

Test yourself

The DCT avoids boundary leakage because it implicitly extends the signal…

  1. periodically
  2. symmetrically (mirrored)
  3. with zeros
  4. with noise

In JPEG, information is lost in…

  1. the DCT
  2. the quantization step
  3. the Huffman coding
  4. the zigzag scan

Why are high-frequency DCT coefficients quantized more coarsely?

  1. they are larger
  2. the eye is less sensitive to fine detail, and they are usually small
  3. they are complex
  4. they carry the DC level