How to pad an image on all sides in PyTorch?

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 librariesimport torchimport torchvision.transforms as transformsfrom PIL import Image# Read the image from your computerimg = Image.open('zambiateklogo.png')# get width and height of imagew, h = img.size# pad 100 to left/right and 50 to top/bottomtransform = transforms.Pad((100, 50))# add padding to imageimg = transform(img)# resize the image to original dimensionimg = img.resize((w, h))# display outputimg.show() | 
Output:
Example 2:
In this example, we will see how to add unique padding space to all sides.
Python3
# import required librariesimport torchimport torchvision.transforms as transformsfrom PIL import Image# Read the image from your computerimg = Image.open('zambiateklogo.png')# get width and height of imagew, h = img.size# pad 10 to left, 20 to top, 30 to right, # 50 bottomtransform = transforms.Pad((10, 20, 50, 50))# add padding to imageimg = transform(img)# resize the image to original dimensionimg = img.resize((w, h))# display outputimg.show() | 
Output:
				
					


