Sub topic 3
Decoding: why compressed images are expensive to read
This chapter assumes you know basic Python and NumPy, can read an image as a height × width × channels array, and have used PyTorch's Dataset and DataLoader. It also assumes you know JPEG and PNG as file formats. It covers what happens between "bytes on disk" and "array in memory", and why that step so often limits an input pipeline.
Reading a file is not decoding it
A pipeline step that "loads an image" does two different things.
- Read. Copy the file's bytes from disk, or from the operating system's page cache, into memory. Cost depends on file size and storage speed.
- Decode. Turn those compressed bytes into a raw array of pixels. Cost depends on pixel count and on the format's algorithm.
A 12-megapixel (4000 × 3000) photo may be a 4 MB JPEG file. Decoded to 8-bit RGB it is 4000 × 3000 × 3 = 36,000,000 bytes, about nine times larger. The CPU has to produce all of those bytes, and it does so with arithmetic, not with a memory copy.
Pillow is lazy about this. Image.open parses only the header, so it returns almost instantly and gives you size and mode. The pixel data is decoded later, when you call load(), convert(), resize(), or np.asarray(). If you time Image.open alone, you will measure the wrong thing.
What a JPEG decoder does
JPEG is lossy. The encoder discards detail the eye is less sensitive to, then packs what remains compactly. The decoder must undo each step.
- Entropy decoding. The bitstream uses Huffman codes of variable length. A decoder cannot know where one symbol ends until it has read the previous one, so this stage is mostly sequential. It also scales with the amount of compressed data, so high-quality files cost more here.
- Dequantisation. Each coefficient is multiplied by a value from a quantisation table. This is cheap.
- Inverse discrete cosine transform (IDCT). Each 8 × 8 block of frequency coefficients is converted back to 64 pixel values. This runs once per block per channel, so cost grows with pixel count.
- Chroma upsampling. Most JPEGs store colour at lower resolution than brightness. With 4:2:0 subsampling, each colour plane has a quarter of the pixels, and the decoder stretches it back to full size.
- Colour conversion. Each pixel moves from YCbCr to RGB, which is a small matrix multiply per pixel.
The important consequence is that decode time follows the number of pixels, not the file size on disk. A 12 MP image takes roughly four times as long to decode as a 3 MP image of similar content, whatever the compression.
Pillow's wheels and OpenCV use libjpeg-turbo, which applies SIMD instructions to the IDCT, upsampling, and colour conversion. Plain libjpeg is several times slower. If a pipeline is unexpectedly slow, check which library your Python environment actually uses.
How formats compare
| Format | Compression | Main decode cost | Notes |
|---|---|---|---|
| JPEG (baseline) | Lossy | Huffman decoding, IDCT, colour conversion | Smallest files for photos, moderate CPU cost |
| JPEG (progressive) | Lossy | Same, but over multiple scans | Usually slower to decode than baseline |
| PNG | Lossless | DEFLATE decompression, then filter reversal | Larger files, often slower than JPEG at equal size, exact pixels |
| WebP | Lossy or lossless | Format-dependent | Often slower than JPEG to decode |
| Raw array (`.npy`) | None | A memory copy | Large files, so read cost grows |
The rows trade CPU time against storage and I/O. JPEG spends CPU to save bytes. Raw arrays spend bytes to save CPU. A later chapter on caching returns to this trade.
Measuring decode cost
The script below builds one synthetic 2000 × 1500 image, stores it as JPEG, PNG, and raw bytes in memory, and times decoding each. Using in-memory buffers removes disk speed from the measurement, so you see decode cost alone.
import io
import time
import numpy as np
from PIL import Image
H, W = 1500, 2000
rng = np.random.default_rng(0)
yy, xx = np.mgrid[0:H, 0:W]
base = np.stack([xx / W * 255, yy / H * 255, (xx + yy) / (H + W) * 255], axis=-1)
arr = np.clip(base + rng.normal(0, 8, base.shape), 0, 255).astype(np.uint8)
jpeg_buf, png_buf = io.BytesIO(), io.BytesIO()
Image.fromarray(arr).save(jpeg_buf, "JPEG", quality=90)
Image.fromarray(arr).save(png_buf, "PNG")
payloads = {
"jpeg": jpeg_buf.getvalue(),
"png": png_buf.getvalue(),
"raw": arr.tobytes(),
}
def decode(kind, data):
if kind == "raw":
return np.frombuffer(data, dtype=np.uint8).reshape(H, W, 3).copy()
return np.asarray(Image.open(io.BytesIO(data)).convert("RGB"))
def median_ms(fn, repeats=15):
times = []
for _ in range(repeats):
t0 = time.perf_counter()
fn()
times.append(time.perf_counter() - t0)
return sorted(times)[len(times) // 2] * 1e3
for kind, data in payloads.items():
ms = median_ms(lambda: decode(kind, data))
print(f"{kind:5s} {len(data) / 1e6:6.2f} MB decode {ms:7.2f} ms")
# Image.open alone only parses the header; compare it with a full decode.
data = payloads["jpeg"]
print("open only :", f"{median_ms(lambda: Image.open(io.BytesIO(data))):.3f} ms")
print("open+load :", f"{median_ms(lambda: decode('jpeg', data)):.3f} ms")Absolute numbers depend on your CPU and Pillow build, so run it yourself. What to look for:
- The JPEG file is much smaller than the PNG and the raw bytes.
- The JPEG decode is usually far slower than the raw copy, despite the smaller file.
- "open only" is a tiny fraction of "open+load". This is the lazy loading described above.
The chapter on profiling shows how to time read, decode, and resize separately across a real dataset. Here the point is that decoding is a distinct cost with its own scaling.
Turning decode time into a throughput limit
Suppose one core decodes a 12 MP JPEG in 40 ms. That core delivers 25 images per second. A GPU that can train on 2000 images per second would need 2000 × 0.04 = 80 cores doing nothing but decoding, before any resizing or augmentation. Even a modern server rarely has that many cores to spare for one job.
When the GPU waits for data, you see low GPU utilisation, long gaps between steps, and CPU cores near 100%. The accelerator is idle because the input stage cannot keep up. Decoding is the first place to look.
Two levers follow from the arithmetic:
- Decode less. Fewer pixels, or fewer images per step. Reduced-size JPEG decoding, covered in its own chapter, takes this route.
- Decode in parallel. More cores or devices working at once. Worker processes and hardware decoders cover this.
Correctness traps when decoding
Speed is not the only issue. A loader that decodes quickly but wrongly corrupts training silently.
- Colour modes. Files can be grayscale (
L), palette (P), RGBA, or CMYK. A model expecting three channels fails or misbehaves on the others. Callconvert("RGB")on every image. - EXIF orientation. Phone photos often store pixels sideways and record the rotation in metadata. Pillow does not apply it automatically.
ImageOps.exif_transposedoes. - Channel order. OpenCV's
cv2.imreadreturns BGR, while Pillow returns RGB. Mixing the two libraries across training and inference swaps the red and blue channels. - Truncated or corrupt files. One bad file in a million raises an exception inside a worker and can stop an epoch. Decide on a policy in advance: skip, replace, or fail loudly.
- Decode differences between libraries. Different JPEG decoders can produce pixel values that differ by a few levels, because IDCT and upsampling implementations vary. The difference is small, but it matters when you compare pipelines, which is the subject of the final chapter.
A loader that handles the first two traps looks like this:
from PIL import Image, ImageOps
def load_rgb(path):
with Image.open(path) as im:
im = ImageOps.exif_transpose(im) # apply the stored rotation
return im.convert("RGB") # force 3 channels, 8 bits eachSummary of the working model
- Reading moves bytes. Decoding computes pixels. They have different costs and different fixes.
- JPEG decode time scales with pixel count. It runs entropy decoding, IDCT, upsampling, and colour conversion, and the first of these is sequential.
- A compressed file is much smaller than its decoded array, so memory use after decoding is far larger than file sizes suggest.
- Dividing per-image decode time into the target throughput tells you how many cores you need.
- Convert modes and apply orientation at load time, or the data is wrong before speed even matters.
Exercise
A pipeline must supply 800 images per second. Each image is a 4000 × 3000 JPEG that takes 30 ms to decode on one core, and decoding is the only cost. (a) How many cores are needed? (b) If you could decode at one quarter of the pixel count at the same per-pixel speed, how many cores would you need? (c) What is the size in megabytes of one decoded 8-bit RGB image at full size?
Show answer
(a) Each core handles 1 / 0.030 ≈ 33.3 images per second, so 800 / 33.3 = 24 cores. (b) Decode time scales with pixels, so 7.5 ms per image, about 133 images per second per core, and 800 / 133.3 = 6 cores. (c) 4000 × 3000 × 3 = 36,000,000 bytes, about 36 MB.
Exercise
You time Image.open("photo.jpg") over 1000 files and get 0.2 ms each, so you conclude decoding is not a bottleneck. What is wrong with the measurement, and how do you fix it?
Show answer
Image.open is lazy and reads only the header, so the pixel decode never ran. Force it inside the timed region, for example with Image.open(path).convert("RGB") or np.asarray(...), and time read, decode, and any later steps separately.