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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With