Open In App

How to pad an image on all sides in PyTorch?

Last Updated : 26 Apr, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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

transforms.pad() method

Paddings are used to create some space around the image, inside any defined border. We can set different paddings for individual sides like (top, right, bottom, left). transforms.Pad() method is used for padding an image. This method accepts images like PIL Image and Tensor Image. The tensor image is a PyTorch tensor with [C, H, W] shape, Where C is the number of channels and H, W is the height and width respectively. The below syntax is used to pad an image.

Syntax: transforms.Pad(N)

Parameter:

  • N: Padding on each border

Return : This method returns an image with padding.

Package Requirement

pip install torchvision
pip install Pillow

Image used for demonstration:

 

Example 1:

In this example, we will see how to pad N to left/right and M to top/bottom padding for all the sides.

Python3




# import required libraries
import torch
import torchvision.transforms as transforms
from PIL import Image
 
# Read the image from your computer
img = Image.open('geekslogo.png')
 
# get width and height of image
w, h = img.size
 
# pad 100 to left/right and 50 to top/bottom
transform = transforms.Pad((100, 50))
 
# add padding to image
img = transform(img)
 
# resize the image to original dimension
img = img.resize((w, h))
 
# display output
img.show()


Output:

How to pad an image on all sides in PyTorch?

 

Example 2:

In this example, we will see how to add unique padding space to all sides.

Python3




# import required libraries
import torch
import torchvision.transforms as transforms
from PIL import Image
 
# Read the image from your computer
img = Image.open('geekslogo.png')
 
# get width and height of image
w, h = img.size
 
# pad 10 to left, 20 to top, 30 to right,
# 50 bottom
transform = transforms.Pad((10, 20, 50, 50))
 
# add padding to image
img = transform(img)
 
# resize the image to original dimension
img = img.resize((w, h))
 
# display output
img.show()


Output:

How to pad an image on all sides in PyTorch?

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads