Invert the Colors of an Image Randomly with a given Probability in PyTorch
RandomInvert() method
RandomInvert() method accepts PIL and tensor image as input. With tensor, we provide shapes in [3, H, W], where H and W are the height and width of the image. This method returns a Randomly colored inverted image. The below syntax is used to invert the colors of an image randomly with a given probability.
Syntax: torchvision.transforms.RandomInvert(p)(img)
Parameter:
- img: This is our input image to be inverted.
- p: it’s probability in the range of (0,1).
Return: This method returns a Randomly color inverted image. if p=0 then it will return the original image and if p=1 then it will return color inverted image.
The below image is used for demonstration:
Example:
The following program is to understand how to invert the colors of an image randomly with a given probability.
Python3
# import required libraries import torch import torchvision.transforms as T from PIL import Image # read image from your computer img = Image. open ( 'a.png' ) # invert the colors with probability=1 transform = T.RandomInvert(p = 1 ) img = transform(img) # display result img.show() |
Output: