Ch. 4 · Image Codecs

한국어日本語
6 min

JPEG Zig-Zag Scan, Run-Length Encoding and EOB Explained

Why does JPEG read its 64 DCT coefficients in zig-zag order? See how the scan creates long runs of zeros that RLE and Huffman coding squeeze into a few bits.

Before JPEG hands the 64 quantized coefficients of an 8×8 DCT block to entropy coding, it has to flatten the 2D array into a 1D sequence. It does not simply read row by row (row-major). It reads in zig-zag order.

Zig-zag from low frequency (top left) to high frequency (bottom right) Coefficients of similar size (mostly 0) end up next to each other
Zig-zag scan — sweeping diagonally from low frequencies (top-left) to high frequencies (bottom-right)
Why this order helps compression

As you learned in Chapter 3, DCT coefficients have their energy concentrated at low frequencies and fall toward 0 as frequency rises. Reading in zig-zag order puts the large coefficients first and the near-zero ones last, which creates long runs of zeros. Compress those runs with RLE (Run-Length Encoding) and 'twelve zeros in a row' can be expressed in just a few bits.

Combining RLE and Huffman

JPEG groups the coefficients into (run, value) pairs, meaning 'this many zeros, then this value', and Huffman-codes those pairs. If all the remaining coefficients are zero, a single EOB (End Of Block) symbol covers the rest of the block.

StepExample
Original zig-zag order15, 3, 0, 0, -2, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, ...
After RLE(0,15) (0,3) (2,-2) (4,1) EOB
Huffman codingEach (run,size) combination is assigned a predefined short code

At higher quality (lower QP) there are more nonzero coefficients, so the EOB comes later. At lower quality the EOB comes sooner and the file gets smaller.

In practice — this idea is still in use

The combination of zig-zag scan + RLE + entropy coding survives almost unchanged in CAVLC in H.264. The coefficient coding based on CABAC in HEVC and adaptive arithmetic coding in AV1 is more sophisticated (for example, it adapts the diagonal scan direction to the block content), but the underlying principle is the same: 'put large coefficients first and zeros last to maximize the runs'.

Zig-zag scanZig-zag scan

The order that unfolds 2D DCT coefficients into 1D from low frequency to high frequency.

RLERun-length encoding

A technique that compresses runs of the same value (especially 0) into a count.

EOBEnd of block

End Of Block. A special symbol signaling that all remaining coefficients are zero.

CAVLCContext-adaptive variable-length coding

Context-Adaptive Variable-Length Coding. H.264's method of coding the runs of zeros produced by RLE with Huffman-family codes chosen according to context.

Huffman codingHuffman coding

Lossless entropy coding that assigns a whole number of bits to each symbol according to its probability.

Check yourself

Why does zig-zag scanning help compression?