Sub topic 1
Where an image goes: the stages of a vision pipeline
Prerequisites
This chapter assumes you know Python classes and iterators, can work with NumPy arrays shaped height, width, channels, and have used PyTorch's Dataset and DataLoader. You should also recognise JPEG and PNG files.
The stages
A vision input pipeline turns an image file into a batch tensor for a model. The usual stages are:
- Read the file bytes from disk.
- Decode the bytes into raw pixels.
- Resize the pixels to the model's input size.
- Convert to a tensor and normalise.
- Collate several images into a batch and copy it to the GPU.
Measure first
Time each stage separately before you optimise anything. Report milliseconds per image.
import glob
import io
import time
from PIL import Image
def time_stages(paths, size=(224, 224)):
t_read = t_decode = t_resize = 0.0
for p in paths:
t0 = time.perf_counter()
with open(p, "rb") as f:
data = f.read()
t1 = time.perf_counter()
im = Image.open(io.BytesIO(data)).convert("RGB") # decoding happens here
t2 = time.perf_counter()
im = im.resize(size, Image.Resampling.BILINEAR)
t3 = time.perf_counter()
t_read += t1 - t0
t_decode += t2 - t1
t_resize += t3 - t2
n = len(paths)
print(f"read {t_read/n*1e3:.2f} ms, decode {t_decode/n*1e3:.2f} ms, "
f"resize {t_resize/n*1e3:.2f} ms per image")
if __name__ == "__main__":
time_stages(sorted(glob.glob("images/*.jpg")))Throughput is images per second, which equals 1000 divided by the total milliseconds per image.
> Pillow's open is lazy. The convert call forces the decode, so the timer must wrap it to measure decoding.
Decoding: why compressed images are expensive to read
A JPEG is a compressed file. To decode it, the CPU reverses several steps for every block of pixels. A 4000 × 3000 photo holds 12 million pixels, and all of them must be rebuilt before resizing can start. For large photos, decoding usually costs more CPU time than any other stage. It also repeats every epoch unless you cache the result.
| Stage | Main cost driver |
|---|---|
| Read | Disk speed and file size |
| Decode | Pixel count of the original image |
| Resize | Output size and filter choice |
Resizing: interpolation, antialiasing, and cost
Resizing estimates new pixel values from old ones. Nearest neighbour copies the closest pixel: fast, but blocky. Bilinear averages nearby pixels: smooth, at moderate cost. Bicubic uses a wider neighbourhood: sharper, but slower.
When shrinking, antialiasing prevents fine detail from turning into false patterns. Pillow's BILINEAR, BICUBIC, and LANCZOS filters antialias when they shrink an image. NEAREST does not.
> Use the same resize method in training and inference. A change in method shifts the model's inputs and can lower accuracy.
Exercise
Exercise
Why does decoding time grow with the original image size, even when the model input stays at 224 × 224?
Show answer
Decoding must rebuild every pixel of the source file before resizing starts, so its cost follows the source pixel count. The output size affects only the resize cost.