”;
Color inversion in Python Pillow is a popular photo effect, that transforms an image by reversing the colors to their complementary hues on the color wheel. It results in changes such as black becoming white, white becoming black, and other color shifts.
This technique, also referred to as image inversion or color negation, is a method in image processing that systematically alters the colors within an image. In a color-inverted image, the colors are transformed in such a way that light areas become dark, dark areas become light, and colors are inverted across the color spectrum.
Applying the Color Inversion to an Image
In Python Pillow, color inversion is achieved through the inversion of colors across the image spectrum. The library offers the invert() function within its ImageOps module, allowing you to apply color inversion to the images. This function is designed to negate the colors of a given image, effectively applying the color inversion effect. The syntax of the method is as follows −
PIL.ImageOps.invert(image)
Where,
-
image − This is the input image to invert.
Example
The following example creates an inverted version of an input image using the PIL.ImageOps.invert() function.
from PIL import Image import PIL.ImageOps # Open an image input_image = Image.open(''Images/butterfly.jpg'') # Create an inverted version of the image inverted_image = PIL.ImageOps.invert(input_image) # Display the input image input_image.show() # Display the inverted image inverted_image.show()
Input Image
Output inverted image
Applying the Color Inversion to RGBA Images
While most functions in the ImageOps module are designed to work with L (grayscale) and RGB images. When you attempt to apply this invert function to an image with RGBA mode (which includes an alpha channel for transparency), it will indeed raise an OSError stating that it is not supported for that image mode.
Example
Here is an example that demonstrates how to work with RGBA images while handling transparency.
from PIL import Image import PIL.ImageOps # Open an image input_image = Image.open(''Images/python logo.png'') # Display the input image input_image.show() # Check if the image has an RGBA mode if input_image.mode == ''RGBA'': # Split the RGBA image into its components r, g, b, a = input_image.split() # Create an RGB image by merging the red, green, and blue components rgb_image = Image.merge(''RGB'', (r, g, b)) # Invert the RGB image inverted_image = PIL.ImageOps.invert(rgb_image) # Split the inverted image into its components r2, g2, b2 = inverted_image.split() # Merge the inverted RGB image with the original alpha channel to maintain transparency final_transparent_image = Image.merge(''RGBA'', (r2, g2, b2, a)) # Show the final transparent image final_transparent_image.show() else: # Invert the image for non-RGBA images inverted_image = PIL.ImageOps.invert(input_image) inverted_image.show()
Input Image
Output inverted image
”;