How to invert colors of image with Pillow?


Pillow - Invert colors of image

To invert colors of an image using Pillow, you can use ImageOps.invert() function of ImageOps module.

Python Pillow - Invert colors of image

Steps to invert an image

Follow these steps to invert the colors of an image.

  1. Import Image, and ImageOps modules from Pillow library.
  2. Read input image using Image.open() function.
  3. Pass the read input Image object as argument to the ImageOps.invert() function. The function returns inverted image as PIL.Image.Image object.
  4. Save the returned image to required location using Image.save() function.

Syntax of invert() function

The syntax of invert() function from PIL.ImageOps module is

PIL.ImageOps.invert(image)
ParameterDescription
imageAn PIL.Image.Image object. This is the source or original image which we would like to invert the colors.

Returns

The function returns a PIL.Image.Image object.

The original image is unchanged.

Examples

1. Invert colors of given image

In the following example, we read an image test_image.jpg, invert its colors using ImageOps.invert() function, and save the resulting image as inverted_image.jpg.

Python Program

from PIL import Image, ImageOps

# Open the image
image = Image.open("test_image.jpg")

# Invert the colors of the image
inverted_image = ImageOps.invert(image)

# Save the resulting image
inverted_image.save("inverted_image.jpg")

Original Image [test_image.jpg]

Python Pillow - Invert colors of image - Input image

Resulting Image with Inverted Colors [inverted_image.jpg]

Python Pillow - Invert colors of image - Inverted image

Summary

In this Python Pillow Tutorial, we learned how to invert the colors of a given image using PIL.ImageOps.invert() function, with the help of examples.