Sub topic 3
Decoding: Why Compressed Images Are Expensive to Read
Assume you know basic Python, NumPy array shapes, and PyTorch Dataset and DataLoader. You should also know that an image tensor usually has height, width, and channel dimensions.
Compressed bytes are not image pixels
An image file usually stores compressed data. Compression reduces disk space and read time, but the model cannot use the compressed bytes directly. A decoder must reconstruct pixel values first.
For a JPEG image, decoding commonly includes these steps:
- Read compressed bytes from storage.
- Parse the JPEG headers.
- Reverse the JPEG compression process.
- Convert color data, often from YCbCr to RGB.
- Create an uncompressed pixel array.
A 224 × 224 RGB image contains 150,528 channel values. At one byte per value, the decoded image needs about 147 KiB in memory, even if the JPEG file occupies only 20 KiB on disk. Larger source images create much more temporary work before resizing.
PNG decoding also reconstructs pixels, but PNG uses lossless compression and often requires filtering and decompression. JPEG is frequently the larger training bottleneck because datasets contain many high-resolution photographs, and JPEG decoding performs substantial mathematical work for every image.
Separate reading from decoding
Reading moves compressed bytes from storage into memory. Decoding turns those bytes into pixels. They are different stages, so measure them separately.
import io
import sys
import time
from pathlib import Path
from PIL import Image
def measure(paths):
read_total = 0.0
decode_total = 0.0
for path in paths:
start = time.perf_counter()
data = Path(path).read_bytes()
after_read = time.perf_counter()
with Image.open(io.BytesIO(data)) as image:
rgb = image.convert("RGB")
rgb.load()
after_decode = time.perf_counter()
read_total += after_read - start
decode_total += after_decode - after_read
count = len(paths)
print(f"images: {count}")
print(f"read: {read_total / count * 1000:.2f} ms/image")
print(f"decode: {decode_total / count * 1000:.2f} ms/image")
if __name__ == "__main__":
if len(sys.argv) < 2:
raise SystemExit("usage: python measure_decode.py IMAGE ...")
measure(sys.argv[1:])The call to convert("RGB") performs color conversion when necessary. The call to load() forces Pillow to finish decoding while the timer is still active.
| Stage | Input | Output | Typical constraint |
|---|---|---|---|
| Read | Compressed file | Compressed bytes | Storage or filesystem |
| Decode | Compressed bytes | Pixel array | CPU time and memory |
| Resize | Pixel array | Smaller pixel array | CPU time and interpolation |
Why source dimensions matter
Resizing after decoding does not remove the cost of decoding the original image. A 4,000 × 3,000 JPEG must usually be reconstructed at a large size before a normal resize reduces it to 224 × 224.
This is why an input pipeline can leave a GPU idle even when file reads seem fast. The CPU may still be decoding and converting the next batch.
The decoding path
Decoding is often the first optimization target because it happens once per image and usually remains on the CPU. Later chapters can reduce its cost by decoding at a smaller JPEG scale, using worker processes, caching suitable representations, or using hardware-accelerated decoders.
Exercise
Why does resizing a 4,000 × 3,000 JPEG to 224 × 224 usually not eliminate the original decoding cost?
Show answer
The decoder generally reconstructs the large source image before the resize operation runs. The resize reduces the result, but it does not undo the work already performed.