This article will demonstrate the method to apply FiveCrop transformation in PyTorch.
How to Apply FiveCrop Transformation on an Image in PyTorch?
To apply FiveCrop transformation on a specific image in PyTorch, look at the below-provided steps:
- Upload an image to Google Colab
- Import necessary libraries
- Read input image
- Define a transform for cropping images
- Apply the transform on the input image
- Display cropped images
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 apply FiveCrop transformation to it:
Step 2: Import Required Library
Next, import the required libraries. For instance, we have imported the following libraries:
import torchvision.transforms as transforms
from PIL import Image
import matplotlib.pyplot as plt
Here:
- “import torch” imports the PyTorch library.
- “import torchvision.transforms as transforms” imports the transforms module from torchvision that is used to preprocess image data before feeding it into a neural network.
- “from PIL import Image” opens and saves different image file formats.
- “import matplotlib.pyplot as plt” imports the “pyplot” module that is used to create visualizations and plots:
Step 3: Read the Input Image
After that, read the input image from the computer. Here, we are reading the “room.jpg” and storing it in the “input_img” variable:
Step 4: Create a Transform
Next, define a transform using the “FiveCrop()” method to crop the input image into a central crop and four corners:
Step 5: Apply the Transform on the Image
Now, apply the above transform on the desired input image:
Step 6: Display Cropped Images
Lastly, define a figure of size, row, and cols in the figure and view all the cropped images by displaying it:
row, col = 1, 5
for j in range(0, col*row):
fig.add_subplot(row, col, j+1)
plt.imshow(trans_imgs[j])
plt.xticks([])
plt.yticks([])
plt.show()
Comparison
The comparison between the original image and the cropped images can be seen below:
Note: You can access our Google Colab Notebook at this link.
We have efficiently explained the method of applying FiveCrop transformation on an image in PyTorch.
Conclusion
To apply FiveCrop transformation on an image in PyTorch, first, upload the desired image to Google Colab. Then, import the necessary libraries and read the input image. Next, use the “FiveCrop()” method to define and apply the transform on the desired input image to crop it. Finally, display the new cropped images. This article demonstrates the method to apply FiveCrop transformation in PyTorch.