Search code examples
wand

How to change all colors to transparent but one?


Using the Wand 0.6.2 library I try to remove all colors but one, I got to the desired result using ImageMagick by:

imageMagicCmd = ["magick.exe", "can.jpg",
             "-alpha","Set", "(", "+clone", "-fuzz", "40%", "-transparent", "rgb(255,0,0)", ")",
             "-compose", "DstOut", "-composite", "SingleColor_Red.png"] 
subprocess.call(imageMagicCmd)

can.jpg image: can.jpg

SingleColor_Red.png image: SingleColor_Red.png

How can I achieve the same result using the Wand library?


Solution

  • Try the following...

    from wand.image import Image
    
    with Image(filename="can.jpg") as img:
        img.alpha_channel = 'set'
        f = int(img.quantum_range * 0.4)
        img.transparent_color('#f00', 0.0, fuzz=f, invert=True)
        img.save(filename="output.png")
    

    ... which should generate the expected results.

    output.png