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

I have a set of white icons on a transparent background, and I would like to invert them so that they are black on a transparent background.

enter image description here

Tried with PIL (ImageChops), but it does not work with transparent background. I also tried the Python Gimp interface, but no luck there either.

Any idea how to invert best in Python?

+5
source share
4 answers

ImageChops.invert also inverts the alpha channel of each pixel.

This should complete the task:

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')
+5
source

I tried the Acorn approach, but the result is somewhat weird (top of the image below).

enter image description here

- , , , Image Magick convert method:

convert tools.png -negate tools_black.png

( , python, PythonMagickWand.

, , ImageMagick , , , .

+1

PIL, :

  • , RGBA, convert('RGBA').
  • RGBA.
  • , - RGB ( point), -.
  • .

:

import Image
im = Image.open('image.png')
im = im.convert('RGBA')
r, g, b, a = im.split()
r = g = b = r.point(lambda i: 0)
im = Image.merge('RGBA', (r, g, b, a))
im.save('saved.png')

.

0
import Image, numpy
pixels = numpy.array(Image.open('myimage.png'))
pixels[:,:,0:3] = 255 - pixels[:,:,0:3] # invert
Image.fromarray(pixels).save('out.png')

This is probably the fastest solution since it does not interpret Python code inside the "for every pixel" loop.

0
source

All Articles