In this article, we are going to see how to rotate an image by an angle in PyTorch. To achieve this, we can use RandomRotation() method. RandomRotation() transform accepts both PIL and tensor images. A Tensor Image is a tensor with (C, H, W) shape, C is for the number of channels, H and W are for the height and width of the image respectively.
Syntax: torchvision.transforms.RandomRotation(Degrees, expand=False, center=None, fill=0, resample=None)
Parameters:
- Degrees – The Range of degrees in which we want to rotate our image.
- expand – This is an optional Parameter. If it will true, expands the output to make it large enough to hold the entire rotated image and If it will false or omitted then make the output image the same size as the input image. Note that the expand flag assumes rotation around the center and no translation.
- center – This is also a optional parameter. it’s center of rotation, (x, y). Origin is the upper left corner and the default is the center of the image.
- fill – Pixel fill value for the area outside the rotated image. Default is 0. If given a number then the value is used for all bands respectively.
- resample – This is also an optional parameter.
This image is used as the input image in the following examples.
Example 1:
The following program is to rotate the image from the range of 60 to 90 degrees.
Python3
# import required libraries import torch import torchvision.transforms as T from PIL import Image # read the image img = Image. open ( 'GFG.jpg' ) # define a transform to rotate the image transform = T.RandomRotation(degrees = ( 60 , 90 )) # use above transform to rotate the image img = transform(img) # display result img.show() |
Output:
Example 2:
The following program is to rotate the image from the range of 30 to 45 degrees.
Python3
# import required libraries import torch import torchvision.transforms as T from PIL import Image # read image img = Image. open ( 'a.jpg' ) # define a transform transform = T.RandomRotation(degrees = ( 30 , 45 )) # use above transform to rotate the image img = transform(img) # display result img.show() |
Output: