এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: English।
High School Computer Science · শ্রেণি 10–12
6Digital Images, Sound and Compression
Noor takes a photograph of the town square with her phone. The file on the phone weighs about MB. She sends the picture to a friend in a message, and the copy that arrives weighs about 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.
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 to (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.
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 block, because the eye is most sensitive to green. A 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.
# 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))
$ 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)
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 bits, which gives colours.
The raw size of an image follows: width times height times bytes per pixel.
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")
$ 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
So Noor’s MB file is already about nine times smaller than the raw 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 levels.
The audio compact disc samples times per second with bits per sample. A stereo recording keeps two channels, one for each ear, so a second of it holds bytes. The listing writes one second of a tone at a smaller rate and depth, with Python’s wave module.
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")
$ python make_wav.py
first samples: [128, 171, 208, 237, 252, 253, 239, 211, 174, 131]
file size: 8044 bytes for 8000 samples
The values go up and down around , the middle of a byte, once every samples. A higher 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 means the compressed data is four times smaller; a ratio below means it grew.
The simplest lossless 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).
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")
$ python rle.py
[(10, 'W'), (3, 'B'), (16, 'W'), (8, 'B'), (18, 'W')]
True 55 characters, 5 runs
BWBWWWBWWWWBBWWWBWWWWBWWWWBBWWBWWWBWWWWBBBBBBBWWWWBBBBB
21 runs for 55 characters
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.
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}")
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
Proposition 6.7 (No lossless method shrinks everything)
For every lossless compression method and every , some file of bytes is not made shorter.
The proof is Exercise 6.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 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.
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)])
$ 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]
Method 6.8 (Choosing a kind of compression)
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; for a sound, its sampling rate, bit depth 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 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 and the bit depth.
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])
$ 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 '
Safe use
A photograph taken with a phone usually carries, in its 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.
6.6 Exercises
Exercise 6.1 ★
What is the raw size, in bytes and in MiB, of a image with bytes per pixel? And of the same image in grey levels with one byte per pixel?
Solution
Solution of Exercise 6.1.
bytes, that is MiB, as the listing printed. In grey levels, one byte per pixel: bytes, about MiB.
Exercise 6.2 ★
How many bytes does one second of stereo sound take at samples per second and bits per sample? And one hour?
Solution
Solution of Exercise 6.2.
bytes per second. One hour: bytes, about MiB.
Exercise 6.3 ★
What does rle_encode("AAABCCCCD") return? How many numbers and characters does the result hold, against the characters of the string?
Solution
Solution of Exercise 6.3.
[(3, "A"), (1, "B"), (4, "C"), (1, "D")] (Python prints the letters with single quotes): numbers and characters, values against . Runs of length cost more than they save.
Exercise 6.4 ★
Put these in order of compressed size with zlib, without running: copies of the letter a; a book chapter of characters; random bytes. Explain.
Solution
Solution of Exercise 6.4.
The 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 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
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 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
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 bytes, one for the length and one for the value. Which row of pixels of one byte each makes the encoding as long as possible, and how long? When does run-length coding pay?
Solution
Solution of Exercise 6.7.
The worst row has no two equal neighbours, such as WBWBWB: runs of length , so bytes, twice the row. The encoding is shorter exactly when there are fewer than runs, that is, when runs are on average longer than 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
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 bits: for red, for green and for blue. How many colours is that? How many levels does each colour have, and why might green get the extra bit?
Solution
Solution of Exercise 6.9.
colours. Red and blue have levels each, green . The eye tells shades of green apart best, as the colour filter mosaic also reflects with its two green photosites 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
Solution of Exercise 6.10.
With <= 4, the index is accepted, but the rows and columns are numbered to . For every pixel in the last row or the last column, a neighbour at index 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 in its header. What is the duration of the tone of the listing?
Solution
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. The tone of the listing has frames at Hz: s.
Exercise 6.12 ★★★
Prove the proposition that no lossless method shrinks every file: count the files of exactly bytes, and the files of fewer than bytes, and use the fact that two different files must not be compressed to the same result.
Solution
Solution of Exercise 6.12.
There are files of exactly bytes, and files of fewer than bytes. Multiplying this sum by gives , since all the other terms cancel; so the sum is , less than . A lossless 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 bytes shorter, it would send different files into fewer than shorter files: two of them would share a result. So some file of 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
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 . On an chessboard every pixel is a run: pixels, runs, a ratio of , the worst case of Exercise 6.7.
Exercise 6.14 ★★★
Prove that rounding a grey value to the nearest of evenly spaced levels with step makes an error of at most . Check it against the output of the quantisation listing for and levels.
Solution
Solution of Exercise 6.14.
The levels are . A grey value lies between two neighbouring levels and , so its distances to them add up to ; the smaller of the two is at most , and rounding picks the nearer level. In the listing the levels are also rounded to whole numbers, which can add up to . For levels, and the largest error printed is ; for levels, and the largest error is .
Exercise 6.15 ★★★
A tone of Hz is sampled 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
Solution of Exercise 6.15.
The count gives crossings per second (exercises/aliasing.py): the recording seems to be a Hz tone. Between two samples the Hz wave makes of a turn, which lands at the same place as going back of a turn. The samples therefore trace a wave that goes back one eighth of a turn per sample, one turn every samples: turns per second. The samples cannot tell the two waves apart, which is why the 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 and bit depth, 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.
- Give the sampling rate and the bit depth of the compact disc.
- How many levels can one sample take?
- How many samples does one second of stereo hold?
- How long is the gap between two samples of one channel, in microseconds?
Part II — Bytes per second and per minute.
- Compute the number of bytes per second.
- Compute the number of bytes per minute.
- Convert it to MiB ( MiB bytes) and to MB ( bytes).
- What is the bit rate, in bits per second?
Part III — A song and an album.
- What is the raw size of a song of minutes seconds?
- How many such songs fit in GB ( bytes)?
- A WAV file adds a header of bytes. By what fraction does it change the size of the song?
- A music service sends the same song at bits per second. What is its compression ratio against the raw recording?
- Is that compression lossy or lossless? Use the proposition of this chapter and Part IV to argue.
Part IV — Compressing samples.
- Run the program. How many runs does one second of music have, against how many bytes? What would run-length coding do to it?
- What ratio does
zlibreach on the music, and on the silence? - Why are the bytes of music so different from one to the next, even for a smooth tone? Think of what a -bit sample’s low byte holds.
- Why does the silence compress so well?
- A recording has a long silence at the end. Explain why lossless compression of the whole file still gains a little.
- State the result: the size of one minute of disc-quality stereo, in bytes and in MiB, and the ratio that
zlibreaches on music against silence.
Solution
Solution of Problem 6.1.
1. samples per second, bits per sample.
2. levels.
3. samples.
4. s µs.
5. bytes per second, as the program prints.
6. bytes.
7. MiB, and MB.
8. bits per second.
9. bytes, about MiB.
10. : whole songs.
11. , about a millionth: nothing.
12. .
13. Lossy. Part IV measures a lossless ratio of about on this music with zlib, nowhere near . Methods built for sound do better by predicting each sample from the ones before, but still nowhere near ; and the proposition says that no lossless method shrinks every file. The service throws away what the ear hardly notices.
14. runs for bytes: almost every byte is a run of its own. Run-length coding with two bytes per run would nearly double the size, to about bytes.
15. About on music ( bytes) and about on silence ( bytes).
16. A sample is stored in two bytes, the low byte first. The low byte holds the finest 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 : one run of 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 bytes, about MiB. A general-purpose lossless compressor, zlib, reaches a ratio of only about on this music, against about 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 methods.