Friday, September 5, 2025
HomeLanguagesHow to crop an image at random location in PyTorch

How to crop an image at random location in PyTorch

In this article, we will discuss how to pad an image on all sides in PyTorch

Torchvision.transforms.RandomCrop method

Cropping is a technique of removal of unwanted outer areas from an image to achieve this we use a method in python that is torchvision.transforms.RandomCrop(). It is used to crop an image at a random location in PyTorch. This method accepts images like PIL Image and Tensor Image. 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.RandomCrop(size)

Parameters:

  • size: Desired crop size of the image.

Return: it returns the cropped image of given input size.

Image used for demonstration:

 

Example 1:

In this example, we are transforming the image with a height of 200 and a width of 400.

Python3




# import required libraries
import torch
import torchvision.transforms as transforms
from PIL import Image
  
# Read image
image = Image.open('pic.jpg')
  
# create an transform for crop the image
# 200px height and 400px wide
transform = transforms.RandomCrop((200, 400))
  
# use above created transform to crop
# the image
image_crop = transform(image)
  
# display result
image_crop.show()


Output:

How to crop an image at random location in PyTorch

 

Example 2:

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.RandomCrop(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 random location in PyTorch

 

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32264 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6634 POSTS0 COMMENTS
Nicole Veronica
11801 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11863 POSTS0 COMMENTS
Shaida Kate Naidoo
6750 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6701 POSTS0 COMMENTS
Umr Jansen
6718 POSTS0 COMMENTS