How To Invert Image In Python

In this tutorial, we will learn how to invert the colors of an image using Python. Inverting an image is simply the process of replacing each color value (Red, Green, or Blue) with its complement, such as 255 minus its current value.

We’ll use Python’s popular imaging library, Pillow (Python Imaging Library), to perform this task.

Step 1: Use Image

Step 2: Install Pillow

First, you need to install the Pillow library. You can do this using pip. Open your terminal or command prompt and run:

Step 3: Import the Necessary Libraries

Now, you need to import the required libraries. In this case, we only need the Image module from the PIL library:

Step 4: Load the Image

Load the image that you want to invert using the Image.open() function:

Replace ‘robot.jpg’ with the actual image file name.

Step 5: Invert the Image

To invert the image, you can use the ImageOps.invert() function from the ImageOps module. First, import the module:

Now, you can invert the image colors by calling the invert() function and passing the image object:

Step 6: Save the Inverted Image

Finally, save the inverted image using the save() function:

This will save the inverted image with the filename ‘inverted_image.jpg’ in the same directory as the original image.

Step 7: Display the Inverted Image (Optional)

If you want to display the inverted image, you can use the show() function:

This will open the inverted image in your system’s default image viewer.

Full Code

Here is the complete code for inverting an image using Python and the Pillow library:

Make sure to replace ‘robot.jpg’ with your actual image file name.

Output

Conclusion

In this tutorial, we learned how to invert the colors of an image using Python and the Pillow library. By following these simple steps, you can easily invert images and perform other image manipulation tasks using the powerful Pillow library.