Sub topic 5
Decoding at Reduced Size with JPEG Draft Mode
This chapter assumes you know the stages of the pipeline (read, decode, resize, batch). It also assumes you can read a per-stage timing profile and know that a JPEG is stored as 8x8 blocks of frequency coefficients. The goal is to skip decoding pixels you will throw away when you resize.
The idea: don't decode what you will discard
A typical camera photo is 4000x3000 pixels, which is 12 million pixels. A classifier usually wants 224x224, about 50 thousand pixels. The usual pipeline decodes all 12 million pixels, converts them to RGB, and then resizes most of them away.
JPEG supports a cheaper route. Its inverse discrete cosine transform (IDCT) can produce an image at 1/2, 1/4, or 1/8 of the original size straight from the coefficients. The decoder then never creates the full-resolution pixels. Pillow exposes this as Image.draft().
What draft mode actually saves
A JPEG decoder does these steps in order:
- Huffman decoding turns the compressed bitstream into quantised coefficients.
- Dequantisation and the IDCT turn coefficients into pixel blocks.
- Chroma upsampling restores the colour channels to full resolution.
- Colour conversion turns YCbCr into RGB.
Reduced-size decoding saves work in steps 2 to 4. The IDCT runs on a smaller block (for example 4x4 instead of 8x8 at 1/2 scale), and upsampling and colour conversion touch far fewer pixels. Step 1 is not reduced, because every coefficient must still be read from the file.
This is why a 1/4 scale (1/16 of the pixels) does not make decoding 16 times faster. The speedup depends on how much of the total time Huffman decoding takes, and it is larger for lightly compressed files. Measure it on your own data.
How `Image.draft` chooses a scale
draft(mode, size) picks the largest reduction factor, from 1, 2, 4, or 8, such that the decoded image is still at least size in both dimensions. Internally the factor is the smaller of width // size[0] and height // size[1], rounded down to 1, 2, 4, or 8.
The table below uses a request of (448, 448), which is twice a 224x224 target.
| Original size | Integer ratios | Scale used | Decoded size |
|---|---|---|---|
| 640x480 | 1, 1 | 1 | 640x480 |
| 1280x960 | 2, 2 | 2 | 640x480 |
| 1920x1080 | 4, 2 | 2 | 960x540 |
| 4000x3000 | 8, 6 | 4 | 1000x750 |
| 8000x6000 | 17, 13 | 8 | 1000x750 |
The scale is limited by the smaller dimension. The 4000x3000 image has a ratio of 8 on its long side but only 6 on its short side. A factor of 8 would make the height 375, which is below 448, so Pillow uses 4.
Why request twice the target size
The load function from the chapter plan asks for (size[0] * 2, size[1] * 2), not the exact target. There are two reasons.
- Quality. The DCT-domain reduction acts like a simple low-pass filter and is not as good as a proper antialiased resize. Decoding to at least 2x the target and then running the normal resize gives the final filter enough input pixels to work with.
- Exact output size. Draft only produces power-of-two reductions. The image will rarely land on exactly 224x224, so a final
resizeis always needed.
A request of exactly the target size is faster but gives slightly blurrier or more aliased results. Treat the 2x margin as a tunable quality setting.
A runnable comparison
The script below builds a synthetic 4000x3000 JPEG, loads it both ways, and compares time and pixel difference. Real photos have more varied content, so expect different numbers.
import io
import time
import numpy as np
from PIL import Image
TARGET = (224, 224)
def make_jpeg(width=4000, height=3000, seed=0):
rng = np.random.default_rng(seed)
x = np.linspace(0, 255, width, dtype=np.float32)[None, :, None]
y = np.linspace(0, 255, height, dtype=np.float32)[:, None, None]
base = ((x + y) / 2).astype(np.int16) # H x W x 1
noise = rng.integers(-8, 9, size=(height, width, 3), dtype=np.int16)
arr = np.clip(base + noise, 0, 255).astype(np.uint8)
buf = io.BytesIO()
Image.fromarray(arr).save(buf, format="JPEG", quality=90)
return buf.getvalue()
def load_full(data, size=TARGET):
im = Image.open(io.BytesIO(data)).convert("RGB")
return im.resize(size, Image.Resampling.BILINEAR)
def load_draft(data, size=TARGET):
im = Image.open(io.BytesIO(data))
im.draft("RGB", (size[0] * 2, size[1] * 2))
im = im.convert("RGB")
return im.resize(size, Image.Resampling.BILINEAR)
def bench(fn, data, repeats=10):
fn(data) # warm-up
t0 = time.perf_counter()
for _ in range(repeats):
fn(data)
return (time.perf_counter() - t0) / repeats * 1e3
if __name__ == "__main__":
data = make_jpeg()
probe = Image.open(io.BytesIO(data))
print("original size:", probe.size)
probe.draft("RGB", (TARGET[0] * 2, TARGET[1] * 2))
print("size after draft:", probe.size)
print(f"full decode: {bench(load_full, data):.1f} ms")
print(f"draft decode: {bench(load_draft, data):.1f} ms")
a = np.asarray(load_full(data), dtype=np.float32)
b = np.asarray(load_draft(data), dtype=np.float32)
print(f"mean abs diff: {np.abs(a - b).mean():.2f} (of 255)")
print(f"max abs diff: {np.abs(a - b).max():.0f}")The two outputs are close but not identical. That difference is the price of the speedup, and the later chapter on parity checks shows how to decide whether it is acceptable.
Gotchas and edge cases
Call draft before the pixels are loaded
draft only works while the file is still unread. Pillow opens an image lazily, so Image.open reads the header and convert or load decodes the data. If you call draft after either of those, it does nothing and you silently get a full-size decode. Always call it directly after open.
It only affects JPEG
For PNG, WebP, and other formats, draft returns None and changes nothing. You can call it unconditionally, so a mixed dataset needs no format check. Those files simply get no speedup.
The image size changes
After a draft, im.size is the reduced size. Any code that uses coordinates from the original image will be wrong. This includes bounding boxes, keypoints, and segmentation masks. Record the original size before calling draft, then scale your annotations by original / final, which is correct because the final resize is just another scale.
Cropping augmentations lose resolution
Random-resized-crop takes a region of the original image and scales it to the target. If you draft first, the crop comes from a 2x-target image. A tight crop of, say, 20% of the image area would then be upscaled and look soft. Use draft only when the full frame is resized to the target (typical for evaluation and simple training), or size the draft request from the smallest crop you expect.
Mode requests and non-RGB files
draft("RGB", ...) asks for RGB output. Grayscale and CMYK JPEGs are handled according to their own color mode, so always call convert("RGB") afterwards to get a consistent three-channel result.
EXIF orientation
Draft does not apply the EXIF rotation tag. If your data relies on it, call ImageOps.exif_transpose after loading. This is a separate concern from draft, but easy to forget when rewriting a loader.
Gains depend on image size
For a dataset of 500x375 thumbnails and a 224x224 target, the request is 448x448 and the scale stays at 1. Draft does nothing there. It pays off when source images are at least four times the target size on the short side.
Decision flow
Applying it in a pipeline
Put the draft call inside the dataset's __getitem__, where worker processes run it in parallel. The load_small function from the chapter plan is the right shape. Keep the margin factor (2) and the interpolation method (bilinear) in one place, because the exact values determine the pixels your model sees.
If you train with draft decoding, use the same path at inference time. A model trained on draft-decoded inputs and evaluated on full-decoded inputs sees a small distribution shift, which can cost a fraction of a percentage point of accuracy. The reverse also holds.
Exercise
A 6000x4000 JPEG is loaded with im.draft("RGB", (448, 448)) for a 224x224 target. What size does the decoder produce, and why not 1/8 scale even though 6000 // 448 is 13? What changes if you request exactly (224, 224)?
Show answer
The ratios are 6000 // 448 = 13 and 4000 // 448 = 8. The smaller is 8, so Pillow picks 1/8 scale, giving 750x500. Both sides are at least 448? No: 500 is above 448 and 750 is above 448, so 1/8 is valid, and the output is 750x500. The 6000 // 448 = 13 ratio does not matter because the short side limits the scale, and 1/8 is also the largest scale available. With a request of (224, 224) the ratios are 26 and 17, so the scale is still capped at 1/8 and the output is still 750x500. The margin only matters for images where the ratio falls between powers of two, for example a 3000x2000 image: with a 448 request the short-side ratio is 4, giving 1/4 (750x500), while a 224 request gives ratio 8 and 1/8 (375x250), a smaller and lower-quality input to the final resize.