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 , the orthonormal DCT-II is
It equals the DFT of the signal extended symmetrically (mirrored) to length . A mirror extension has no jump at the boundary, so there is no leakage from the edges, and the coefficients decay quickly.
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
- Convert to luminance and colour channels (YCbCr); downsample colour, which the eye resolves poorly.
- Cut each channel into blocks and apply the 2-D DCT (a 1-D DCT on rows, then on columns).
- Quantize: divide each coefficient by a step from a table (large steps for high frequencies) and round. This is where information is discarded.
- Zigzag-scan the coefficients so the many zeros at high frequencies line up.
- Run-length and Huffman encode.
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 "blocking" artifacts.
In software
scipy.fft.dct(x, norm="ortho")anddctnfor 2-D; Pillow'sImage.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 to .
Exercises
Exercise 1: DC coefficient
What is the orthonormal DCT coefficient of a constant block of value 100 with ?
Answer
.
Solution
; all other coefficients are 0.
Exercise 2: Why ?
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 .
Answer
They agree.
Solution
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 .
Test yourself
The DCT avoids boundary leakage because it implicitly extends the signal…
- periodically
- symmetrically (mirrored)
- with zeros
- with noise
In JPEG, information is lost in…
- the DCT
- the quantization step
- the Huffman coding
- the zigzag scan
Why are high-frequency DCT coefficients quantized more coarsely?
- they are larger
- the eye is less sensitive to fine detail, and they are usually small
- they are complex
- they carry the DC level