How to Create a Negative Image with Python Code?

Estimated read time 1 min read

To create a negative image using Python, you can use the PIL (Python Imaging Library) module. Here is an example code that takes an image and creates its negative:

from PIL import Image

# Open the original image
img = Image.open("original_image.jpg")

# Invert the image
inverted_image = Image.eval(img, lambda x: 255 - x)

# Save the inverted image
inverted_image.save("negative_image.jpg")

In this code, we first open the original image using the Image.open() function from the PIL module. We then invert the image using the Image.eval() function and a lambda function that subtracts each pixel value from 255. Finally, we save the inverted image using the save() method.

Note that you need to install the Pillow module which is a fork of PIL and is more actively maintained. You can install it using pip:

pip install Pillow

Replace original_image.jpg with the filename of your input image and negative_image.jpg with the desired output filename.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply