How to rotate an image by an angle using PyTorch in Python?
Last Updated :
26 Apr, 2022
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 torch
import torchvision.transforms as T
from PIL import Image
img = Image. open ( 'GFG.jpg' )
transform = T.RandomRotation(degrees = ( 60 , 90 ))
img = transform(img)
img.show()
|
Output:
Example 2:
The following program is to rotate the image from the range of 30 to 45 degrees.
Python3
import torch
import torchvision.transforms as T
from PIL import Image
img = Image. open ( 'a.jpg' )
transform = T.RandomRotation(degrees = ( 30 , 45 ))
img = transform(img)
img.show()
|
Output:
Share your thoughts in the comments
Please Login to comment...