Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invert colors of image with PIL (Python-Imaging)?

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?

like image 672
bialix Avatar asked Mar 23 '10 09:03

bialix


People also ask

How do you invert an image in Python?

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.

How do I invert the colors on an image?

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.

How do you invert the colors on a JPEG?

Invert the image by pressing the shortcut key Ctrl + I .


2 Answers

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."

like image 151
Gary Kerr Avatar answered Oct 19 '22 23:10

Gary Kerr


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') 
like image 21
Dave Avatar answered Oct 19 '22 22:10

Dave