问题
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:
- Ensure the image is represented as
RGBA
, by usingconvert('RGBA')
. - Split the image into seperate
RGBA
bands. - Do what ever you want to the
RGB
bands (in your case we set them all to black by using thepoint
function), but don't touch the alpha band. - 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