import torch import torchvision.transforms as transforms from PIL import Image # Load an image img = Image.open('image.jpg') # Define the resize transform and apply to the image resize_transform = transforms.Resize(size=(224, 224)) resized_img = resize_transform(img) # Convert the image to a tensor img_tensor = transforms.ToTensor()(resized_img)
import torch import torchvision.transforms as transforms from PIL import Image # Load an image img = Image.open('image.jpg') # Define the resize transform with interpolation parameters and apply to the image resize_transform = transforms.Resize(size=(224, 224), interpolation=Image.BICUBIC) resized_img = resize_transform(img) # Convert the image to a tensor img_tensor = transforms.ToTensor()(resized_img)In this example, we defined a resize transform with the BICUBIC interpolation method, which can provide better quality results when resizing images compared to the default method. We applied the transform to the image and converted it to a PyTorch tensor. Overall, the torchvision.transforms.Resize package library provides easy-to-use and powerful tools in python for resizing images, regardless of the shape, resolution, or aspect ratio.