I need to convert series of images drawn as white on black background letters to images where white and black are inverted (as negative). How can I achieve this using PIL?
Invert Images Using bitwise_not() Method in Python It considers that you have an image by the name of image. png in your working directory. This program will first load an image, invert it and save it in the working directory. After that, it will show both the original and the inverted images.
Open Microsoft Paint. Go to “File > Open” or simply press Ctrl + O keys to open an image in Paint. Press Ctrl + A keys to select the entire image. Now, right-click on the image and select the Invert color option.
Invert the image by pressing the shortcut key Ctrl + I .
Try the following from the docs: http://effbot.org/imagingbook/imageops.htm
from PIL import Image import PIL.ImageOps image = Image.open('your_image.png') inverted_image = PIL.ImageOps.invert(image) inverted_image.save('new_name.png')
Note: "The ImageOps module contains a number of 'ready-made' image processing operations. This module is somewhat experimental, and most operators only work on L and RGB images."
If the image is RGBA transparent this will fail... This should work though:
from PIL import Image import PIL.ImageOps image = Image.open('your_image.png') if image.mode == 'RGBA': r,g,b,a = image.split() rgb_image = Image.merge('RGB', (r,g,b)) inverted_image = PIL.ImageOps.invert(rgb_image) r2,g2,b2 = inverted_image.split() final_transparent_image = Image.merge('RGBA', (r2,g2,b2,a)) final_transparent_image.save('new_file.png') else: inverted_image = PIL.ImageOps.invert(image) inverted_image.save('new_name.png')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With