In order to automatically resize your input images you need to define a preprocessing pipeline all your images go through. This can be done with torchvision.transforms.Compose() (Compose docs). To resize Images you can use torchvision.transforms.Scale() (Scale docs) from the torchvision package.
See the documentation:
Note, in the documentation it says that .Scale() is deprecated and .Resize() should be used instead. Resize docs
This would be a minimal working example:
import torch
from torchvision import transforms
p = transforms.Compose([transforms.Scale((48,48))])
from PIL import Image
img = Image.open('img.jpg')
img.size
# (224, 224) <-- This will be the original dimensions of your image
p(img).size
# (48, 48) <-- This will be the rescaled/resized dimensions of your image
1)
If you are using transform you can simply use resize. For example, this code will convert MNIST dataloading into a 32*32 shape (in the resize line)
train_loader = torch.utils.data.DataLoader(
torchvision.datasets.MNIST('/files/', train=True, download=True,
transform=torchvision.transforms.Compose([
torchvision.transforms.ToTensor(),
torchvision.transforms.Resize(32), # This line
torchvision.transforms.Normalize(
(0.1307,), (0.3081,))
])),
batch_size=batch_size_train, shuffle=True)
2)
If you only want a function you can use torchvision.transforms.functional.resize(image, size, ...). The other answers seem deprecated.
In the Resize Docs is written
Resize the input image to the given size.
Parameters:
- img (PIL Image or Tensor) – Image to be resized.
- size Desired output size. If size is a sequence like (h, w), the output size will be matched to this. If size is an int, the smaller edge of the image will be matched to this number maintaining the aspect ratio
Return type:
- PIL Image or Tensor
It seems like you are looking for interpolate (a function in nn.functional):
import torch.nn.functional as nnf
x = torch.rand(5, 1, 44, 44)
out = nnf.interpolate(x, size=(224, 224), mode='bicubic', align_corners=False)
If you really care about the accuracy of the interpolation, you should have a look at ResizeRight: a pytorch/numpy package that accurately deals with all sorts of "edge cases" when resizing images. This can have an effect when directly merging features of different scales: inaccurate interpolation may result in misalignments.
The TorchVision transforms.functional.resize() function is what you're looking for:
import torchvision.transforms.functional as F
t = torch.randn([5, 1, 44, 44])
t_resized = F.resize(t, 224)
If you wish to use another interpolation mode than bilinear, you can specify this with the interpolation argument.