How to adjust the contrast of an image in PyTorch?


The contrast of an image refers to the amount of color differentiation that exists between the various features of an image. To adjust the contrast of an image, we apply adjust_contrast(). It's one of the functional transforms provided by the torchvision.transforms module. This module contains many important functional transformations that can be used to perform different types manipulations on the image data.

adjust_contrast() transformation accepts both PIL and tensor images. A tensor image is a PyTorch tensor with shape [C, H, W], where C is the number of channels, H is the image height, and W is the image width. This transform also accepts a batch of tensor images which is a tensor with [B, C, H, W] where B is the number of images in the batch. If the image is neither a PIL image nor a tensor image, then we first convert it to a tensor image and then apply the adjust_contrast(). All the functional transforms can be accessed from torchvision.transforms.functional.

Syntax

torchvision.transforms.functional.adjust_contrast(img, contrast_factor)

Parameters

  • img - It's the image of which the contrast is to be adjusted. It is a PIL image or torch tensor. It may be a single image or a batch of images.

  • contrast_factor - A non-negative number. 0 gives a solid gray image, 1 gives the original image.

Output

It returns the contrast adjusted image.

Steps

To adjust the contrast of an image, one could follow the steps given below

  • Import the required libraries. In all the following examples, the required Python libraries are torch., Pillow,and torchvision Make sure you have already installed them.

import torch
import torchvision
import torchvision.transforms.functional as F
from PIL import Image
  • Read the input image. The input image is a PIL image or a torch tensor.

img = Image.open('Nature_canada.jpg')
  • Adjust the contrast of the image with the desired contrast factor.

img = F.adjust_contrast(img, 0.3)
  • Visualize the contrast adjusted image.

img.show()

Input Images

We will use this image as the input file in the following examples

Example 1

In the following Python program, we adjust the contrast of an input image with a contrast_factor=0.3.

# Import the required libraries
import torch
from PIL import Image
import torchvision.transforms.functional as F

# read the input image
img = Image.open('Nature_canada.jpg')

# adjust the contrast of the image
img = F.adjust_contrast(img, 0.3)

# display the contrast adjusted image
img.show()

Output

Example 2

In the following Python program, we adjust the contrast of an input image with a contrast_factor=6. 

import torch
from PIL import Image
import torchvision.transforms.functional as F

img = Image.open('Nature_canada.jpg')
img = F.adjust_contrast(img, 6)
img.show()

Output

Updated on: 20-Jan-2022

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements