Sub topic 4
Resizing: interpolation, antialiasing, and cost
This chapter assumes you can read basic Pillow and PyTorch code and know what a height × width × channels array is. You should also know that the previous chapter's decode step produces a full-size pixel array. Resizing turns that array into the fixed shape the model expects. It is often the second-largest CPU cost after decoding, and it can change the model's accuracy without raising any error.
What interpolation does
A resize maps each output pixel back to a position in the source image and computes a value from nearby source pixels. The interpolation method (also called the filter or kernel) decides which neighbours contribute and with what weights.
- Nearest neighbour copies the single closest source pixel. It is the cheapest method and produces blocky or jagged results.
- Bilinear takes a weighted average of the 2 × 2 closest pixels.
- Bicubic uses a 4 × 4 neighbourhood. It is sharper than bilinear and can overshoot slightly (values below 0 or above 255 are clipped).
- Lanczos uses a larger windowed-sinc kernel (a 6 × 6 neighbourhood at scale 1). It gives the sharpest results and costs the most.
- Box / area averages every source pixel that falls inside the output pixel's footprint.
Most implementations are separable. They resize all rows horizontally, then all columns vertically. This keeps the cost proportional to the kernel width rather than its square.
Aliasing: why downscaling is the hard case
Training pipelines almost always shrink images, for example from 4000 × 3000 down to 224 × 224. When you shrink by a factor of 4, each output pixel represents a 4 × 4 block of source pixels. A filter that only looks at its 2 × 2 or 4 × 4 neighbourhood at source scale skips most of those pixels. Fine detail then folds into false coarse patterns, called aliasing: moiré on fabrics, shimmering edges, and thin lines that vanish or thicken.
Antialiasing fixes this by widening the kernel in proportion to the shrink factor, so every source pixel contributes to some output pixel. Pillow's resize does this automatically for every filter except nearest. Other libraries do not:
| Library call | Antialiased when downscaling? |
|---|---|
| `PIL.Image.resize` with BILINEAR, BICUBIC, LANCZOS, BOX, HAMMING | Yes |
| `PIL.Image.resize` with NEAREST | No |
| `cv2.resize` with `INTER_LINEAR` or `INTER_CUBIC` | No |
| `cv2.resize` with `INTER_AREA` | Yes (area averaging) |
| `torch.nn.functional.interpolate`, bilinear or bicubic | No by default; pass `antialias=True` |
| `torchvision.transforms.functional.resize` on tensors | Depends on the version and the `antialias` argument; set it explicitly |
The next script builds an image with a white line every fourth column. The true average brightness is 25% of white, about 64 out of 255. It then shrinks the image by 4 with three methods.
import numpy as np
from PIL import Image
arr = np.zeros((1024, 1024), dtype=np.uint8)
arr[:, ::4] = 255 # white column every 4th pixel
im = Image.fromarray(arr)
for name, flt in [("nearest", Image.Resampling.NEAREST),
("bilinear", Image.Resampling.BILINEAR),
("box", Image.Resampling.BOX)]:
out = np.asarray(im.resize((256, 256), flt))
print(f"{name:9s} mean={out.mean():6.1f}")Nearest samples only black columns, so it reports a mean of 0 and the lines disappear. The two antialiased filters report values close to 64, which matches the source image. The same effect appears in PyTorch.
import torch
import torch.nn.functional as F
x = torch.zeros(1, 1, 1024, 1024)
x[..., ::4] = 1.0 # same pattern, float tensor
plain = F.interpolate(x, size=(256, 256), mode="bilinear", align_corners=False)
anti = F.interpolate(x, size=(256, 256), mode="bilinear",
align_corners=False, antialias=True)
print(f"no antialias: {plain.mean():.3f} antialias: {anti.mean():.3f}")The plain call samples between two black columns and returns 0. The antialiased call returns a value near 0.25.
Choosing a method
Match the method to the direction of the resize and to what the model was trained on.
Two rules cover most cases:
- If a reference pipeline exists, copy it. A pretrained checkpoint was validated with a specific preprocessing recipe. Changing the filter shifts its input statistics.
- Resize label images with nearest. Averaging class IDs 3 and 7 produces class 5, which is wrong. Image data and label data need different filters.
For training from scratch, antialiased bilinear is a sound default. The accuracy gap between bilinear, bicubic, and Lanczos is usually small compared with the gap between antialiased and non-antialiased resizing.
What resizing costs
For a separable filter, the work per output pixel in each pass is proportional to the number of taps, which is the number of source pixels that contribute. On upscaling the tap count is fixed by the kernel. On downscaling the kernel stretches, so the count grows with the shrink factor:
- Taps per output pixel ≈ 2 × kernel radius × scale factor. The radius is 1 for bilinear, 2 for bicubic, and 3 for Lanczos.
- Shrinking 4000 × 3000 to 224 × 224 is about a 13–18× reduction per axis. A bilinear kernel then reads roughly 30 source pixels per output pixel in each pass.
- The first (horizontal) pass runs over the full-height source, so its output is still large. Most of the cost sits there.
Measure the actual cost on your own images with this benchmark.
import time
import numpy as np
from PIL import Image
rng = np.random.default_rng(0)
big = Image.fromarray(rng.integers(0, 256, (3000, 4000, 3), dtype=np.uint8))
filters = {
"nearest": Image.Resampling.NEAREST,
"bilinear": Image.Resampling.BILINEAR,
"bicubic": Image.Resampling.BICUBIC,
"lanczos": Image.Resampling.LANCZOS,
}
for name, flt in filters.items():
big.resize((224, 224), flt) # warm-up
t0 = time.perf_counter()
for _ in range(10):
big.resize((224, 224), flt)
ms = (time.perf_counter() - t0) / 10 * 1e3
print(f"{name:9s} {ms:6.2f} ms")Expect nearest to be far faster than the others, and bilinear to be faster than bicubic, which is faster than Lanczos. Exact numbers depend on your CPU and Pillow build.
Ways to cut the cost without changing the result much
- Use
reducing_gap.im.resize(size, flt, reducing_gap=2.0)first shrinks the image by an integer factor with a cheap box reduction, then applies the real filter. It is faster on large downscales, but the output differs slightly from a plain resize. - Use
Image.draftfor JPEGs. The decoder can emit a 1/2, 1/4, or 1/8 size image directly, so the later resize reads far fewer pixels. The previous chapter's decoding costs and the next chapter's draft mode cover this. - Resize before converting to float. A uint8 image is a quarter of the memory of float32, so every pass moves less data. Normalisation comes after the resize.
- Pick the cheapest filter that meets your accuracy target. Check that choice with a validation run, not by eye.
Common errors
- Mixing libraries between training and serving. The same filter name can mean different things. OpenCV's
INTER_LINEARis not antialiased, and Pillow'sBILINEARis. - Resizing a non-square image straight to a square. This distorts the aspect ratio. Decide on a policy deliberately: stretch, resize the short side then centre-crop, or resize with padding. The variable-size chapter returns to this.
- Interpolating label masks with a smooth filter. This creates invalid class IDs. Use nearest.
- Resizing after normalisation to float. This is slower and uses more memory than necessary. For the intended order, see the operation-order chapter.
- Changing the filter to save time and skipping validation. Switching bicubic to bilinear can speed up the pipeline, but you must confirm that accuracy holds. The parity-check chapter covers how.
Exercise
Your serving code calls cv2.resize(img, (224, 224), interpolation=cv2.INTER_LINEAR) on 2000 × 1500 photos, but the model was trained with Pillow's Image.BILINEAR. Accuracy in production is lower than in validation. Explain the likely cause and give two fixes.
Show answer
Pillow's BILINEAR widens its kernel when downscaling (antialiasing), while OpenCV's INTERLINEAR samples only a 2 × 2 neighbourhood. At roughly 7× shrinkage, OpenCV skips most source pixels and aliases fine detail, so the model sees different inputs than during training. Fix 1: resize with Pillow in serving, using the same filter. Fix 2: keep OpenCV but use INTERAREA, which averages the source footprint, and then check parity against the Pillow output on a sample of images. Setting antialias=True in a PyTorch resize is a third option.
Exercise
A segmentation dataset stores each mask as a single-channel image where each pixel value is a class ID from 0 to 20. Which interpolation should you use to resize the masks to match resized photos, and why?
Show answer
Use nearest neighbour. Any averaging filter blends neighbouring IDs into values that belong to no real class (for example, classes 3 and 7 blend to 5). Nearest copies an existing ID, so every output pixel stays a valid class. The photos can still use an antialiased filter, because they hold intensities where averaging is meaningful.