10. Lossy Compression

Throwing away what you can't perceive

Everything we've covered so far has been lossless compression: the decompressed output is identical to the original input, bit for bit. Lossless is essential when every bit matters — source code, databases, executables. Flip one bit and the program crashes.

But most of the data humans actually consume — photos, music, video — doesn't need to be perfect. It just needs to look right or sound right. Lossy compression throws away information you probably won't notice, and in exchange it achieves compression ratios that lossless methods can't touch. A WAV file is 10 MB; the MP3 is 1 MB. A raw image is 25 MB; the JPEG is 2 MB. Same perceived quality, a fraction of the size.

Why Lossy Works: Human Perception

Lossy compression isn't magic — it's biology. Our senses have hard limits, and lossy codecs are engineered to exploit them.

The Perception Gap

There is a gap between what's in the data and what we actually perceive. Our eyes can't distinguish tiny color differences, especially in areas of high detail. Our ears can't hear a quiet tone when a loud tone at a nearby frequency is playing. Lossy compression lives in this gap — it discards the information that falls below the threshold of human perception.

The science behind this has specific names. Psychovisual modeling studies what the eye and brain can and can't see: we're more sensitive to brightness changes than color changes, more sensitive to low-frequency patterns (gradual gradients) than high-frequency ones (sharp edges in fine textures). Psychoacoustic modeling studies what the ear can and can't hear: a loud tone at 1 kHz makes a quiet tone at 1.1 kHz completely inaudible.

Every lossy codec is built on a model of human perception. The better the model, the more information it can throw away without you noticing.

The General Lossy Pipeline

Nearly all lossy compression follows the same three-stage pipeline. The details vary by format, but the structure is universal:

  1. Transform

    Convert the data into a domain where important and unimportant information are separable. For images, this typically means a frequency-domain transform like the DCT. For audio, sub-band decomposition or the MDCT. The raw pixels or samples are a tangled mix of perceptually important and unimportant data; the transform untangles them.

  2. Quantize

    Round the transformed values to reduce their precision. This is the step where information is permanently lost. Coarser quantization means smaller values (easier to compress) but more distortion. The key insight: you can quantize aggressively on the components humans can't perceive, and gently on the ones they can.

  3. Entropy Code

    Losslessly compress the quantized values using Huffman coding, arithmetic coding, or similar techniques. After quantization, many values are zero or small integers — highly compressible. This stage squeezes out the remaining statistical redundancy without any further loss.

Quantization: Where Information Dies

Quantization is the heart of lossy compression — the irreversible step. In its simplest form, scalar quantization, you divide each value by a step size and round to the nearest integer. To reconstruct, you multiply back. The result is close to the original but not exact.

Scalar Quantization Example

Original values:

[47, 52, 49, 103, 98, 101]

Quantize with step size 10 (divide, round):

[47/10, 52/10, 49/10, 103/10, 98/10, 101/10]
= [4.7,  5.2,   4.9,   10.3,   9.8,   10.1 ]
  round:
= [5,    5,     5,     10,     10,    10   ]

Reconstruct (multiply by step size):

[50, 50, 50, 100, 100, 100]

Compare to original: [47, 52, 49, 103, 98, 101] vs [50, 50, 50, 100, 100, 100]. Close, but not exact. The fine detail is gone — but we've collapsed six distinct values into just two (5 and 10), which are trivially easy to compress further.

Finer quantization (smaller step) = better quality, less compression. Coarser quantization (larger step) = worse quality, more compression. Every lossy format exposes this knob in some form — it's the "quality slider."

JPEG: Lossy Image Compression

