In this article, we are going to discuss RandomResizedCrop() method in Pytorch using Python.
RandomResizedCrop() method
RandomResizedCrop() method of torchvision.transforms module is used to crop a random area of the image and resized this image to the given size. This method accepts both PIL Image and Tensor Image. The tensor image is a PyTorch tensor with [C, H, W] shape, where C represents a number of channels and H, W represents height and width respectively. This method returns a randomly cropped image.
Syntax: torchvision.transforms.RandomResizedCrop(size, scale, ratio)
Parameters:
- size: Desired crop size of the image.
- scale: This parameter is used to define the upper and lower bounds for the random area.
- ratio: This parameter is used to define upper and lower bounds for the random aspect ratio.
Return: This method will returns the randomly cropped image of given input size.
The below image is used for demonstration:
Example 1:
In this example, we are transforming the image with a height of 300 and a width of 600.
Python3
# import required libraries import torch import torchvision.transforms as transforms from PIL import Image # Read image image = Image. open ( 'pic.png' ) # create an transform for crop the image # 300px height and 600px wide transform = transforms.RandomResizedCrop(size = ( 300 , 600 )) # use above created transform to crop # the image image_crop = transform(image) # display result image_crop.show() |
Output:
Example 2:
In this example, we crop an image at a random location with the expected scale of 0.2 to 0.8.
Python3
# import required libraries import torch import torchvision.transforms as transforms from PIL import Image # Read image image = Image. open ( 'a.png' ) # create an transform for crop the image transform = transforms.RandomResizedCrop(size = ( 300 , 600 ), scale = ( 0.2 , 0.8 )) # use above created transform to crop # the image image_crop = transform(image) # display result image_crop.show() |
Output:
Example 3:
In this example, we crop an image at a random location with the expected ratio of 0.5 to 1.08.
Python3
# import required libraries import torch import torchvision.transforms as transforms from PIL import Image # Read image image = Image. open ( 'a.png' ) # create an transform for crop the image transform = transforms.RandomResizedCrop( size = ( 300 , 600 ), scale = ( 0.2 , 0.8 ), ratio = ( 0.5 , 1.08 )) # use above created transform to crop # the image image_crop = transform(image) # display result image_crop.show() |
Output: