How to adjust the contrast of an image in PyTorch
Last Updated :
09 Oct, 2022
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 channels, and H W is the image height and width respectively. This method also accepts a batch of tensors as input with shape [B, C, H, W] where B is the number of images in the batch. and C, H, and W are the number of channels image height and width respectively. This method returns a Contrast adjusted image. before moving further let’s see the syntax of the adjust_contrast() method.
Syntax: adjust_contrast(img, contrast_factor)
Parameters:
- img: This is our PIL or tensor image of which the contrast is to be adjusted.
- contrast_factor: This is a non-negative float number. 0 and 1 gives solid gray original image respectively.
Returns: This method returns a Contrast adjusted image:
The below image is used for demonstration:
image is used for demonstration
Example 1:
In this example, we are adjusting the contrast of an image in PyTorch when the contrast_factor is 0.5.
Python3
import torch
from PIL import Image
import torchvision.transforms.functional as con
input_img = Image. open ( 'image.png' )
input_img = con.adjust_contrast(input_img, 0.5 )
input_img.show()
|
Output:
image is used for demonstration
Example 2:
In this example, we are adjusting the contrast of an image in PyTorch when the contrast_factor is 0.
Python3
import torch
from PIL import Image
import torchvision.transforms.functional as con
input_img = Image. open ( 'a.png' )
input_img = con.adjust_contrast(input_img, 0 )
input_img.show()
|
Output
image is used for demonstration
Example 3:
In this example, we are adjusting the contrast of an image in PyTorch when the contrast_factor is 1.
Python3
import torch
from PIL import Image
import torchvision.transforms.functional as con
input_img = Image. open ( 'a.png' )
input_img = con.adjust_contrast(input_img, 1 )
input_img.show()
|
Output
image is used for demonstration
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...