CenterCrop() method
We can crop an image in PyTorch by using the CenterCrop() method. This method accepts images like PIL Image, Tensor Image, and a batch of Tensor images. 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.
Syntax: torchvision.transforms.CenterCrop(size)
Parameters:
- size: Desired crop size of the image.
Return: This method is returns the cropped image of given input size.
Image used for demonstration:
Example 1:
In this example, we are transforming the image at the center. In this, we will get a square image as output.
Python3
# import required libraries import torch import torchvision.transforms as transforms from PIL import Image # Read image image = Image. open ( 'a.jpg' ) # create an transform for crop the image transform = transforms.CenterCrop( 200 ) # use above created transform to crop # the image image_crop = transform(image) # display result image_crop.show() |
Output:
Example 2:
In this example, we are transforming the image with a height of 180 and a width of 300.
Python3
# import required libraries import torch import torchvision.transforms as transforms from PIL import Image # Read image image = Image. open ( 'a.jpg' ) # define an transform, height=180 width=300 transform = transforms.CenterCrop(( 180 , 300 )) # use above created transform to crop # the image image_crop = transform(image) # display result image_crop.show() |
Output:
How to crop an image at center in PyTorch?
In this article, we will discuss how to crop an image at the center in PyTorch.