Sub topic 5
Interpolation and border handling
This chapter assumes you know how images are stored as pixel arrays, and that you have read the previous chapter on geometric transforms (flips, crops, rotations, scaling). You should also be able to read short PyTorch snippets. The chapter covers what happens at the pixel level when a transform moves content by a non-integer amount, and what fills the area that the transform exposes.
Why geometric transforms need both
A rotation by 30 degrees does not map pixels onto pixels. Most transformed positions fall between the source pixels, and some fall outside the source image. Every geometric transform therefore needs two decisions:
- Interpolation decides what value to compute at a non-integer position.
- Border handling decides what value to use when the position is outside the image.
Libraries use inverse mapping to make this tractable. They loop over each pixel of the output, apply the inverse transform to find where that pixel comes from in the source, and then sample the source at that coordinate. This guarantees every output pixel gets a value, whereas pushing source pixels forward would leave holes.
Interpolation modes
The common modes differ in how many neighbors they use and what kind of values they can produce.
| Mode | Neighbors used | Output values | Typical use |
|---|---|---|---|
| Nearest | 1 | Only values already in the source | Masks, label maps, class ids |
| Bilinear | 4 (2x2) | Weighted averages, always within the range of the neighbors | Default for photos |
| Bicubic | 16 (4x4) | Sharper, but can overshoot the neighbor range | Quality-sensitive resizing |
| Area / antialiased | Many | Averages over the source footprint | Large downscaling |
Nearest picks the closest source pixel. It is fast and never invents a value, but it produces blocky, jagged edges on photographs. Bilinear blends the four surrounding pixels by distance, which gives smooth results with slight blurring. Bicubic uses a larger neighborhood to keep edges crisper. Its weights can be negative, so a result can land below 0 or above 255. If you work on float tensors after bicubic resampling, clamp the result to the valid range.
Why masks must use nearest
Averaging is meaningless for categorical data. If class 1 (road) sits next to class 3 (car) and you interpolate bilinearly, the boundary gets class 2, which might be "pedestrian". The code below shows this on one row of pixels.
import numpy as np
row = np.array([1, 1, 3, 3], dtype=np.float32) # class ids across an object edge
# Sample halfway between pixel 1 (value 1) and pixel 2 (value 3).
bilinear = 0.5 * row[1] + 0.5 * row[2]
nearest = row[int(round(1.5 + 1e-6))] # snaps to a real pixel
print("bilinear:", bilinear) # 2.0, a class that is not at this edge
print("nearest: ", nearest) # 3.0, a class that exists in the sourceThe rule is simple. Images get bilinear (or bicubic), and anything holding class ids, instance ids, or other discrete labels gets nearest. Continuous targets such as depth maps are a judgment call. Bilinear is usually fine in the interior, but it blends across depth discontinuities.
Shrinking needs more than bilinear
Bilinear looks at only four source pixels. When you shrink an image by 4x or more, most source pixels are never read, and thin patterns turn into aliasing (jagged or moire artifacts). The fix is antialiasing, which low-pass filters the image before or during resampling. PIL's resize does this for you. Tensor resizing historically did not, and recent torchvision versions enable antialias=True by default for tensors. Check your installed version, and set the argument explicitly so training results do not depend on it.
Border modes
When the source coordinate falls outside the image, the border mode decides what to return. The row [1, 2, 3, 4] padded by three pixels on each side shows the options.
import numpy as np
row = np.array([1, 2, 3, 4])
for mode in ["constant", "edge", "reflect", "symmetric", "wrap"]:
print(f"{mode:9s}", np.pad(row, 3, mode=mode))
# constant [0 0 0 1 2 3 4 0 0 0]
# edge [1 1 1 1 2 3 4 4 4 4]
# reflect [4 3 2 1 2 3 4 3 2 1]
# symmetric [3 2 1 1 2 3 4 4 3 2]
# wrap [2 3 4 1 2 3 4 1 2 3]| Mode | OpenCV name | Behavior | Main risk |
|---|---|---|---|
| Constant | `BORDER_CONSTANT` | Fills with one value (often 0) | Black wedges are an easy shortcut cue |
| Replicate / edge | `BORDER_REPLICATE` | Repeats the outermost pixel | Smeared streaks |
| Reflect | `BORDER_REFLECT_101` | Mirrors without repeating the edge pixel | Ghost copies of objects |
| Symmetric | `BORDER_REFLECT` | Mirrors, repeating the edge pixel | Same as reflect |
| Wrap | `BORDER_WRAP` | Tiles from the opposite side | Content jumps to the wrong side |
Note that the names are not consistent across libraries. NumPy's reflect matches OpenCV's BORDER_REFLECT_101, and NumPy's symmetric matches OpenCV's BORDER_REFLECT. Check the exact definition before assuming two pipelines match.
Choosing a mode
Constant fill is the default in most libraries and the safest for classification, but it has two problems you need to handle.
First, a model can learn that black corners signal "this image was rotated". That cue is present in training and absent at evaluation, so the model may waste capacity on it. Keeping rotation angles small, or cropping afterwards so that the corners are cut away, reduces the effect.
Second, the fill value interacts with normalization. A fill of 0 applied to a uint8 image before Normalize is black, which becomes a strongly negative value after normalization. A fill of 0 applied after Normalize equals the dataset mean color, which is a much milder signal. Pick the order deliberately. A common choice is to fill with the mean color in 0 to 255 units before normalizing, so the fill becomes exactly 0 afterward.
Reflect and replicate hide the border cue, which suits natural textures such as foliage or sky. They are risky when objects are centered and labeled. A reflected object appears twice, but only one copy has a label. In detection, that creates unlabeled "ghost" objects that teach the model to treat real objects as background.
Applying the right mode to the image and mask together
The next example rotates an image and its mask by the same angle. The image uses bilinear interpolation and mean-color fill. The mask uses nearest interpolation and a fill of 255, which we treat as an "ignore" label.
import torch
import torchvision.transforms.functional as TF
from torchvision.transforms import InterpolationMode
torch.manual_seed(0)
image = torch.randint(0, 256, (3, 64, 64), dtype=torch.uint8)
mask = torch.randint(0, 5, (1, 64, 64), dtype=torch.uint8) # class ids 0..4
angle = 30.0 # one draw, reused for both
mean_fill = [124, 116, 104] # ImageNet mean in 0-255 units
image_rot = TF.rotate(
image, angle, interpolation=InterpolationMode.BILINEAR, fill=mean_fill
)
mask_rot = TF.rotate(
mask, angle, interpolation=InterpolationMode.NEAREST, fill=[255]
)
print(sorted(torch.unique(mask_rot).tolist())) # only 0-4 and 255The printed set contains only the original ids plus 255. With bilinear interpolation on the mask, you would see values that were never in the data. Training with torch.nn.CrossEntropyLoss(ignore_index=255) then skips the filled corners, so the model is not penalized for predicting anything in a region that has no ground truth.
Common errors
- Interpolated labels. Resizing masks with bilinear or bicubic produces invalid class ids. Use nearest.
- Different interpolation in train and eval. A model trained on bilinear-resized images and evaluated on bicubic-resized ones sees a small but real distribution shift. Pretrained models are especially sensitive, so match the interpolation used in the original training recipe.
- Mixing libraries. PIL, OpenCV, and tensor-based resizing give slightly different numbers for the same nominal mode, largely because of antialiasing and rounding. Use one library per pipeline, including at inference time.
- Unclamped bicubic output. On float tensors, bicubic can leave the 0 to 1 range. Clamp before the next step. On uint8 images, libraries saturate for you.
- Constant fill after normalization by accident. A fill of 0 on a normalized tensor is a gray patch rather than a black one. This is fine if intended, but it surprises people who visualize the result.
- Reflect on labeled objects. In detection and instance tasks, reflection duplicates objects without annotations. Prefer constant fill, or crop to the valid region.
- Large rotations with constant fill. A 45 degree rotation can leave a quarter of the image as fill. Either limit the angle or follow the rotation with a crop.
Exercise
You rotate a segmentation image by 20 degrees and want training to ignore the corners that the rotation exposes. Which interpolation mode and fill value would you use for the mask, and what must you set in the loss function?
Show answer
Use nearest interpolation, so that no new class ids are created, and fill the exposed corners with a reserved value such as 255 that is not a real class. Then set ignoreindex=255 in the loss, for example CrossEntropyLoss(ignoreindex=255), so those pixels contribute no gradient.
Exercise
A colleague pads a classification image with reflect mode before a random crop and says it is safer than black borders. For which kind of dataset would you object, and why?
Show answer
For images where a single labeled object sits near the edge, such as centered portraits or object-detection data. Reflection mirrors the object into the padded area, so the image contains a duplicate. In classification this can confuse the label, and in detection the duplicate has no box, so it acts as a false negative training signal.