The Wayback Machine - https://web.archive.org/web/20240916011641/https://www.geeksforgeeks.org/how-to-pad-an-image-on-all-sides-in-pytorch/
Open In App

How to pad an image on all sides in PyTorch?

Last Updated : 26 Apr, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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?

 



Similar Reads

How to Pad the Input Tensor Boundaries with Zero in PyTorch
In this article, we will discuss how to pad the input tensor boundaries with zero in Python using PyTorch. torch.nn.ZeroPad2D() method This method has accepted the size of padding as input and returns a new tensor with boundaries. The boundaries may be the same or different from all sides (left, right, top, bottom). we can increase the height and w
2 min read
How to Pad the Input Tensor Boundaries With a Constant Value in PyTorch?
In this article, we will discuss How to Pad the Input Tensor Boundaries With a Constant Value in PyTorch. We can pad the input tensor boundaries with a constant value by using torch.nn.ConstantPad2D() method. torch.nn.ConstantPad2D() method We can pad the boundaries of 3D and 4D tensors and the shape of the input tensor is [C, H, W] and [N, C, H, W
3 min read
PyTorch vs PyTorch Lightning
The PyTorch research team at Facebook AI Research (FAIR) introduced PyTorch Lightning to address these challenges and provide a more organized and standardized approach. In this article, we will see the major differences between PyTorch Lightning and Pytorch. Table of Content PytorchPytorch Lightning: Advanced Framework of PytorchPytorch vs Pytorch
9 min read
How to disable GPU in PyTorch (force Pytorch to use CPU instead of GPU)?
PyTorch is a deep learning framework that offers GPU acceleration. This enables the users to utilize the GPU's processing power. The main goal is to accelerate the training and interference processes of deep learning models. PyTorch automatically utilizes the GPU for operations and this leads to quicker computation times. Using the GPU for PyTorch
5 min read
Python | Pandas Series.str.pad()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas provide a method to add padding (whitespaces or other characters) to every string element in a series. .str has to be prefixed ev
4 min read
Pad or fill a string by a variable in Python using f-string
f-string stands for formatted string. It had come up by Python Version 3.6 and rapidly used to do easy formatting on strings. F-string is a string literal having syntax starts with f and followed by {}. That placeholder used for holding variable, that will be changed upon the variable names and their values respectively. There are already strings f
4 min read
numpy.pad() function in Python
numpy.pad() function is used to pad the Numpy arrays. Sometimes there is a need to perform padding in Numpy arrays, then numPy.pad() function is used. The function returns the padded array of rank equal to the given array and the shape will increase according to pad_width. Syntax: numpy.pad(array, pad_width, mode='constant', **kwargs) Parameters :
2 min read
Rotate image without cutting off sides using Python - OpenCV
Prerequisite: Image Processing in Python (Scaling, Rotating, Shifting and Edge Detection) Rotating images with OpenCV is easy, but sometimes simple rotation tasks cropped/cut sides of an image, which leads to a half image. Now, In this tutorial, We will explore a solution to safely rotate an image without cropping/cutting sides of an image so that
6 min read
Image Datasets, Dataloaders, and Transforms in Pytorch
Deep learning in Pytorch is becoming increasingly popular due to its ease of use, support for multiple hardware platforms, and efficient processing. Image datasets, dataloaders, and transforms are essential components for achieving successful results with deep learning models using Pytorch. In this article, we will discuss Image datasets, dataloade
7 min read
How to Adjust Saturation of an image in PyTorch?
In this article, we are going to discuss How to adjust the saturation of an image in PyTorch. adjust_saturation() method Saturation is basically used to adjust the intensity of the color of the given Image, we can adjust the saturation of an image by using the adjust_saturation() method of torchvision.transforms module. The method accepts a batch o
2 min read
How to convert an image to grayscale in PyTorch
In this article, we are going to see how to convert an image to grayscale in PyTorch. torchvision.transforms.grayscale method Grayscaling is the process of converting an image from other color spaces e.g. RGB, CMYK, HSV, etc. to shades of gray. It varies between complete black and complete white. torchvision.transforms.grayscale() method is used to
2 min read
How to Find Mean Across the Image Channels in PyTorch?
In this article, we are going to see how to find mean across the image channels in PyTorch. We have to compute the mean of an image across the channels Red, Green, and, Blue. we can find the mean across the image channel by using torch.mean() method. torch.mean() method torch.mean() method is used to find the mean of all elements in the input tenso
2 min read
Implement Deep Autoencoder in PyTorch for Image Reconstruction
Since the availability of staggering amounts of data on the internet, researchers and scientists from industry and academia keep trying to develop more efficient and reliable data transfer modes than the current state-of-the-art methods. Autoencoders are one of the key elements found in recent times used for such a task with their simple and intuit
8 min read
How to rotate an image by an angle using PyTorch in Python?
In this article, we are going to see how to rotate an image by an angle in PyTorch. To achieve this, we can use RandomRotation() method. RandomRotation() transform accepts both PIL and tensor images. A Tensor Image is a tensor with (C, H, W) shape, C is for the number of channels, H and W are for the height and width of the image respectively. Synt
2 min read
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 metho
2 min read
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. 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 channel
2 min read
How to perform random affine transformation of an image in PyTorch
In this article, we will cover how to perform the random affine transformation of an image in PyTorch. RandomAffine() method RandomAffine() method accepts PIL Image and Tensor Image. The tensor image is a PyTorch tensor with [C, H, W] shape, where C represents the number of channels and H, W represents the height and width respectively. This method
2 min read
How to draw bounding boxes on an image in PyTorch?
In this article, we are going to see how to draw bounding boxes on an image in PyTorch. draw_bounding_boxes() method The draw_bounding_boxes function helps us to draw bounding boxes on an image. With tensor we provide shapes in [C, H, W], where C represents the number of channels and H, W represents the height and width respectively, this function
2 min read
Invert the Colors of an Image Randomly with a given Probability in PyTorch
In this article, we will discuss how to invert the colors of an image randomly with a given probability in Python using PyTorch. RandomInvert() method RandomInvert() method accepts PIL and tensor image as input. With tensor, we provide shapes in [3, H, W], where H and W are the height and width of the image. This method returns a Randomly colored i
1 min read
How to Read a JPEG or PNG Image in PyTorch
In this article, we are going to discuss how to Read a JPEG or PNG Image using PyTorch in Python. image_read() method In PyTorch, the image_read() method is used to read an image as input and return a tensor of size [C, H, W], where C represents a number of channels and H, W represents height and width respectively. The below syntax is used to read
2 min read
How to Randomly change the brightness, contrast, saturation and hue of an image in PyTorch
In this article, we are going to discuss How to Randomly change the brightness, contrast, saturation, and hue of an image in PyTorch. we can randomly change the brightness, contrast, saturation, and hue of an image by using ColorJitter() method of torchvision.transforms module. ColorJitter() method: The ColorJitter() method accepts PIL images, tens
2 min read
How to adjust the contrast of an image in PyTorch
In this article, we are going to see how to adjust the contrast of an image in PyTorch using Python. We can adjust the contrast of an image by using the adjust_contrast() method. adjust_contrast() method adjust_contrast() method accepts the PIL and tensor images as input. tensor image is a tensor with [C, H, W] shape, where C is the number of chann
2 min read
Standard Deviation Across the Image Channels in PyTorch
In Python, image processing and computer vision tasks often require the calculation of statistical metrics across the color channels of an image. The standard deviation, which measures how far apart values in a dataset are from the mean, is one such metric. In this article, we'll look at how to use PyTorch to find the standard deviation across all
4 min read
Displaying a Single Image in PyTorch
Displaying images is a fundamental task in data visualization, especially when working with machine learning frameworks like PyTorch. This article will guide you through the process of displaying a single image using PyTorch, covering various methods and best practices. Table of Content Understanding Image Tensors in PyTorchLoading an Image With Py
4 min read
PyQt5 – Setting padding size at different sides of Status Bar
In this article we will see how to set different padding size for different edges of Status Bar. Status bar allows us to set only padding for top and bottom edge, there is no padding available for right or left edge. We can set padding using padding in Style Sheet, in order to set different padding sizes we will use padding-top and padding-bottom i
2 min read
Python | PyTorch sin() method
PyTorch is an open-source machine learning library developed by Facebook. It is used for deep neural network and natural language processing purposes. The function torch.sin() provides support for the sine function in PyTorch. It expects the input in radian form and the output is in the range [-1, 1]. The input type is tensor and if the input conta
2 min read
Create Model using Custom Module in Pytorch
Custom module in Pytorch A custom module in PyTorch is a user-defined module that is built using the PyTorch library's built-in neural network module, torch.nn.Module. It's a way of creating new modules by combining and extending the functionality provided by existing PyTorch modules. The torch.nn.Module class provides a convenient way to create cu
8 min read
Graphs, Automatic Differentiation and Autograd in PyTorch
Graphs, Automatic Differentiation and Autograd are powerful tools in PyTorch that can be used to train deep learning models. Graphs are used to represent the computation of a model, while Automatic Differentiation and Autograd allow the model to learn by updating its parameters during training. In this article, we will explore the concepts behind t
7 min read
Install Pytorch on Linux
In this article, we are going to see how you can install PyTorch in the Linux system. We are using Ubuntu 20 LTS you can use any other one. To successfully install PyTorch in your Linux system, follow the below procedure: First, check if you are using python’s latest version or not. Because PyGame requires python 3.7 or a higher version, make sure
2 min read
Python | PyTorch sinh() method
PyTorch is an open-source machine learning library developed by Facebook. It is used for deep neural network and natural language processing purposes. The function torch.sinh() provides support for the hyperbolic sine function in PyTorch. It expects the input in radian form. The input type is tensor and if the input contains more than one element,
2 min read
Article Tags :
Practice Tags :