This article will illustrate the method to rotate a particular image by a specific angle in PyTorch.
How to Rotate a Desired Image by Specific Angle in PyTorch?
To rotate a desired image by a specific angle in PyTorch, check out the below-listed steps:
- Upload a desired image to Google Colab
- Import required libraries
- Read input image
- Define a transform
- Rotate the input image using the defined transform
- Display the rotated image
Step 1: Upload an Image to Google Colab
First, open Google Colab and click on the below-highlighted icons. Then, choose the specific image from the computer and upload it:
Subsequently, the image will be uploaded to Google Colab:
Here, we have uploaded the following image and we will rotate it by a specific angle:
Step 2: Import Required Library
After that, import the necessary libraries. For instance, we have imported the following libraries:
import torchvision.transforms as T
from PIL import Image
Here:
- “import torch” imports the PyTorch library.
- “import torchvision.transforms as T” imports the transforms module from torchvision that is used to preprocess image data before feeding it into a neural network.
- “from PIL import Image” is used for opening and saving different image file formats:
Step 3: Read the Input Image
Then, read the input image from the computer. Here, we are reading the “my_img.jpg” and storing it in the “input_img” variable:
Step 4: Define a Transform
Next, define a transform to rotate the input image. Users need to specify the desired range of (min, max) degrees. Here, we have specified (30, 60) degrees and the new image will be rotated with any random angle selected from this range:
Step 5: Apply the Transform on Input Image
Now, rotate the input image by specified angles using the above-defined transform:
Step 6: Display Rotated Image
Finally, view the rotated image by displaying it:
The above output shows that the input image has been successfully rotated by random angles in the specified range of 30, and 60 degrees.
Similarly, users can also specify other ranges of degrees to rotate the image. Here, we will specify the following range to see the difference:
This will generate a new image that will be rotated with any random angle selected from the specified range of 90 and 120 degrees:
Comparison
The comparison between the original image and rotated images by different angles can be seen below:
Note: You can access our Google Colab Notebook at this link.
We have efficiently explained the method to rotate an image by different angles in PyTorch.
Conclusion
To rotate the desired image by a specific angle in PyTorch, first, upload the desired image to Google Colab. Then, import the necessary libraries and read the input image. After that, define the transform using the “RandomRotation()” method and apply it to the input image. Finally, display the new rotated image. This article has illustrated the method to rotate the desired image by a specific angle in PyTorch.