简体   繁体   中英

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.

在此处输入图片说明

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?

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')

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

在此处输入图片说明

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.

You can do this quite easily with PIL , like this:

  1. Ensure the image is represented as RGBA , by using convert('RGBA') .
  2. Split the image into seperate RGBA bands.
  3. Do what ever you want to the RGB bands (in your case we set them all to black by using the point function), but don't touch the alpha band.
  4. Merge the bands back.

heres the code:

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')

give it a shot.

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

Probably the fastest solution so far, since it doesn't interpret any Python code inside a "for each pixel" loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM