Tuesday, February 24, 2026
HomeLanguagesPython PyTorch – RandomHorizontalFlip() Function

Python PyTorch – RandomHorizontalFlip() Function

In this article, we will discuss the RandomHorizontalFlip() Method in PyTorch Python.

RandomHorizontalFlip() method

RandomHorizontalFlip() method of torchvision.transforms module is used to horizontally flip the given image at a random angle with a given probability. This method accepts a PIL and tensor image as input. The tensor image is a PyTorch tensor with shape [C, H, W], where C represents the number of channels and  H, W represents the height and width respectively. This method returns a horizontally flipped image and an original image if the probability P is 1 or 0 respectively, if P is in the range between 0 to 1 then P is the probability to return the horizontally flipped image.

Syntax: torchvision.transforms.RandomHorizontalFlip(p)(img)

Parameter:

  • p: p is the probability of the image being flipped at a random angle.
  • img: input image to be flipped.  

Returns: This method returns a randomly flipped image  at a random angle.

The below image is used for demonstration:

 

Example 1:

In this example, we flip an image using RandomHorizontalFlip() Method when the probability is 1.

Python3




# import required libraries
import torch
import torchvision.transforms as T
from PIL import Image
  
# read input image from computer
img = Image.open('a.png')
  
# define a transform
transform = T.RandomHorizontalFlip(p=1)
  
# apply above defined transform to 
# input image
img = transform(img)
  
# display result
img.show()


Output:

RandomHorizontalFlip() Method in Python PyTorch

 

Example 2:

In this example, we flip an image using RandomHorizontalFlip() Method when the probability is in the range of 0 to 1.

Python3




# import required libraries
import torch
import torchvision.transforms as T
from PIL import Image
  
# read input image from computer
img = Image.open('img.png')
  
# define a transform
transform = T.RandomHorizontalFlip(p=0.5)
  
# apply above defined transform to 
# input image
img = transform(img)
  
# display result
img.show()


Output:

RandomHorizontalFlip() Method in Python PyTorch

 

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

1 COMMENT

Most Popular

Dominic
32506 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6882 POSTS0 COMMENTS
Nicole Veronica
12005 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12099 POSTS0 COMMENTS
Shaida Kate Naidoo
7011 POSTS0 COMMENTS
Ted Musemwa
7255 POSTS0 COMMENTS
Thapelo Manthata
6967 POSTS0 COMMENTS
Umr Jansen
6956 POSTS0 COMMENTS