torchvision.transforms.Resize(size, interpolation=2)功能及缩放逻辑问询
Hey there! Let's clear up exactly what torchvision.transforms.Resize(size, interpolation=2) does—this is a super common question when working with image transforms in PyTorch.
核心功能
First off, the key thing to know: this transform directly scales (resizes) your image to the target size—it does NOT pad smaller images with blank space, nor does it crop larger ones. How it adjusts the image depends entirely on how you pass the size parameter:
- If you pass a single integer (e.g.,
size=224):
The transform will scale the image so that its shorter side matches this integer, and the longer side will scale proportionally to maintain the original aspect ratio. No stretching or distortion here—your image keeps its original shape, just resized up or down. - If you pass a tuple (e.g.,
size=(224, 224)):
The transform will force the image to fit exactly into this height and width, regardless of the original aspect ratio. This means if your input image was, say, 400x200 and you resize to 224x224, the image will get stretched vertically to fit, causing distortion.
Interpolation参数说明
The interpolation=2 part refers to the method used to compute pixel values when scaling. In PyTorch, 2 maps to InterpolationMode.BILINEAR (bilinear interpolation)—this is the default mode, and it produces smoother, more natural-looking scaled images compared to simpler methods like nearest-neighbor interpolation.
关于补全/裁剪的补充
If you need to get an image to a fixed size without distortion (e.g., padding smaller images or cropping larger ones), Resize alone won't do it. You'll need to combine it with other transforms. For example, a common workflow for fixed-size input is:
from torchvision import transforms # Resize to a larger intermediate size, then center crop to target size transform = transforms.Compose([ transforms.Resize(256), # Scale short side to 256, keep aspect ratio transforms.CenterCrop(224), # Crop to exact 224x224 from center ])
Or if you need to pad smaller images to reach the target size, you could pair Resize with Pad after checking the image dimensions.
内容的提问来源于stack exchange,提问作者Anjalla

