---
title: "Digital Images, Sound and Compression"
book: "High School Computer Science"
subject: computer-science
language: en
chapter: 6
exercises: 15
source: https://one-course.com/books/computer-science/2/en/chapter/6-digital-images-sound-and-compression
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 6 — Digital Images, Sound and Compression

Noor takes a photograph of the town square with her phone. The file on the phone weighs about $4$ MB. She sends the picture to a friend in a message, and the copy that arrives weighs about $300$ KB, more than ten times less; on the friend’s screen it looks the same. Something was thrown away on the way, and something else was packed more tightly.

![An illustration: taking a photograph of the market square, light becomes millions of numbers in a fraction of a second.](https://one-course.com/images/onecourse/chapters/computer-science-2/g10-images-sound-compression/img-3ed1e350baf8.jpg)

*An illustration: taking a photograph of the market square, light becomes millions of numbers in a fraction of a second.*

This chapter follows a picture and a sound from the world into numbers: how a sensor measures light, how a microphone signal becomes a list of samples, how big the raw numbers are, and the two ways of making them smaller, one that loses nothing and one that loses what the eye or the ear will not miss.

**You already know.**

An image on a screen is a grid of pixels, each with a red, a green and a blue value from $0$ to $255$ (Book 1, grade 5); a grid image can be stored as a plain-text file of numbers (Book 1, grade 9). The resolution of an image is its number of pixels across and down, and file sizes are counted in bytes, kilobytes and megabytes (Book 1, grade 4). The physics book describes sound as a vibration of the air and a signal as a quantity that varies with time (grade 10).

## 6.1 From a scene to pixels

A camera’s sensor is a grid of millions of tiny light detectors.

![The image sensor of a consumer digital camera, on its flexible circuit: the light falls on the rectangle in the middle. Photograph: C-M, CC BY-SA 3.0.](https://one-course.com/images/onecourse/chapters/computer-science-2/g10-images-sound-compression/img-a8e2d9d5d13e.jpg)

*The image sensor of a consumer digital camera, on its flexible circuit: the light falls on the rectangle in the middle. Photograph: C-M, CC BY-SA 3.0.*

**Definition 6.1 (Photosite).**

A *photosite* is one light-sensitive cell of a camera’s sensor. During the exposure it measures how much light falls on it, as a number. A photosite measures brightness only; to see colour, each one sits under a small red, green or blue filter and measures that colour alone.

The filters form a repeating mosaic, usually with two green filters for one red and one blue in each $2 \times 2$ block, because the eye is most sensitive to green. A [photosite](#def-g10-images-sound-compression-photosite) therefore knows one of the three colours of its pixel; the camera’s processor guesses the other two from the neighbours. This step is called *demosaicing*.

![A colour filter mosaic over 4 × 4 photosites, and the 3 × 3 neighbourhood used to give the blue photosite at row 1, column 1 its missing red and green.](https://one-course.com/images/onecourse/chapters/computer-science-2/g10-images-sound-compression/fig-5e23c54edbfc.svg)

*A colour filter mosaic over $4 \times 4$ [photosites](#def-g10-images-sound-compression-photosite), and the $3 \times 3$ neighbourhood used to give the blue [photosite](#def-g10-images-sound-compression-photosite) at row $1$, column $1$ its missing red and green.*

```python
# Each photosite measured one colour: R, G or B, in the pattern RG / GB.
MOSAIC = [[200, 120, 190, 118],
          [110, 60, 115, 64],
          [180, 125, 170, 130],
          [105, 58, 100, 62]]


def colour_of(r, c):
    if r % 2 == 0:
        return "R" if c % 2 == 0 else "G"
    return "G" if c % 2 == 0 else "B"


def average(values):
    return round(sum(values) / len(values))


def rgb_at(r, c):
    """(R, G, B) of photosite (r, c): its own value, its neighbours' averages."""
    found = {"R": [], "G": [], "B": []}
    for dr in (-1, 0, 1):
        for dc in (-1, 0, 1):
            rr, cc = r + dr, c + dc
            if 0 <= rr < 4 and 0 <= cc < 4 and (dr, dc) != (0, 0):
                found[colour_of(rr, cc)].append(MOSAIC[rr][cc])
    found[colour_of(r, c)] = [MOSAIC[r][c]]
    return tuple(average(found[k]) for k in "RGB")


for r in range(4):
    print("  ".join(f"{colour_of(r, c)}{MOSAIC[r][c]:>3}" for c in range(4)))
print("pixel (1, 1):", rgb_at(1, 1))
print("pixel (2, 2):", rgb_at(2, 2))
```

***Listing 6.1.** Demosaicing by averaging the neighbours. code/grade-10/06-images-sound-compression/listings/demosaic.py*

```
$ python demosaic.py
R200  G120  R190  G118
G110  B 60  G115  B 64
R180  G125  R170  G130
G105  B 58  G100  B 62
pixel (1, 1): (185, 118, 60)
pixel (2, 2): (170, 118, 61)
```

***Output 6.1.** The mosaic, each value with the colour it measured, and two pixels rebuilt.*

Real cameras use cleverer guesses than a plain average, but the principle is the same: two thirds of the colour values of a photograph were computed, not measured.

**Definition 6.2 (Colour depth).**

The *colour depth* of an image is the number of bits used for the colour of one pixel. With one byte for each of red, green and blue, it is $24$ bits, which gives $2^{24} = 16{,}777{,}216$ colours.

The raw size of an image follows: width times height times bytes per pixel.

```python
def raw_size(width, height, bytes_per_pixel=3):
    """Bytes of an uncompressed image: one value per colour per pixel."""
    return width * height * bytes_per_pixel


for width, height in ((640, 480), (1920, 1080), (4000, 3000)):
    size = raw_size(width, height)
    print(f"{width} x {height}: {width * height:>10,} pixels, {size:>10,} bytes"
          f" = {size / 2**20:.1f} MiB")
```

***Listing 6.2.** Raw sizes of three images. code/grade-10/06-images-sound-compression/listings/raw_size.py*

```
$ python raw_size.py
640 x 480:    307,200 pixels,    921,600 bytes = 0.9 MiB
1920 x 1080:  2,073,600 pixels,  6,220,800 bytes = 5.9 MiB
4000 x 3000: 12,000,000 pixels, 36,000,000 bytes = 34.3 MiB
```

***Output 6.2.** A $12$-megapixel photograph takes $36$ million bytes before any [compression](#def-g10-images-sound-compression-compression).*

So Noor’s $4$ MB file is already about nine times smaller than the raw $36$ MB of the image it holds.

## 6.2 Sound as numbers

A microphone turns the vibration of the air into an electric signal that varies continuously with time. A computer keeps only some values of it.

**Definition 6.3 (Sampling rate, bit depth).**

To *sample* a signal is to measure it at regular instants. The *sampling rate* is the number of measurements, or *samples*, per second, in hertz (Hz). Each sample is then rounded to one of a fixed number of levels, a step called *quantisation*; the *bit depth* is the number of bits used for one sample, so that there are $2^{\text{bit depth}}$ levels.

![A 440 Hz tone sampled 8000 times per second and quantised on 3 bits, that is 8 levels. Each dot is a stored sample; between two samples nothing is kept. With 16 bits the steps would be more than 9000 times finer.](https://one-course.com/images/onecourse/chapters/computer-science-2/g10-images-sound-compression/fig-4be3d3584f5c.svg)

*A $440$ Hz tone sampled $8000$ times per second and quantised on $3$ bits, that is $8$ levels. Each dot is a stored sample; between two samples nothing is kept. With $16$ bits the steps would be more than $9000$ times finer.*

The audio compact disc samples $44{,}100$ times per second with $16$ bits per sample. A stereo recording keeps two channels, one for each ear, so a second of it holds $44{,}100 \times 2 \times 2 = 176{,}400$ bytes. The listing writes one second of a tone at a smaller rate and depth, with Python’s `wave` module.

```python
import math
import wave
from pathlib import Path

RATE = 8000        # samples per second
FREQUENCY = 440    # hertz
samples = bytes(round(127.5 + 127 * math.sin(2 * math.pi * FREQUENCY * k / RATE))
                for k in range(RATE))

with wave.open("tone.wav", "wb") as w:
    w.setnchannels(1)
    w.setsampwidth(1)  # one byte per sample: 8 bits
    w.setframerate(RATE)
    w.writeframes(samples)

print("first samples:", list(samples[:10]))
size = Path("tone.wav").stat().st_size
print("file size:", size, "bytes for", len(samples), "samples")
```

***Listing 6.3.** One second of a $440$ Hz tone, $8$ kHz, $8$ bits. code/grade-10/06-images-sound-compression/listings/make_wav.py*

```
$ python make_wav.py
first samples: [128, 171, 208, 237, 252, 253, 239, 211, 174, 131]
file size: 8044 bytes for 8000 samples
```

***Output 6.3.** $8000$ samples of one byte, and $44$ bytes more for the file’s header.*

The values go up and down around $128$, the middle of a byte, once every $8000 / 440 \approx 18$ samples. A higher [sampling rate](#def-g10-images-sound-compression-sampling-rate) follows faster vibrations, which the ear hears as higher notes; the physics book explains why a rate of twice the highest frequency is needed.

## 6.3 Compression without loss

**Definition 6.4 (Compression, lossless, lossy).**

*Compression* encodes data in fewer bytes. It is *lossless* when decompression gives back exactly the original bytes, and *lossy* when it gives back only an approximation, chosen so that the difference is hard to notice.

**Definition 6.5 (Compression ratio).**

The *compression ratio* is the original size divided by the compressed size. A ratio of $4$ means the compressed data is four times smaller; a ratio below $1$ means it grew.

The simplest [lossless](#def-g10-images-sound-compression-compression) method works on data with long stretches of the same value, such as a map with a plain background.

**Definition 6.6 (Run-length coding).**

*Run-length coding* replaces each *run*, a maximal stretch of equal consecutive values, by the pair (length of the run, value).

![One row of 55 pixels of a map, white and black, and its five runs. Ten numbers describe 55 pixels.](https://one-course.com/images/onecourse/chapters/computer-science-2/g10-images-sound-compression/fig-64aede340371.svg)

*One row of $55$ pixels of a map, white and black, and its five runs. Ten numbers describe $55$ pixels.*

```python
import random


def rle_encode(s):
    """Return the list of (count, character) runs of the string s."""
    runs = []
    for ch in s:
        if runs and runs[-1][1] == ch:
            runs[-1] = (runs[-1][0] + 1, ch)
        else:
            runs.append((1, ch))
    return runs


def rle_decode(runs):
    return "".join(ch * count for count, ch in runs)


row = "WWWWWWWWWWBBBWWWWWWWWWWWWWWWWBBBBBBBBWWWWWWWWWWWWWWWWWW"
runs = rle_encode(row)
print(runs)
print(rle_decode(runs) == row, len(row), "characters,", len(runs), "runs")

rng = random.Random(7)
noise = "".join(rng.choice("WB") for _ in range(len(row)))
print(noise)
print(len(rle_encode(noise)), "runs for", len(noise), "characters")
```

***Listing 6.4.** [Run-length coding](#def-g10-images-sound-compression-rle), on a map row and on noise. code/grade-10/06-images-sound-compression/listings/rle.py*

```
$ python rle.py
[(10, 'W'), (3, 'B'), (16, 'W'), (8, 'B'), (18, 'W')]
True 55 characters, 5 runs
BWBWWWBWWWWBBWWWBWWWWBWWWWBBWWBWWWBWWWWBBBBBBBWWWWBBBBB
21 runs for 55 characters
```

***Output 6.4.** Five runs for the map row; $21$ for a random row of the same length.*

On noise the runs are short, and storing each one as a pair can take more room than the pixels themselves. How much a method compresses depends on the data, not only on the method.

The general-purpose compressors used for files, such as the DEFLATE method behind `zip` files and Python’s `zlib` module (described in 1996), go further: they replace a repeated sequence by a reference to its earlier occurrence, a *dictionary method*, and write frequent values with fewer bits than rare ones.

```python
import random
import zlib

samples = {
    "repeated text": b"the cat sat on the mat. " * 400,
    "zeros": bytes(10_000),
    "random bytes": random.Random(1).randbytes(10_000),
}
for name, data in samples.items():
    packed = zlib.compress(data, 9)
    same = zlib.decompress(packed) == data
    print(f"{name:14} {len(data):6} -> {len(packed):6} bytes"
          f"  ratio {len(data) / len(packed):7.1f}  same back: {same}")
```

***Listing 6.5.** `zlib` on three kinds of data. code/grade-10/06-images-sound-compression/listings/zlib_sizes.py*

```
$ python zlib_sizes.py
repeated text    9600 ->     73 bytes  ratio   131.5  same back: True
zeros           10000 ->     33 bytes  ratio   303.0  same back: True
random bytes    10000 ->  10011 bytes  ratio     1.0  same back: True
```

***Output 6.5.** Repetitive data shrinks a hundredfold; random bytes grow a little.*

**Proposition 6.7 (No lossless method shrinks everything).**

For every [lossless](#def-g10-images-sound-compression-compression) [compression](#def-g10-images-sound-compression-compression) method and every $n$, some file of $n$ bytes is not made shorter.

The proof is [Exercise 6.12](#exo-g10-images-sound-compression-12): it counts files. The random bytes of the listing are such files, and so, very nearly, are recordings of music, as the weekend problem shows.

## 6.4 Compression with loss

A photograph or a song does not have to come back bit for bit: it has to look or sound the same. [Lossy](#def-g10-images-sound-compression-compression) methods throw away what matters least: fine detail that the eye cannot see at the viewing size, sounds hidden by louder ones, and small differences of colour or loudness. The simplest of these steps uses fewer levels.

```python
def quantise(value, levels):
    """Round a grey value 0..255 to the nearest of `levels` evenly spaced values."""
    step = 255 / (levels - 1)
    return round(round(value / step) * step)


greys = list(range(256))
for levels in (256, 16, 8, 2):
    errors = [abs(g - quantise(g, levels)) for g in greys]
    step = 255 / (levels - 1)
    print(f"{levels:3} levels: step {step:6.2f}  largest error {max(errors)}")
print([quantise(g, 8) for g in (0, 20, 100, 128, 200, 255)])
```

***Listing 6.6.** Fewer grey levels. code/grade-10/06-images-sound-compression/listings/quantise.py*

```
$ python quantise.py
256 levels: step   1.00  largest error 0
 16 levels: step  17.00  largest error 8
  8 levels: step  36.43  largest error 18
  2 levels: step 255.00  largest error 127
[0, 36, 109, 146, 182, 255]
```

***Output 6.6.** With $8$ levels instead of $256$, each grey needs $3$ bits instead of $8$, and is off by at most $18$.*

![How a photograph file is made: a lossy step chooses what to forget, then a lossless step packs what is left. Sending a picture in a message usually repeats the lossy step more strongly.](https://one-course.com/images/onecourse/chapters/computer-science-2/g10-images-sound-compression/fig-53451909d740.svg)

*How a photograph file is made: a [lossy](#def-g10-images-sound-compression-compression) step chooses what to forget, then a [lossless](#def-g10-images-sound-compression-compression) step packs what is left. Sending a picture in a message usually repeats the [lossy](#def-g10-images-sound-compression-compression) step more strongly.*

**Method 6.8 (Choosing a kind of compression).**

1. Programs, text, tables and anything that must come back exactly: [lossless](#def-g10-images-sound-compression-compression) only.
2. Photographs, music and video meant for eyes and ears: [lossy](#def-g10-images-sound-compression-compression) , at a quality chosen for the use (a message, a print, an archive).
3. Never compress a [lossy](#def-g10-images-sound-compression-compression) file again and again with loss: each round loses a little more.

## 6.5 Metadata

**Definition 6.9 (Metadata).**

The *metadata* of a file is data about the data it holds: for an image, its width, height and [colour depth](#def-g10-images-sound-compression-colour-depth); for a sound, its [sampling rate](#def-g10-images-sound-compression-sampling-rate), [bit depth](#def-g10-images-sound-compression-sampling-rate) and number of channels; often also the date, the device and the place where it was made.

Every image or sound file starts with a *header* that holds the [metadata](#def-g10-images-sound-compression-metadata) a program needs to read the rest.

The simple PPM image format writes its header as text: the letters `P6`, the width, the height and the largest value. A WAV file, a format of 1991, starts with the four letters `RIFF`, then `WAVE` and a block named `fmt` that gives the channels, the [sampling rate](#def-g10-images-sound-compression-sampling-rate) and the [bit depth](#def-g10-images-sound-compression-sampling-rate).

```python
import wave
from pathlib import Path

pixels = bytes([255, 0, 0, 0, 255, 0, 0, 0, 255, 255, 255, 255])  # 2 x 2, RGB
Path("tiny.ppm").write_bytes(b"P6\n2 2\n255\n" + pixels)
data = Path("tiny.ppm").read_bytes()
magic, width, height, maxval = data.split(maxsplit=4)[:4]
print("PPM:", magic, int(width), int(height), int(maxval), len(data), "bytes")

with wave.open("click.wav", "wb") as w:
    w.setnchannels(2)
    w.setsampwidth(2)
    w.setframerate(44100)
    w.writeframes(bytes(4 * 441))
with wave.open("click.wav", "rb") as r:
    print("WAV:", r.getnchannels(), "channels,", 8 * r.getsampwidth(), "bits,",
          r.getframerate(), "Hz,", r.getnframes(), "frames")
print(Path("click.wav").read_bytes()[:16])
```

***Listing 6.7.** Writing two tiny files and reading their headers. code/grade-10/06-images-sound-compression/listings/read_header.py*

```
$ python read_header.py
PPM: b'P6' 2 2 255 23 bytes
WAV: 2 channels, 16 bits, 44100 Hz, 441 frames
b'RIFF\x08\x07\x00\x00WAVEfmt '
```

***Output 6.7.** $2 \times 2$ pixels take $12$ bytes and the PPM header $11$; the WAV file begins with its format’s name.*

**Safe use.**

A photograph taken with a phone usually carries, in its [metadata](#def-g10-images-sound-compression-metadata), the date, the model of the phone and often the exact position where it was taken. Before sharing a picture of a place that should stay private, such as your home, check what the file says about itself, or use a program or setting that removes the [metadata](#def-g10-images-sound-compression-metadata).

## 6.6 Exercises

**Exercise 6.1 ★.**

What is the raw size, in bytes and in MiB, of a $4000 \times 3000$ image with $3$ bytes per pixel? And of the same image in grey levels with one byte per pixel?

**Solution of Exercise 6.1.**

$4000 \times 3000 \times 3 = 36{,}000{,}000$ bytes, that is $36{,}000{,}000 / 2^{20} \approx 34.3$ MiB, as the listing printed. In grey levels, one byte per pixel: $12{,}000{,}000$ bytes, about $11.4$ MiB.

**Exercise 6.2 ★.**

How many bytes does one second of stereo sound take at $48{,}000$ samples per second and $16$ bits per sample? And one hour?

**Solution of Exercise 6.2.**

$48{,}000 \times 2 \times 2 = 192{,}000$ bytes per second. One hour: $3600 \times 192{,}000 = 691{,}200{,}000$ bytes, about $659$ MiB.

**Exercise 6.3 ★.**

What does `rle_encode("AAABCCCCD")` return? How many numbers and characters does the result hold, against the $9$ characters of the string?

**Solution of Exercise 6.3.**

`[(3, "A"), (1, "B"), (4, "C"), (1, "D")]` (Python prints the letters with single quotes): $4$ numbers and $4$ characters, $8$ values against $9$. Runs of length $1$ cost more than they save.

**Exercise 6.4 ★.**

Put these in order of compressed size with `zlib`, without running: $10{,}000$ copies of the letter `a`; a book chapter of $10{,}000$ characters; $10{,}000$ random bytes. Explain.

**Solution of Exercise 6.4.**

The $10{,}000$ letters `a` come out smallest, a few dozen bytes: the whole input is one repetition. The chapter’s text comes next, a few thousand bytes: words and spaces repeat, and some letters are much more frequent than others. The random bytes come out largest, a little more than $10{,}000$ bytes: there is nothing to exploit, and the format adds a few bytes of its own, as the listing showed.

**Exercise 6.5 ★.**

Write `rle_decode(runs)` without looking at the listing, and check that decoding an encoding gives back the string.

**Solution of Exercise 6.5.**

`return "".join(ch * count for count, ch in runs)`: each pair gives its character repeated `count` times, and the pieces are joined in order. The listing checks `rle_decode(rle_encode(row)) == row`; the chapter’s tests check it on $300$ random strings.

**Exercise 6.6 ★★.**

An encoder walks through the string with an index, counts equal neighbours, and appends a run each time the character changes. On `"WWB"` it returns `[(2, "W")]`. Find the bug and correct it; which strings does the buggy version handle correctly?

**Solution of Exercise 6.6.**

A run is appended only when the character changes, and the last run is followed by no change: it is never appended. After the loop, add the last run (`exercises/rle_bugs.py`):

    `if s: runs.append((count, s[-1]))`

The test on the empty string keeps an empty list. The buggy version is right only on the empty string: every other string has a last run.

**Exercise 6.7 ★★.**

Suppose a run is stored in $2$ bytes, one for the length and one for the value. Which row of $n$ pixels of one byte each makes the encoding as long as possible, and how long? When does [run-length coding](#def-g10-images-sound-compression-rle) pay?

**Solution of Exercise 6.7.**

The worst row has no two equal neighbours, such as `WBWBWB`: $n$ runs of length $1$, so $2n$ bytes, twice the row. The encoding is shorter exactly when there are fewer than $n/2$ runs, that is, when runs are on average longer than $2$ pixels: plain areas, drawings and maps, not photographs.

**Exercise 6.8 ★★.**

A plain PGM image is a text file: `P2`, the width, the height, the largest grey value, then the grey values. Write `histogram(text)`, which returns the list of the numbers of pixels of each grey level.

**Solution of Exercise 6.8.**

Split the text into words; check that the first is `P2`; read the width, height and largest value; take the next `width * height` words as whole numbers; count them in a list of `maxval + 1` zeros (`exercises/pgm_histogram.py`). For the image `P2 3 2 4` with values `0 1 1 4 4 4` it returns `[1, 2, 0, 0, 3]`.

**Exercise 6.9 ★★.**

Some screens store a colour in $16$ bits: $5$ for red, $6$ for green and $5$ for blue. How many colours is that? How many levels does each colour have, and why might green get the extra bit?

**Solution of Exercise 6.9.**

$2^{16} = 65{,}536$ colours. Red and blue have $2^5 = 32$ levels each, green $2^6 = 64$. The eye tells shades of green apart best, as the colour filter mosaic also reflects with its two green [photosites](#def-g10-images-sound-compression-photosite) in four, so the extra bit is best spent there.

**Exercise 6.10 ★★.**

A student changes the condition of the demosaicing listing to `0 <= rr <= 4 and 0 <= cc <= 4`. Which pixels does this break, and how?

**Solution of Exercise 6.10.**

With `<= 4`, the index $4$ is accepted, but the rows and columns are numbered $0$ to $3$. For every pixel in the last row or the last column, a neighbour at index $4$ is read, and `MOSAIC[4]` or `MOSAIC[r][4]` raises an `IndexError`: the program stops. The other pixels are unchanged. The condition must be `< 4`, or better `< len(MOSAIC)`.

**Exercise 6.11 ★★.**

Write `wav_duration(path)`, which returns the duration of a WAV file in seconds from the number of frames and the [sampling rate](#def-g10-images-sound-compression-sampling-rate) in its header. What is the duration of the tone of the listing?

**Solution of Exercise 6.11.**

Open the file with `wave.open(path, "rb")` and return `w.getnframes() / w.getframerate()` (`exercises/wav_duration.py`): a frame holds one sample per channel, so the number of frames per second is the [sampling rate](#def-g10-images-sound-compression-sampling-rate). The tone of the listing has $8000$ frames at $8000$ Hz: $1.0$ s.

**Exercise 6.12 ★★★.**

Prove the proposition that no [lossless](#def-g10-images-sound-compression-compression) method shrinks every file: count the files of exactly $n$ bytes, and the files of fewer than $n$ bytes, and use the fact that two different files must not be compressed to the same result.

**Solution of Exercise 6.12.**

There are $256^n$ files of exactly $n$ bytes, and $1 + 256 + 256^2 + \dots + 256^{n-1}$ files of fewer than $n$ bytes. Multiplying this sum by $256 - 1$ gives $256^n - 1$, since all the other terms cancel; so the sum is $(256^n - 1)/255$, less than $256^n$. A [lossless](#def-g10-images-sound-compression-compression) method must send two different files to two different results, otherwise decompression could not tell which one to give back. If it made every file of $n$ bytes shorter, it would send $256^n$ different files into fewer than $256^n$ shorter files: two of them would share a result. So some file of $n$ bytes is not made shorter.

**Exercise 6.13 ★★★.**

Write `bitmap_ratio(rows)` for a black-and-white bitmap given as a list of strings of `W` and `B`: it returns the number of pixels, the number of runs over all rows, and the ratio when each run costs as much as two pixels. Try it on a bitmap of your own with large plain areas, and on a chessboard.

**Solution of Exercise 6.13.**

`bitmap_ratio` adds the lengths of the rows and the numbers of runs of each row, and returns the pixels divided by twice the runs (`exercises/rle_bitmap.py`). On a map with large plain areas the ratio is well above $1$. On an $8 \times 8$ chessboard every pixel is a run: $64$ pixels, $64$ runs, a ratio of $0.5$, the worst case of [Exercise 6.7](#exo-g10-images-sound-compression-7).

**Exercise 6.14 ★★★.**

Prove that rounding a grey value to the nearest of evenly spaced levels with step $s$ makes an error of at most $s/2$. Check it against the output of the quantisation listing for $16$ and $8$ levels.

**Solution of Exercise 6.14.**

The levels are $0, s, 2s, \dots$. A grey value $v$ lies between two neighbouring levels $ks$ and $(k + 1)s$, so its distances to them add up to $s$; the smaller of the two is at most $s/2$, and rounding picks the nearer level. In the listing the levels are also rounded to whole numbers, which can add up to $\tfrac12$. For $16$ levels, $s = 17$ and the largest error printed is $8 \le 8.5$; for $8$ levels, $s \approx 36.43$ and the largest error is $18 \le 18.2$.

**Exercise 6.15 ★★★.**

A tone of $7000$ Hz is sampled $8000$ times per second. Count, in the samples, how many times per second the signal goes from negative to non-negative. What frequency does the recording seem to have? Explain with the positions of the samples on the wave (this effect is called *aliasing*).

**Solution of Exercise 6.15.**

The count gives $1000$ crossings per second (`exercises/aliasing.py`): the recording seems to be a $1000$ Hz tone. Between two samples the $7000$ Hz wave makes $7000/8000 = \tfrac78$ of a turn, which lands at the same place as going back $\tfrac18$ of a turn. The samples therefore trace a wave that goes back one eighth of a turn per sample, one turn every $8$ samples: $8000 / 8 = 1000$ turns per second. The samples cannot tell the two waves apart, which is why the [sampling rate](#def-g10-images-sound-compression-sampling-rate) must be more than twice the highest frequency kept.

## 6.7 Problem: A Minute of Music

**Problem 6.1.**

Weekend problem — why music files hardly shrink with a general-purpose compressor

A disc-quality recording uses the compact disc’s [sampling rate](#def-g10-images-sound-compression-sampling-rate) and [bit depth](#def-g10-images-sound-compression-sampling-rate), in stereo. The program `exercises/minute_of_music.py` computes its size and compresses one second of synthetic music, made of three tones and a little noise, and one second of silence.

**Part I — The format.**

1. Give the [sampling rate](#def-g10-images-sound-compression-sampling-rate) and the [bit depth](#def-g10-images-sound-compression-sampling-rate) of the compact disc.
2. How many levels can one sample take?
3. How many samples does one second of stereo hold?
4. How long is the gap between two samples of one channel, in microseconds?

**Part II — Bytes per second and per minute.**

5. Compute the number of bytes per second.
6. Compute the number of bytes per minute.
7. Convert it to MiB ( $1$ MiB $= 2^{20}$ bytes) and to MB ( $10^6$ bytes).
8. What is the bit rate, in bits per second?

**Part III — A song and an album.**

9. What is the raw size of a song of $3$ minutes $30$ seconds?
10. How many such songs fit in $1$ GB ( $10^9$ bytes)?
11. A WAV file adds a header of $44$ bytes. By what fraction does it change the size of the song?
12. A music service sends the same song at $160{,}000$ bits per second. What is its [compression ratio](#def-g10-images-sound-compression-ratio) against the raw recording?
13. Is that [compression](#def-g10-images-sound-compression-compression) [lossy](#def-g10-images-sound-compression-compression) or [lossless](#def-g10-images-sound-compression-compression) ? Use the proposition of this chapter and Part IV to argue.

**Part IV — Compressing samples.**

14. Run the program. How many runs does one second of music have, against how many bytes? What would [run-length coding](#def-g10-images-sound-compression-rle) do to it?
15. What ratio does `zlib` reach on the music, and on the silence?
16. Why are the bytes of music so different from one to the next, even for a smooth tone? Think of what a $16$ -bit sample’s low byte holds.
17. Why does the silence compress so well?
18. A recording has a long silence at the end. Explain why [lossless](#def-g10-images-sound-compression-compression) [compression](#def-g10-images-sound-compression-compression) of the whole file still gains a little.
19. State the result: the size of one minute of disc-quality stereo, in bytes and in MiB, and the ratio that `zlib` reaches on music against silence.

**Solution of Problem 6.1.**

**1.** $44{,}100$ samples per second, $16$ bits per sample.

**2.** $2^{16} = 65{,}536$ levels.

**3.** $2 \times 44{,}100 = 88{,}200$ samples.

**4.** $1/44{,}100$ s $\approx 22.7$ µs.

**5.** $88{,}200 \times 2 = 176{,}400$ bytes per second, as the program prints.

**6.** $60 \times 176{,}400 = 10{,}584{,}000$ bytes.

**7.** $10{,}584{,}000 / 2^{20} \approx 10.09$ MiB, and $10.584$ MB.

**8.** $8 \times 176{,}400 = 1{,}411{,}200$ bits per second.

**9.** $210 \times 176{,}400 = 37{,}044{,}000$ bytes, about $35.3$ MiB.

**10.** $10^9 / 37{,}044{,}000 \approx 26.99$: $26$ whole songs.

**11.** $44 / 37{,}044{,}000 \approx 1.2 \times 10^{-6}$, about a millionth: nothing.

**12.** $1{,}411{,}200 / 160{,}000 = 8.82$.

**13.** [Lossy](#def-g10-images-sound-compression-compression). Part IV measures a [lossless](#def-g10-images-sound-compression-compression) ratio of about $1.09$ on this music with `zlib`, nowhere near $8.82$. Methods built for sound do better by predicting each sample from the ones before, but still nowhere near $8.82$; and the proposition says that no [lossless](#def-g10-images-sound-compression-compression) method shrinks every file. The service throws away what the ear hardly notices.

**14.** $175{,}662$ runs for $176{,}400$ bytes: almost every byte is a run of its own. [Run-length coding](#def-g10-images-sound-compression-rle) with two bytes per run would nearly double the size, to about $351{,}000$ bytes.

**15.** About $1.09$ on music ($161{,}664$ bytes) and about $909$ on silence ($194$ bytes).

**16.** A sample is stored in two bytes, the low byte first. The low byte holds the finest $\tfrac{1}{256}$ of the amplitude: even a smooth tone moves by hundreds of levels from one sample to the next, and the small noise changes it at random. The bytes of the two channels and of the two halves of each sample also alternate. Seen as a sequence of bytes, the music looks almost random.

**17.** Every byte is $0$: one run of $176{,}400$ bytes, which a dictionary method describes in a few references to what it has just written.

**18.** The silent part compresses as well as the silence of Part IV, so the file shrinks by roughly the length of that silence; the music before it hardly shrinks at all.

**19.** One minute of disc-quality stereo is $44{,}100 \times 2 \times 2 \times 60 = 10{,}584{,}000$ bytes, about $10.1$ MiB. A general-purpose [lossless](#def-g10-images-sound-compression-compression) compressor, `zlib`, reaches a ratio of only about $1.09$ on this music, against about $909$ on silence: seen as bytes, the samples look nearly random. Compressors made for sound predict each sample and do better, but not by a factor of eight: that is why music files are made small with [lossy](#def-g10-images-sound-compression-compression) methods.
