Sub topic 2
Interpolation and Border Handling
This chapter assumes you know basic Python, PyTorch tensors, and how transforms.Compose chains image operations. You should also know that an image is an array of pixel values with shape (height, width, channels).
Interpolation and Border Handling
Geometric transforms such as rotation and scaling map each output pixel back to a source position. That position is often fractional, so the library must estimate a value from neighboring pixels. This estimate is called interpolation.
- Nearest neighbor copies the closest pixel. It is fast and never invents new values. Use it for masks and class labels.
- Bilinear averages the four closest pixels. It looks smoother and suits photographs.
Pixels that map outside the original image need a border rule. A constant fill (for example, black) is the simplest choice. Reflection and replication are other options.
Photometric and Occlusion Transforms
Photometric transforms change color and brightness but keep the shape of objects. ColorJitter adjusts brightness, contrast, saturation, and hue. GaussianBlur softens edges. Gaussian noise adds random values to each pixel and is usually applied to tensors.
Occlusion transforms hide a rectangular patch so the model learns to use more than one visual cue. RandomErasing works on tensors, so it runs after ToTensor.
Composing Training and Evaluation Pipelines
Training pipelines are random, so each epoch sees slightly different images. Evaluation pipelines must be deterministic, so validation scores are comparable between runs. Keep the normalization values identical in both.
from PIL import Image
from torchvision import transforms
from torchvision.transforms import InterpolationMode
mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224, 0.225]
train_tf = transforms.Compose([
transforms.RandomRotation(15, interpolation=InterpolationMode.BILINEAR, fill=0),
transforms.RandomResizedCrop(224, scale=(0.6, 1.0)),
transforms.RandomHorizontalFlip(p=0.5),
transforms.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2, hue=0.02),
transforms.RandomApply([transforms.GaussianBlur(kernel_size=3, sigma=(0.1, 1.0))], p=0.3),
transforms.ToTensor(),
transforms.Normalize(mean, std),
transforms.RandomErasing(p=0.25, scale=(0.02, 0.2)),
])
eval_tf = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean, std),
])
img = Image.new("RGB", (300, 260), color=(120, 80, 40))
print(train_tf(img).shape, eval_tf(img).shape)Exercise
A segmentation mask has class IDs 1 and 2 side by side. Why must the mask use nearest-neighbor interpolation when it is rotated?
Show answer
Bilinear blending produces values such as 1.5 at class boundaries, which are not valid labels. Nearest neighbor keeps only the existing IDs.