Skip to content
Related Articles

Related Articles

How to Randomly change the brightness, contrast, saturation and hue of an image in PyTorch

Improve Article
Save Article
  • Last Updated : 27 Jun, 2022
Improve Article
Save Article

 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, tensor images, and a batch of tensor images as input. The batch of tensor images is a tensor with shape [B, C, H, W], where B is the number of images in the batch. The tensor image is a PyTorch tensor with [C, H, W] shape, where C represents the number of channels and H, W represents the image height and width respectively. This method returns a new image with Randomly changed brightness, contrast, saturation, and hue from the given respective range. Let’s see the syntax of this method.

Syntax: torchvision.transforms.ColorJitter(brightness=0, contrast=0, saturation=0, hue=0)

Parameter:

  • brightness: How much to jitter brightness. it must be non negative number.
  • contrast: How much to jitter contrast and it also be non negative number.
  • saturation: How much to jitter saturation and it Should be non negative number.
  • hue: How much to jitter hue. it Should have 0<= hue <= 0.5 or -0.5 <= min <= max <= 0.5.

Return: This method returns a new image with Randomly changed brightness, contrast, saturation and hue from the given respective range.

The below image is used for demonstration:

 

Example 1:

In this example, we are going to see how to Randomly change the brightness, contrast, saturation, and hue of an image using the ColorJitter() function in PyTorch.

Python3




# import required libraries
import torch
import torchvision.transforms as transforms
from PIL import Image
  
# Read the image from computer
input_img = Image.open('img.png')
  
# define a transform
transform = transforms.ColorJitter(
    brightness=0.5, contrast=1, saturation=0.1, hue=0.5)
  
# apply the above transform on image
output_img = transform(input_img)
  
# display result
output_img.show()


Output:

 

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!