How to adjust the brightness of an image in PyTorch?


The brightness of an image is a measure of its intensity after the image has been captured. To adjust the brightness of an image, we apply adjust_brightness(). 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 manipulate the image data.

adjust_brightness() transformation accepts both PIL and tensor images. A tensor image is a PyTorch tensor with shape [C, H, W], where C is number of channels, H is image height, and W is image width. This transform also accepts a batch of tensor images. A batch of tensor images 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_brightness().

Syntax

torchvision.transforms.functional.adjust_brightness(img,
brightness_factor)

Parameters

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

  • brightness_factor - A non-negative float number. 0 gives a black image, 1 gives the original image.

Output

It returns the brightness adjusted image.

Steps

To adjust the brightness 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('Nature1.jpg')
  • Adjust the brightness of the image with the desired brightness factor.

img = F.adjust_brightness(img, 0.3)
  • Visualize the brightness 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 brightness of the image with a brightness_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('Nature1.jpg')

# adjust the brightness of image
img = F.adjust_brightness(img, 0.3)

# display the brightness adjusted image
img.show()

Output

Example 2

In the following Python program, we adjust the brightness of the image with a brightness_factor=1.6.

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

img = Image.open('Nature1.jpg')
img.show()
img = F.adjust_brightness(img, 1.6)
img.show()

Output

Updated on: 20-Jan-2022

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements