Sub topic 11
Variable-Size Images: Padding, Bucketing, and Resizing Policy
Assume you know Python, NumPy-style image shapes, and PyTorch Dataset and DataLoader. You should also understand that an image tensor usually has shape channels × height × width.
A batch is a group of samples processed together. Standard tensor batches require every sample to have the same shape. Real datasets often contain different image sizes, so the input pipeline needs a policy for making them compatible.
Three ways to handle different sizes
The simplest policy is to resize every image to one fixed size before batching. This gives predictable memory use and fast tensor operations, but it changes the image geometry. Classification often tolerates this. Detection and segmentation may lose accuracy when objects become stretched or overly small.
Padding preserves the original pixels. The pipeline adds empty pixels until every image in a batch has the same height and width. The model or loss must know which pixels are padding, usually through a mask.
Bucketing groups images with similar dimensions. Each batch then needs less padding than a random batch. Bucketing preserves more of the original resolution, but it complicates sampling and can reduce randomness.
| Policy | Main benefit | Main cost | Good fit |
|---|---|---|---|
| Fixed resize | Simple and efficient batches | Distorts or removes detail | Many classification models |
| Per-batch padding | Preserves image content | Wastes compute on padding | Detection and segmentation |
| Size bucketing | Reduces padding waste | More sampler complexity | Large variable-resolution datasets |
Padding a batch
The following collate function receives images with shape channels × height × width. It pads each image at the bottom and right, then returns the original sizes. Returning sizes allows later code to create masks or scale predictions back to the source image.
import torch
def pad_collate(images):
if not images:
raise ValueError("images must not be empty")
channels = images[0].shape[0]
height = max(image.shape[1] for image in images)
width = max(image.shape[2] for image in images)
batch = torch.zeros(
len(images), channels, height, width,
dtype=images[0].dtype
)
sizes = torch.empty(len(images), 2, dtype=torch.int64)
for index, image in enumerate(images):
if image.shape[0] != channels:
raise ValueError("all images must have the same channel count")
image_height, image_width = image.shape[1:]
batch[index, :, :image_height, :image_width] = image
sizes[index] = torch.tensor([image_height, image_width])
return batch, sizes
if __name__ == "__main__":
images = [
torch.full((3, 100, 160), 10, dtype=torch.uint8),
torch.full((3, 80, 120), 20, dtype=torch.uint8),
]
batch, sizes = pad_collate(images)
print(batch.shape) # torch.Size([2, 3, 100, 160])
print(sizes.tolist()) # [[100, 160], [80, 120]]Padding with zero is safe only when zero represents a suitable background value. After normalisation, zero may represent the mean rather than black. For attention or loss calculations, build a valid-pixel mask from the returned sizes.
Choosing a resizing policy
A useful compromise is to preserve aspect ratio, resize the longer edge to a limit, and then pad to a size required by the model. Convolutional networks often prefer dimensions divisible by ocho or sixteen because downsampling layers repeatedly halve spatial dimensions.
For training, keep the policy consistent with the model's expected input distribution. For evaluation, use a deterministic policy. If predictions refer to original coordinates, record the resize scale and padding offset so you can invert the transformation.
Bucketing by size
A bucket groups samples by similar height, width, or aspect ratio. Sort or assign paths to buckets, shuffle within each bucket, and form batches locally. Measure the padding ratio:
padding ratio = padded pixels / total batch pixels
A high ratio means the batch is spending time processing empty space. Bucketing lowers that ratio, but excessively narrow buckets can produce small or repetitive batches. Start with a few aspect-ratio groups and compare throughput and validation accuracy.
Exercise
A batch contains images of 640×480 and 320×240. Which policy best preserves their geometry, and what extra information should the collate function return?
Show answer
Use padding, preferably after grouping similar aspect ratios. Return each image's original height and width, or a valid-pixel mask, so padded regions can be ignored and coordinates can be restored.