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

狂风中的少年 提交于 2019-12-10 13:44:19

问题


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?


回答1:


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



回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/11484204/python-invert-image-with-transparent-background-pil-gimp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!