JPEG (1992) is the most widely used image format in history. It follows the transform-quantize-encode pipeline with specific choices at each stage:

  1. Split into 8×8 blocks

    The image is divided into 8×8 pixel blocks, each processed independently.

  2. Color space conversion: RGB → YCbCr

    Separate brightness (Y) from color (Cb, Cr). Human vision is much more sensitive to brightness than to color, so the color channels can be downsampled (typically to half resolution) immediately — a 2:1 reduction on two of the three channels with barely visible effect.

  3. DCT (Discrete Cosine Transform)

    Each 8×8 block is transformed from spatial domain to frequency domain using the DCT. This concentrates the block's energy into a few low-frequency coefficients (top-left corner). High-frequency coefficients (bottom-right) represent fine detail and are often near zero.

  4. Quantization

    Each DCT coefficient is divided by a value from a quantization table and rounded. The table uses small divisors for low-frequency coefficients (preserving them) and large divisors for high-frequency coefficients (crushing them toward zero). This is where the quality setting takes effect.

  5. Zigzag scan

    The 8×8 block of quantized coefficients is read in a zigzag pattern from low-frequency to high-frequency. This clusters all the zeros (from the quantized high-frequency coefficients) at the end.

  6. RLE + Huffman coding

    Run-length encoding compresses the long runs of zeros, then Huffman coding encodes the remaining values. The result is a compact bitstream.

DCT Coefficients Before and After Quantization (8×8 block)

Before quantization (DCT output):

 415  -30  -61   27   56  -20   -2    0
  -4  -22   10  -14  -11   11    5   -6
 -47   -8   77  -24  -29   10    7   -5
  35   14  -10    6    2   -3    4   -2
  -7   -2    3    5   -6    2    0    1
  -4    3   -1   -2    0    4   -1    0
   1    2    0   -1    2    0   -2    1
  -1    0    1    0    0    0    0    0

After quantization (most high-frequency values → 0):

  26   -2   -5    2    3   -1    0    0
   0   -1    1   -1   -1    0    0    0
  -3    0    4   -1   -1    0    0    0
   2    1    0    0    0    0    0    0
   0    0    0    0    0    0    0    0
   0    0    0    0    0    0    0    0
   0    0    0    0    0    0    0    0
   0    0    0    0    0    0    0    0

The bottom-right half is entirely zeros. A zigzag scan through this block produces a short burst of meaningful values followed by a long run of zeros — exactly what RLE and Huffman handle efficiently.

MP3: Lossy Audio Compression

MP3 (MPEG-1 Audio Layer III, 1993) applies the same philosophy to sound: transform, model perception, quantize, encode. But instead of visual perception, it exploits psychoacoustic phenomena.

Psychoacoustic Masking

Frequency masking: A loud tone at one frequency makes quieter tones at nearby frequencies inaudible. A loud 1 kHz tone "masks" a quiet 1.1 kHz tone — your ear literally cannot hear it. No point encoding something nobody can hear.

Temporal masking: A loud sound masks quiet sounds that occur just before it (pre-masking, ~5 ms) and just after it (post-masking, ~100 ms). A cymbal crash hides subtle details in the moments surrounding it.

The MP3 pipeline: the audio signal is split into 32 sub-bands via a filter bank, then each sub-band is further decomposed using the MDCT (Modified Discrete Cosine Transform). A psychoacoustic model analyzes the signal in parallel, determining the masking threshold for each frequency band — the level below which sounds are inaudible. Bits are allocated to each band based on perceptual importance: bands where the signal is well above the masking threshold get more bits (finer quantization), bands near or below the threshold get fewer bits or none at all.

CD Audio (Uncompressed)

1,411 kbps

44,100 samples/sec × 16 bits × 2 channels

MP3 at 128 kbps

128 kbps — 91% smaller

Barely perceptible difference for most listeners

Video Compression: The Time Dimension

Video is a sequence of images — but compressing each frame independently as a JPEG would be enormously wasteful. Why? Because most of the time, consecutive frames are almost identical.

Temporal Redundancy

In a typical video, 95% or more of each frame is identical to the previous one. A talking head, a panning camera, a car driving by — most pixels barely change from frame to frame. Video codecs exploit this by encoding the differences between frames rather than the frames themselves.

Video codecs use three types of frames:

  • I-frames (Intra frames): Compressed independently, like a JPEG. These are the "keyframes" — reference points that don't depend on any other frame.
  • P-frames (Predicted frames): Encode only the differences from a previous frame. "This block is the same as before." "This block shifted 3 pixels right."
  • B-frames (Bidirectional frames): Can reference both previous and future frames. Even more efficient, at the cost of encoding complexity and latency.

The key technique is motion estimation: instead of encoding raw pixels, the encoder searches for matching blocks in reference frames and encodes a motion vector — "this 16×16 block moved 3 pixels right and 1 pixel down." Only the residual (the small difference between the predicted and actual block) needs to be transformed, quantized, and coded. The result: compression ratios of 100:1 or more with good visual quality.

