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:
1 |
pip install pillow |
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:
1 |
from PIL import Image |
Step 4: Load the Image
Load the image that you want to invert using the Image.open() function:
1 |
image = Image.open('robot.jpg') |
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:
1 |
from PIL import ImageOps |
Now, you can invert the image colors by calling the invert() function and passing the image object:
1 |
inverted_image = ImageOps.invert(image) |
Step 6: Save the Inverted Image
Finally, save the inverted image using the save() function:
1 |
inverted_image.save('inverted_image.jpg') |
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:
1 |
inverted_image.show() |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
from PIL import Image from PIL import ImageOps # Load the image image = Image.open('robot.jpg') # Invert the image inverted_image = ImageOps.invert(image) # Save the inverted image inverted_image.save('inverted_image.jpg') # Display the inverted image (optional) inverted_image.show() |
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.