11. DCT & Image Compression
The mathematical trick at the heart of JPEG
An image is a grid of numbers. Each pixel has a brightness value (0–255 for grayscale), and a typical photo might have millions of pixels. A 12-megapixel photo in raw form is about 36 MB. We need to get that down to 2–4 MB without destroying the image. That's a 10:1 ratio, and the Discrete Cosine Transform (DCT) is the single most important tool for achieving it.
The DCT converts spatial data — pixel values laid out in a grid — into frequency data. It separates what matters visually from what doesn't. The things that don't matter much can be thrown away, and that's where the compression comes from. This is lossy compression: the reconstructed image isn't identical to the original, but if done right, the difference is invisible.
From Pixels to Frequencies
Think of a small region of an image — say, an 8×8 block of pixels. The pixel values might change gradually across the block (a smooth gradient in the sky) or change rapidly (the edge of a letter on a white background). We can describe these patterns using frequencies:
- Low frequencies — smooth, gradual changes. The overall brightness and broad gradients.
- High frequencies — sharp edges, fine textures, rapid transitions.
The Key Observation
Most image regions are dominated by low frequencies. A patch of sky, a section of skin, the flat side of a building — these are mostly smooth. The DCT concentrates most of the image's energy (the important information) into a small number of low-frequency coefficients. The many high-frequency coefficients are typically small — close to zero. This is what makes compression possible: we can discard or coarsely round those small values with very little visible impact.
What the DCT Does
The DCT takes a block of pixel values and expresses them as a weighted sum of cosine basis functions. Each basis function represents a specific frequency of oscillation. The weights (called coefficients) tell you how much of each frequency pattern is present in the original data.
Let's start with the 1D case for simplicity. Given N values (typically N = 8), the DCT produces N coefficients:
- The first coefficient (k = 0) is the DC coefficient — it's proportional to the average value of the block.
- The remaining coefficients (k = 1, 2, ..., 7) are AC coefficients, representing increasingly fine oscillations.
The 1D DCT-II Formula
X[k] = c(k) · Σ x[n] · cos(π/N · (n + 0.5) · k)
n=0..N-1
where c(0) = sqrt(1/N), c(k) = sqrt(2/N) for k > 0
For each output coefficient k, you multiply every input value x[n] by a cosine
at frequency k, then sum them up. The cosine argument shifts by half a sample
(the n + 0.5 term), which is what distinguishes the DCT from the
ordinary DFT and gives it better boundary behavior.
1D DCT Worked Example
Input: 8 pixel values
x = [52, 55, 61, 66, 70, 61, 64, 73]
Step 1: Compute the DCT coefficients
Applying the formula with N = 8:
X[0] = 0.354 · (52 + 55 + 61 + 66 + 70 + 61 + 64 + 73) = 0.354 · 502 ≈ 177.6
X[1] = 0.500 · Σ x[n] cos(π/8 (n+0.5) · 1) ≈ -12.1
X[2] = 0.500 · Σ x[n] cos(π/8 (n+0.5) · 2) ≈ 5.8
X[3] = 0.500 · Σ x[n] cos(π/8 (n+0.5) · 3) ≈ -2.2
X[4] = 0.500 · Σ x[n] cos(π/8 (n+0.5) · 4) ≈ 1.5
X[5] = 0.500 · Σ x[n] cos(π/8 (n+0.5) · 5) ≈ -0.9
X[6] = 0.500 · Σ x[n] cos(π/8 (n+0.5) · 6) ≈ 0.3
X[7] = 0.500 · Σ x[n] cos(π/8 (n+0.5) · 7) ≈ -0.2
Notice the pattern: X[0] is large (177.6 — it captures the average brightness). X[1] is moderate (−12.1 — there's a noticeable upward trend). The rest are small and getting smaller. Most of the energy is in the first few coefficients.
Step 2: Quantize
Divide each coefficient by a quantization step size (say, Q = 10) and round to the nearest integer:
Before: [177.6, -12.1, 5.8, -2.2, 1.5, -0.9, 0.3, -0.2]
÷ 10: [ 17.8, -1.2, 0.6, -0.2, 0.2, -0.1, 0.0, 0.0]
Rounded: [ 18, -1, 1, 0, 0, 0, 0, 0]
Five of the eight coefficients are now zero. Only three values need to be stored. The run of zeros at the end compresses trivially with run-length encoding. This is the heart of lossy compression: we've discarded information that contributes very little to the visual appearance.
2D DCT: The Real Thing
Images are two-dimensional, so JPEG uses the 2D DCT on 8×8 blocks of pixels. The 2D DCT is separable: you apply the 1D DCT to each row, then apply it again to each column of the result. (The order doesn't matter — you get the same answer either way.)
The result is an 8×8 matrix of 64 coefficients. Each coefficient corresponds to one of 64 basis patterns:
The 8×8 basis pattern grid (conceptual):
k_x = 0 1 2 3 4 5 6 7
k_y ┌──────────────────────────────────────────────────────┐
0 │ DC low-h ─────────────────────────── high-h │
1 │ low-v │
2 │ │ │
3 │ │ increasing horizontal frequency → │
4 │ │ │
5 │ │ increasing vertical frequency ↓ │
6 │ │ │
7 │ high-v checkerboard │
└──────────────────────────────────────────────────────┘
- Top-left (0,0) — the DC coefficient: average brightness of the entire 8×8 block. A flat, uniform pattern.
- Moving right — increasing horizontal frequency. One vertical stripe, two stripes, three stripes, etc.
- Moving down — increasing vertical frequency. Horizontal stripes at increasing rates.
- Bottom-right (7,7) — highest frequency in both directions. A checkerboard pattern at the finest possible scale.
Any 8×8 image block can be reconstructed by adding together all 64 basis patterns, each weighted by its coefficient. After quantization, most of the high-frequency coefficients (lower-right region) become zero. The block is reconstructed from just the surviving low-frequency patterns — and it still looks almost identical to the original.
The JPEG Quantization Matrix
JPEG doesn't use a single quantization step for all 64 coefficients. Instead, it uses a quantization matrix — a different divisor for each position. The crucial design: high-frequency positions get larger divisors, because the human eye is less sensitive to high-frequency detail.
Standard JPEG Luminance Quantization Matrix
16 11 10 16 24 40 51 61
12 12 14 19 26 58 60 55
14 13 16 24 40 57 69 56
14 17 22 29 51 87 80 62
18 22 37 56 68 109 103 77
24 35 55 64 81 104 113 92
49 64 78 87 103 121 120 101
72 92 95 98 112 100 103 99
Top-left values are small (16, 11, 10) — low-frequency coefficients are preserved with high precision. Bottom-right values are large (120, 103, 99) — high-frequency coefficients are aggressively rounded.
The quantization formula for each coefficient:
quantized[i][j] = round( DCT[i][j] / Q[i][j] )
Quality setting: JPEG's quality slider (1–100) simply scales this matrix. Lower quality = larger divisors = more coefficients round to zero = smaller file = more visible artifacts. At very low quality, only a handful of coefficients survive — the image looks blocky because each 8×8 block is being described by just a few smooth patterns.
Zigzag Scan
After quantization, the 8×8 coefficient matrix has many zeros, especially in the high-frequency positions (lower-right). To exploit this, JPEG reads the coefficients in zigzag order — a path that traverses from low frequency (top-left) to high frequency (bottom-right).
The Zigzag Path
0 → 1 5 → 6 14 →15 27 →28
↙ ↗ ↙ ↗ ↙ ↗ ↙
2 4 7 13 16 26 29 42
↓ ↗ ↙ ↗ ↙ ↗ ↙ ↗ ↓
3 8 12 17 25 30 41 43
↙ ↗ ↙ ↗ ↙ ↗ ↙
9 11 18 24 31 40 44 53
↓ ↗ ↙ ↗ ↙ ↗ ↙ ↗ ↓
10 19 23 32 39 45 52 54
↙ ↗ ↙ ↗ ↙ ↗ ↙
20 22 33 38 46 51 55 60
↓ ↗ ↙ ↗ ↙ ↗ ↙ ↗ ↓
21 34 37 47 50 56 59 61
↙ ↗ ↙ ↗ ↙ ↗ ↙
35 36 48 49 57 58 62 63
Reading positions 0, 1, 2, 3, 4, 5, 6, 7, 8, ... traces a zigzag from the DC coefficient at position 0 down to the highest-frequency coefficient at position 63.
Why zigzag?
After quantization, a typical block might produce something like:
Zigzag order: [18, -1, 1, 0, -1, 0, 0, 0, 0, 0, 0, ..., 0]
The non-zero values cluster at the start (low frequencies) and the tail is a long run of zeros. Run-length encoding collapses that tail efficiently: instead of storing 50+ individual zeros, you store a single "end of block" marker.
Putting It All Together: JPEG Pipeline
-
Color convert (RGB → YCbCr)
Separate luminance (brightness) from chrominance (color). The eye is more sensitive to brightness, so chrominance channels can be compressed more aggressively.
-
Chroma subsampling
Reduce the resolution of the color channels (typically 4:2:0 — quarter the color data). This alone cuts the data by half, with negligible visual impact.
-
Split into 8×8 blocks
Divide each channel into non-overlapping 8×8 pixel blocks. Each block is processed independently.
-
DCT
Apply the 2D DCT to each block, converting spatial pixel values into 64 frequency coefficients.
-
Quantize
Divide each coefficient by the corresponding entry in the quantization matrix and round. This is the lossy step — information is permanently discarded here.
-
Zigzag scan
Read the 64 quantized coefficients in zigzag order, grouping the zeros at the end.
-
Run-length encoding
Encode runs of zeros compactly. Each non-zero AC coefficient is preceded by a count of the zeros before it.
-
Huffman coding
Encode the RLE symbols with variable-length prefix codes. Common patterns get shorter codes.
Decompression runs this pipeline in reverse: Huffman decode → undo RLE → un-zigzag → dequantize (multiply back by Q matrix) → inverse DCT → reassemble blocks → convert YCbCr back to RGB. The dequantized coefficients are only approximate (the rounding was irreversible), which is why the reconstructed image isn't perfectly identical to the original.
DCT vs DFT
DFT (Discrete Fourier Transform)
- Produces complex coefficients (real + imaginary parts)
- Assumes signal is periodic — creates artificial discontinuities at block boundaries
- Requires 2N real numbers to represent N complex coefficients
DCT (Discrete Cosine Transform)
- Produces real coefficients only — simpler and more efficient to work with
- Implicitly mirrors the signal at boundaries — no discontinuities, smoother behavior
- Slightly better energy compaction for typical images (more energy in fewer coefficients)
The DCT's boundary behavior is why it wins for image compression. When the DFT treats a block as periodic, the left edge often doesn't match the right edge, creating a spurious discontinuity that wastes high-frequency coefficients. The DCT's implicit mirroring avoids this entirely, concentrating energy more tightly in the low-frequency coefficients.
Beyond JPEG: DCT in Video
JPEG compresses individual frames, but video codecs take the idea much further. H.264, H.265 (HEVC), and AV1 all use DCT-like transforms at their core, with important refinements:
- Integer transforms — instead of exact cosine values, they use integer approximations. This ensures encoder and decoder produce bit-identical results (no floating-point rounding mismatches).
- Variable block sizes — not just 8×8. Modern codecs use 4×4, 8×8, 16×16, and 32×32 blocks (H.265 goes up to 32×32; AV1 up to 64×64). Larger blocks for smooth regions, smaller blocks for detailed areas.
- Motion compensation — video codecs predict each block from nearby frames. The DCT is applied to the residual (the difference between prediction and reality), which tends to be small and compresses extremely well.
Where the DCT Is Used
| Format | Domain | DCT Variant |
|---|---|---|
| JPEG | Still images | 8×8 DCT-II (floating point) |
| MPEG-1 / MPEG-2 | Video (DVD, broadcast TV) | 8×8 DCT |
| H.264 / AVC | Video (Blu-ray, streaming) | 4×4 and 8×8 integer DCT |
| H.265 / HEVC | Video (4K streaming) | 4×4 to 32×32 integer DCT |
| HEIF | Still images (iPhone photos) | Uses H.265 intra-frame coding internally |
| MP3 / MPEG Audio | Audio | Modified DCT (MDCT) on overlapping windows |
The DCT family is arguably the most impactful algorithm in media compression. Virtually every photo you've viewed online, every video you've streamed, and every song you've played uses some form of it.
Key Takeaways
- The DCT converts spatial pixel data into frequency coefficients, concentrating most of the image's energy into a few low-frequency values
- High-frequency coefficients (fine detail) are small and can be aggressively quantized with little visible impact — this is the core of lossy compression
- JPEG processes images in 8×8 blocks: DCT → quantize → zigzag → RLE → Huffman
- The quantization matrix controls quality: larger divisors for high frequencies mean more zeros, smaller files, and more artifacts
- The DCT beats the DFT for this task because it uses only real numbers and handles block boundaries more gracefully
- The same idea extends to video (H.264, H.265, AV1) with integer transforms, variable block sizes, and motion-compensated prediction
Try It Yourself — DCT & Quantization
Enter 8 values below to see the full 1D DCT pipeline: transform, quantize, and reconstruct. Drag the quality slider to watch coefficients get zeroed out and the reconstruction degrade.
Original Values
DCT Coefficients
Quantized Coefficients
Reconstructed Values
Compression Statistics
The DCT is where information theory meets human perception. Unlike the lossless algorithms earlier in this series, JPEG deliberately throws away data — but it throws away the right data, the parts your eyes won't miss. The quantization matrix is tuned to the limits of human vision, and the DCT is what makes that selective discarding possible by cleanly separating "what matters" from "what doesn't." Every time you take a photo, share an image, or stream a video, this 1970s piece of mathematics is doing the heavy lifting.