Kolton Ndoj

JPEG: your photos are secretly made of waves

Every photo you take, send or scroll past on the web

What problem does it solve?

How can a photo shrink to a tenth of its size and still look almost the same?

The big idea

JPEG cuts the image into 8×8 tiles and rewrites each tile as a mix of 64 checkerboard-like wave patterns, from smooth (one flat colour) to finely striped. That rewrite is the Discrete Cosine Transform, a close cousin of the Fourier transform that uses only cosines. Here's the aha: in a real photo almost all the energy sits in the few smooth patterns, and your eyes barely notice errors in the fine stripes. So JPEG rounds the fine-stripe amounts coarsely, often to zero, and the long runs of zeros compress beautifully.

How it works, step by step

  1. 1. Convert colour to brightness plus two colour channels, and usually store the colour at half resolution, since eyes are less sharp for colour.
  2. 2. Cut each channel into 8×8 blocks.
  3. 3. Apply the DCT: express each block as amounts of 64 cosine patterns.
  4. 4. Quantize: divide each amount by a number (bigger for fine patterns) and round. This is where detail is thrown away.
  5. 5. Read the amounts in a zigzag from smooth to fine, and pack the many zeros with run-length and Huffman coding.

The key formula

Xk=∑n=0N−1xncos⁡ ⁣[πN(n+12)k]X_k=\sum_{n=0}^{N-1} x_n\cos\!\left[\frac{\pi}{N}\left(n+\tfrac12\right)k\right]
xnx_n
the brightness of pixel n along a row of the block (N = 8)
kk
which wave pattern: 0 is flat, 7 is the finest stripes
XkX_k
how much of pattern k the row contains
cos⁡[⋯ ]\cos[\cdots]
the k-th cosine wave sampled at the 8 pixel centres; JPEG does this across rows and down columns

How fast is it?

Fast-Fourier-style tricks make the DCT cheap, and phones have hardware for it. Typical compression is around 10:1 with little visible loss. It's lossy: the rounding step can't be undone, and at high compression you see blocky 8×8 tiles and 'ringing' around sharp edges.

Graph for JPEG: your photos are secretly made of waves -0.57.51.2-1.2
The k-th JPEG cosine pattern along one row of 8 pixels; the samples are taken at t = 0, 1, …, 7. Pattern 0 is flat, pattern 7 alternates almost pixel by pixel. Every row of an 8×8 block is a mix of these 8 waves. (drawn with the default slider values — move the sliders live)

Try it yourself

Fun fact

The DCT was invented by Nasir Ahmed, with T. Natarajan and K. R. Rao, in 1974, and Ahmed has said his grant proposal for it was originally rejected as too simple. JPEG became a standard in 1992, and the same cosine idea lives on inside video formats.

Related

Open it in the Math Lab →

Media · Stretch