Compression: JPEG and the DCT on 2-D blocks
About this lesson
Follow one real 8×8 block of a photo through a baseline JPEG encoder. The pixels are centred on zero, the 2-D discrete cosine transform (DCT) rewrites them as amounts of 64 cosine patterns, and almost all the energy lands in a few low-frequency values. Dividing by a quantization table and rounding turns 44 of the 64 values into zeros; that is where JPEG loses information. A zigzag read and Huffman codes then pack the block into 93 bits, about 5.3 times smaller than the raw 64 bytes, and the decoder brings it back with a mean error of 4.875 grey levels. Builds on four lessons of this course: Images as 2-D signals (sig-images), The DFT (sig-dft), Quantization and bit depth (sig-quantization) and Information and entropy (sig-entropy).
A photo is a grid of numbers
A greyscale photo stores one brightness per pixel, from 0 (black) to 255 (white): one byte each. Here is one 8×8 block of a photo, 64 pixels, 64 bytes. JPEG codes an image block by block.
one 8×8 block, 8-bit greyscale 0 = black ... 255 = white 64 pixels = 64 bytes = 512 bits row 0: 52 55 61 66 70 61 64 73 row 3: 63 58 71 122 154 106 70 69 an image is a 2-D signal: brightness as a function of (row, column)
Read the lesson step by step
A photo is a grid of numbers
A greyscale photo stores one brightness per pixel, from 0 (black) to 255 (white): one byte each. Here is one 8×8 block of a photo, 64 pixels, 64 bytes. JPEG codes an image block by block.
one 8×8 block, 8-bit greyscale 0 = black ... 255 = white 64 pixels = 64 bytes = 512 bits row 0: 52 55 61 66 70 61 64 73 row 3: 63 58 71 122 154 106 70 69 an image is a 2-D signal: brightness as a function of (row, column)Centre the values on zero
JPEG subtracts 128 from every pixel, so the values run from −128 to 127 and sit around zero. The top-left pixel 52 becomes −76. The block then goes to the DCT.
level shift (T.81 A.3.1): g − 2^(P−1), P = 8 bits g − 128 52 − 128 = −76 154 − 128 = 26 range 0 .. 255 -> −128 .. 127 mean of the shifted block: −51.9264 cosine patterns
The DCT (discrete cosine transform) treats a block as a mix of 64 fixed patterns. Pattern (u, v) is a cosine with u half-waves down and v across. (0, 0) is flat. Bigger u and v mean finer detail.
pattern (u, v) at pixel (x, y): cos((2x+1)·u·π/16) · cos((2y+1)·v·π/16) x, y, u, v = 0 .. 7 (0, 0): flat, the average brightness (0, 1): light to dark across, one half-wave (1, 0): the same, top to bottom (7, 7): a fine checkerboard like the DFT, but real cosines onlyThe DCT: how much of each pattern
For each pattern, multiply it by the block pixel by pixel and add up: one number F(u, v). That gives 64 numbers. F(0, 0) = −415.375 is 8 × the average, −51.92. Nothing is lost yet: the DCT can be undone exactly.
F(u,v) = ¼·C(u)·C(v)·Σx Σy (g−128)· cos((2x+1)uπ/16)·cos((2y+1)vπ/16) C(0) = 1/√2, C(u) = 1 for u > 0 F(0,0) = ⅛·Σ (g−128) = −3323 / 8 = 8 × the mean (−51.92) = −415.375 (the DC term) F(0,1) = −30.19 64 numbers in, 64 numbers out; the inverse DCT gives g back exactlyEnergy piles into one corner
Photos change slowly from pixel to pixel, so the low patterns do most of the work. F(0, 0) alone holds 86% of the energy (the sum of squares); the first 6 values in low-to-high order hold 90%. Fine-detail values are small.
energy = Σ F(u,v)² = Σ (g−128)² (the DCT is orthonormal: energy is kept) F(0,0) alone: 86% first 6, low to high: 90% plot: F in zigzag order k = 0 .. 63 (low frequency on the left) the tail on the right is near zeroQuantize: divide and round
Divide each F(u, v) by its entry in a table Q and round. Q is larger for fine detail, which the eye notices less. −415.375 / 16 rounds to −26. 44 of the 64 become 0. This is the step that loses information.
q(u,v) = round( F(u,v) / Q(u,v) ) Q = T.81 Table K.1 (example luminance table) F(0,0) = −415.375, Q = 16 -> −26 F(0,1) = −30.19, Q = 11 -> −3 non-zero after rounding: 20 of 64 zero: 44 many F values -> one q: no way backZigzag: the zeros line up
Read the 64 numbers in zigzag order, from low to high frequency. The non-zero values come first. After value number 26 (k = 25) every value is 0, so one end-of-block code replaces the last 38 zeros.
zigzag sequence (T.81 Figure 5): −26 −3 0 −3 −2 −6 2 −4 1 −3 1 1 5 1 2 −1 1 −1 2 0 0 0 0 0 −1 −1 then 38 zeros -> EOB non-zero values: 20 zeros before position 26: 6Huffman codes: 93 bits
Each value becomes a code; common ones get short codes. With JPEG's standard tables this block takes 93 bits, padded to 12 bytes, instead of 64 bytes: about 5.3 times smaller. File headers add more, shared by every block.
DC: minus the previous block's DC (none: 0) −26 -> size 5: 110 + 00101 AC: (zeros before, size) code + value bits (0,2) 01 00 (1,2) 11011 00 (0,2) 01 01 ... EOB 1010 93 bits -> 12 bytes: C5 4D 8B 0B 46 50 99 4B 02 1B D0 57Decoding: back to pixels
The decoder undoes each step: multiply q by Q, inverse DCT, add 128. The block comes back close, not exact: the mean error is 4.875 levels out of 255, the largest 15. Rounding threw that detail away.
F' = q × Q g' = inverse DCT(F') + 128, rounded, clamped to 0 .. 255 row 0 before: 52 55 61 66 70 61 64 73 row 0 after: 62 65 57 60 72 63 60 82 mean |error| = 4.875 largest |error| = 15The DCT in Python
In Python with numpy, the DCT is an 8×8 matrix C. F = C @ (g − 128) @ C.T gives all 64 values at once; np.round(F / Q) quantizes. F[0, 0] is −415.375 and q[0, 0] is −26, as in the figure.
import numpy as np # g, Q: 8×8 arrays of the block and table n = np.arange(8) k = np.outer(n, 2*n + 1) C = np.cos(k*np.pi/16) / 2 C[0] /= np.sqrt(2) F = C @ (g - 128) @ C.T q = np.round(F / Q) >>> print(F[0, 0].round(3)) -415.375 >>> print(int(q[0, 0]), int((q != 0).sum())) -26 20 (Python 3 with numpy; @ is matrix multiply)
5 quick questions
Choose one answer per question. You can change your choices before checking them.
01Which step of baseline JPEG throws information away?
The level shift, the DCT and Huffman coding can all be undone exactly. Rounding F/Q maps many different values to the same whole number, so the original cannot be recovered: Wallace calls quantization the principal source of lossiness.
02Every pixel of an 8×8 block is 128. What does the DCT give?
After the level shift every value is 128 − 128 = 0, and the DCT of an all-zero block is all zeros. (A flat block of 130 would give F(0, 0) = 8 × 2 = 16 and zeros elsewhere: a flat block only needs the (0, 0) pattern.)
03F(0, 1) = −30.19 and Q(0, 1) = 11. What is q(0, 1)?
−30.19 / 11 = -2.74, which rounds to −3. The decoder will use −3 × 11 = -33 instead of −30.19.
04Why does JPEG read the quantized values in zigzag order?
The zigzag runs from the (0, 0) corner to the (7, 7) corner. High-frequency values are usually zero after quantizing, so they form one long run at the end that a single end-of-block code replaces (here the last 38 values).
05Why are the entries of the quantization table larger towards the bottom-right?
The bottom-right patterns are the finest detail. T.81's example tables are based on psychovisual thresholding: larger steps where errors are least visible, so more of those values round to zero.
Glossary
- Block
- An 8×8 tile of pixels. Baseline JPEG transforms, quantizes and codes each block on its own.
- Level shift
- Subtracting 128 from 8-bit pixel values so they run from −128 to 127, centred on zero.
- DCT (discrete cosine transform)
- A transform that writes a block as a weighted sum of cosine patterns. JPEG uses the 8×8 2-D DCT-II; it can be undone exactly.
- DC and AC coefficients
- F(0, 0) is the DC coefficient, 8 times the block's mean (after the shift). The other 63 are AC coefficients, one per finer pattern.
- Energy compaction
- For smooth signals most of the sum of squares sits in a few low-frequency coefficients, so the rest are small.
- Quantization table Q
- 64 step sizes, one per coefficient. Each F(u, v) is divided by its step and rounded; larger steps keep less detail.
- Zigzag order
- The order that reads the 8×8 coefficients from lowest to highest spatial frequency.
- Huffman coding
- A lossless code that gives shorter bit patterns to more common symbols.
Notes and sources
- The 8×8 block, its DCT, the quantized values and the decoded block are the worked example of the Wikipedia "JPEG" article; every number here is recomputed by this lesson's model. The coded bits were checked against a real encoder (libjpeg-turbo through Pillow at quality=50, which uses Table K.1 unchanged): the same 12 bytes.
- Q is Table K.1 of ITU-T T.81, which says its example tables "are based on psychovisual thresholding". Encoders scale it with a quality setting. The Huffman tables are T.81's example tables K.3 and K.5.
- Colour JPEGs first convert RGB to brightness plus two colour channels (often stored at lower resolution) and code each the same way. The DC value is coded as the difference from the previous block; this block is the first, so the difference is the value itself.
- ITU-T Recommendation T.81 (1992) | ISO/IEC 10918-1: Digital compression and coding of continuous-tone still images (JPEG), Annexes A, F and K (W3C copy)
- G. K. Wallace, The JPEG Still Picture Compression Standard, IEEE Transactions on Consumer Electronics, 1992 (IJG copy)
- JPEG (Wikipedia): the 8×8 example block, its DCT, quantized and decoded values
- Discrete cosine transform (Wikipedia): Ahmed, Natarajan and Rao, 1974; energy compaction
- A. V. Oppenheim, R. W. Schafer, J. R. Buck, Discrete-Time Signal Processing (course text listed on MIT OCW 6.341 readings)
- MIT OpenCourseWare 6.003 Signals and Systems (D. Freeman, Fall 2011)
- NumPy documentation: numpy.matmul (the @ operator)
- NumPy documentation: numpy.round (halves round to even)
- Pillow documentation: JPEG quality and optimize options
Quiz Unlocks after the last step.