Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: invert image with transparent background (PIL, Gimp,...)

I have a set of white icons on transparent background, and I'd like to invert them all to be black on transparent background.

enter image description here

Have tried with PIL (ImageChops) but it does not seem to work with transparent backgrounds. I've also tried Gimp's Python interface, but no luck there, either.

Any idea how inverting is best achieved in Python?

like image 838
Hoff Avatar asked Jul 14 '12 13:07

Hoff


2 Answers

ImageChops.invert seems to also invert the alpha channel of each pixel.

This should do the job:

import Image

img = Image.open('image.png').convert('RGBA')

r, g, b, a = img.split()

def invert(image):
    return image.point(lambda p: 255 - p)

r, g, b = map(invert, (r, g, b))

img2 = Image.merge(img.mode, (r, g, b, a))

img2.save('image2.png')
like image 75
Acorn Avatar answered Nov 01 '22 10:11

Acorn


I have tried Acorn's approach, but the result is somewhat strange (top part of the below image).

enter image description here

The bottom icon is what I really wanted, I achieved it by using Image Magick's convert method:

convert tools.png -negate tools_black.png

(not python per se, but python wrappers exist, like PythonMagickWand.

The only drawback is that you have to install a bunch of dependencies to get ImageMagick to work, but it seems to be a powerful image manipulation framework.

like image 1
Hoff Avatar answered Nov 01 '22 08:11

Hoff