RandomResizedCrop() Method in Python PyTorch
Last Updated :
03 Jun, 2022
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 torch
import torchvision.transforms as transforms
from PIL import Image
image = Image. open ( 'pic.png' )
transform = transforms.RandomResizedCrop(size = ( 300 , 600 ))
image_crop = transform(image)
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 torch
import torchvision.transforms as transforms
from PIL import Image
image = Image. open ( 'a.png' )
transform = transforms.RandomResizedCrop(size = ( 300 , 600 ),
scale = ( 0.2 , 0.8 ))
image_crop = transform(image)
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 torch
import torchvision.transforms as transforms
from PIL import Image
image = Image. open ( 'a.png' )
transform = transforms.RandomResizedCrop(
size = ( 300 , 600 ), scale = ( 0.2 , 0.8 ), ratio = ( 0.5 , 1.08 ))
image_crop = transform(image)
image_crop.show()
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...