A photograph in layers.

The last chapter took a line apart into an outline plus layers of finer and finer detail. A photograph comes apart the same way. Once it has, three useful things become possible: you can adjust the picture one size of detail at a time, store it in a fraction of the space, and remove grain without blurring the edges.

Broad shapes and fine detail

A stereo with tone controls splits music by pitch. One slider sets the bass, another sets the treble, and a few more handle the range in between. Turn the treble down and the cymbals fade, while the bass line carries on exactly as before.

A wavelet transform gives a picture the same kind of controls, with size in place of pitch. It splits a photograph into a base picture, which holds only the broadest shapes, and a set of detail layers. One layer holds features about sixteen pixels across. The next holds features half that size, the next half again, and the finest layer holds whatever changes from one pixel to its neighbor. Add the base and all four layers back together and the result is the original photograph, exactly, down to the last pixel.

Each slider below sets how much of one layer goes into the rebuilt picture. Drag the divider on the picture to compare the rebuilt version with the original.

how much of each layer

Each small picture shows one layer by itself. In a detail layer, flat gray means the layer adds nothing at that spot, and lighter or darker marks are what it adds or takes away. Press one to see that layer alone.

Start by sliding the finest layer down to zero. The stars and the thinnest ripples disappear, and almost nothing else changes, because nothing else in the picture is that small. Now try the opposite, and push the two finest layers toward 200%. Every small feature stands out harder. The sharpening and clarity controls in a photo editor work along these lines: they turn up some sizes of detail and leave the others alone.

The last slider is the base picture. Take it to zero and what remains is only the detail, drawn on gray. It looks like a pencil sketch of the scene, since the detail layers are where the edges live.

About the wavelet menu. The transform slides a small wave-shaped pattern across the picture to do the splitting, as chapter 6 showed, and the menu at the top of the page chooses which pattern. Symlet 4 is a good general choice and is the one selected. Haar is the simplest wavelet there is, a plain jump between two pixels, and it is worth trying in the next section for the blocky marks it leaves behind.

Throwing most of it away

On a computer screen the built-in pictures on this page are 640 pixels wide and 400 tall. That makes 256,000 pixels, each with three color numbers, or 768,000 numbers in all. (On a phone the page works on a smaller copy, so the counts below will be smaller.) After the split there are still exactly as many numbers as before, so nothing has been saved yet.

What has changed is that the numbers now differ greatly in size. Across the smooth parts of the picture, the open sky and the still water, the detail numbers come out very close to zero, because there is no detail there to record. The large numbers are few, and they gather along the edges and in the textured areas, where the detail is.

That suggests an experiment. Keep only the largest numbers, replace all the others with zero, and rebuild the picture from what is left. The slider sets what share of the numbers is kept.

where the kept numbers are

Every mark is a number that survived. They trace the outlines of things, and the smooth areas stay empty.

With the lake picture and one number in ten kept, most people cannot tell the two halves apart. With one in fifty, the fine texture has gone soft, but every edge is still in its place. Now press "the same count of plain pixels." The left half becomes what you would get by spending the same amount of storage in the obvious way, as a smaller picture enlarged back to full size. The wavelet version holds up far better, because it spends its numbers where the picture needs them.

This experiment is the core of a real compression method, and one of its first large uses was at the FBI. By the early 1990s the Bureau held some 200 million fingerprint cards, inked on paper and stored in filing cabinets. It wanted them on computers. A single card, scanned finely enough to show the ridges properly, takes about ten megabytes, so the whole collection would have needed about two million gigabytes at a time when a large hard disk held one. The usual way of compressing photographs made things worse, because it cut each picture into small square blocks, and at the compression the FBI needed the blocks began to show and broke up the ridge lines that examiners depend on.

In 1993 the Bureau settled on a wavelet method instead. It stores a print in about one fifteenth of the space, and what it loses is spread thinly over the picture instead of landing on the ridges. A few years later the same idea became a general standard called JPEG 2000, which is how films are delivered to digital cinemas.

The fingerprint pattern in the picture menu is there so you can try the experiment on that kind of picture. You will find it a much harder case than the lake. Ridges cover nearly all of it, so there are few smooth areas to save on, and the picture starts to suffer much sooner. That is why the FBI's method does more than drop the small numbers, as the note below explains.

What a real compressor adds. Throwing away the small numbers is where most of the saving comes from, and a real method does two more things. It rounds the numbers it keeps, coarsely in the layers where the eye is forgiving and finely in the layers that matter, and it packs the result so that long runs of zeros take almost no room. Both standards above use a wavelet designed by Albert Cohen, Ingrid Daubechies and Jean-Christophe Feauveau. It is a relative of the symlets on this page, and it is exactly symmetrical.

Removing grain

The grain in a film photograph, and the speckle in a digital photograph taken in dim light, are random. They change from one pixel to the next with no pattern at all. Two things follow once such a picture is split into layers. First, nearly all of the grain lands in the finest layers, because grain is small. Second, within those layers it is spread evenly, as a small random number added everywhere.

The real content of the picture behaves in the opposite way, as the last section showed. It is concentrated in a few large numbers along the edges. That difference gives a simple rule for telling the two apart: a small detail number is probably grain, and a large one is probably picture. So set the small ones to zero, keep the large ones, and rebuild. In 1994 two statisticians at Stanford, David Donoho and Iain Johnstone, showed how well this plain rule works and how to choose the cutoff between small and large.

Below, the page first adds grain to the picture, so that it knows what the clean version looked like and can measure how close the cleanup gets. The strength slider sets the cutoff. It is applied in full to the finest layer and eased in each broader layer, because the broad layers hold very little of the grain and a great deal of the picture.

18
40

Take the strength down to zero and raise it slowly. First the grain in the sky melts away while the ridge lines and the mast stay sharp. Keep going and the cleanup begins to eat real detail: the stars go, and then the ripples. The number under the picture tells the same story. It falls, reaches a lowest point, and climbs again. That lowest point is the best this method can do for this picture, and hunting for it by eye is what a photographer does with the noise slider in an editor.

Then switch the method to a plain blur and try to do as well. A blur hides grain too, since it is an average, but it has no way to tell grain from edges, and it softens both. On the lake the two methods finish fairly close, because most of that picture is smooth sky and water, where a blur does no harm. The eye chart is the sterner test. It is edges from top to bottom, and there the blur's number stays far higher. The wavelet method can tell grain from an edge because an edge is a large number, and a large number survives the cutoff.

The program

The wavelet transform is built into the numerical libraries of most programming languages, so for real work people call the library. Chapter 6 shows its inner loop. With a library, everything on this page comes down to a few lines. This version is in Python and uses PyWavelets, the same library this site's own arithmetic is checked against.

import numpy as np
import pywt

def layers(img, wavelet="sym4", levels=4):
    """Split a picture into a base and detail layers. The base comes first."""
    return pywt.wavedec2(img, wavelet, mode="periodization", level=levels)

def keep_largest(coeffs, share):
    """Zero everything except the largest numbers. share=0.05 keeps 5 percent."""
    flat, where = pywt.coeffs_to_array(coeffs)
    cutoff = np.quantile(np.abs(flat), 1 - share)
    flat[np.abs(flat) < cutoff] = 0
    return pywt.array_to_coeffs(flat, where, output_format="wavedec2")

def remove_grain(coeffs, cutoff):
    """Pull every detail number toward zero by cutoff. Smaller ones become zero."""
    cleaned = [coeffs[0]]                       # the base is left alone
    for level in coeffs[1:]:
        cleaned.append(tuple(pywt.threshold(d, cutoff, mode="soft") for d in level))
    return cleaned

def rebuild(coeffs, wavelet="sym4"):
    return pywt.waverec2(coeffs, wavelet, mode="periodization")

# img is a 2-D array of brightness values, one number per pixel
parts = layers(img)
small = rebuild(keep_largest(parts, 0.05))
clean = rebuild(remove_grain(parts, 30.0))