Modern video codecs — H.264/AVC, H.265/HEVC, and AV1 — refine these ideas with variable block sizes, more sophisticated motion models, in-loop filtering, and better entropy coding. Each generation improves compression efficiency by roughly 30-50% over the last, at the cost of significantly more encoding compute.

Quality vs Size: The Tradeoff

High Quality (JPEG q=95)

Large file, nearly indistinguishable from original

Fine textures and subtle gradients preserved

Low Quality (JPEG q=10)

Tiny file, visible blocking and ringing artifacts

Only the coarse structure remains

This tradeoff is governed by rate-distortion theory: for any given bit rate (file size), there is a minimum achievable distortion, and vice versa. The curve is always convex — you get diminishing returns. The first 90% of quality comes cheaply. The last 10% costs disproportionately.

Measuring quality is its own challenge. PSNR (Peak Signal-to-Noise Ratio) is simple but doesn't correlate well with human perception — it treats all errors equally. SSIM (Structural Similarity Index) better captures perceived quality by comparing structure, luminance, and contrast. Modern codecs increasingly use perceptual metrics that model the human visual system directly, optimizing for what people actually see rather than what the math says.

JPEG Quality Settings — What Happens

QualityTypical SizeVisual Result
95~300 KBVirtually identical to original. Suitable for archiving.
80~120 KBSlight softening in fine detail. Good for web use.
50~60 KBNoticeable loss in textures. Acceptable for thumbnails.
10~15 KBHeavy blocking artifacts. 8×8 grid clearly visible.

(Sizes are approximate for a typical 1024×768 photograph.)

Generational Loss

Re-Compression Destroys Quality

Every time you decompress and re-compress a lossy file, more information is lost. Open a JPEG, make a small edit, save as JPEG again — the quantization errors compound. After several cycles, blocking artifacts, color banding, and blurring become severe. This is generational loss, and it's the reason professionals work in lossless formats.

The professional workflow: shoot in RAW (camera sensor data, lossless), edit in a lossless format (TIFF, PNG, or the RAW file itself), and export to JPEG or WebP only as the final step. For audio: record in WAV or FLAC, edit losslessly, export to MP3 or AAC at the end. For video: edit in a lossless or near-lossless intermediate codec (ProRes, DNxHR), then export to H.264/H.265 for distribution. The lossy step happens once, at the very end.

Lossy Formats in the Real World

Format Type Typical Use Notes
JPEG Image Photographs, web images DCT-based, ubiquitous since 1992
WebP Image Web images Google format, ~30% smaller than JPEG at similar quality
AVIF Image Next-gen web images Based on AV1 video codec, excellent compression
MP3 Audio Music distribution Psychoacoustic model, 128-320 kbps typical
AAC Audio Streaming, Apple ecosystem Successor to MP3, better quality at same bitrate
Opus Audio VoIP, streaming, games State of the art, excellent at all bitrates
H.264 / AVC Video Streaming, Blu-ray Most widely deployed video codec
H.265 / HEVC Video 4K streaming, broadcast ~50% better compression than H.264
AV1 Video YouTube, Netflix Royalty-free, competitive with H.265

Key Takeaways

  • Lossy compression discards information that falls below the threshold of human perception — exploiting the gap between data and experience
  • The universal pipeline is Transform → Quantize → Entropy Code; quantization is the irreversible step
  • JPEG uses DCT to separate spatial frequencies, then aggressively quantizes high-frequency coefficients humans can't easily see
  • MP3 uses psychoacoustic masking to identify inaudible components, then allocates fewer bits to them
  • Video codecs add temporal prediction (I/P/B-frames and motion estimation) to achieve 100:1+ compression
  • Quality vs size is a fundamental tradeoff — the last 10% of quality costs disproportionately
  • Re-compressing lossy data causes generational loss — always work in lossless and export to lossy once at the end

Lossy compression is what makes modern media possible. Without it, a single minute of video would take gigabytes, streaming would be impractical, and your phone couldn't hold more than a handful of photos. The insight is simple but powerful: don't waste bits on things nobody will notice. By understanding human perception and exploiting its limits, lossy codecs compress data by orders of magnitude while preserving the experience.