如何使用 Wand 使图像的背景透明?

Den*_*ger 1 python imagemagick wand

我有一张白色背景的图像,想将白色背景转换为透明。我怎样才能用 Wand 做到这一点?

执行此操作的 ImageMagick 命令是:

convert ~/Desktop/cat_with_white_gb.png -transparent white ~/Desktop/cat_with_transparent_bg.png
Run Code Online (Sandbox Code Playgroud)

我试过了:

import urllib2

fg_url = 'http://i.stack.imgur.com/Mz9y0.jpg'
fg = urllib2.urlopen(fg_url)

with Image(file=fg) as img:
    img.background_color = Color('transparent')
    img.save(filename='test.png')
Run Code Online (Sandbox Code Playgroud)

with Image(file=fg) as fg_img:
    with Color('#FFF') as white:
        fg_img.transparent_color(white, 0.0)
Run Code Online (Sandbox Code Playgroud)

emc*_*lle 5

要记住的重要事情是 JPEG 源图像没有 alpha 通道。您可以通过定义来添加它wand.image.Image.alpha_channel,或者只是将图像格式设置为可以使用透明度的格式。

from wand.image import Image
from wand.color import Color

with Image(filename="http://i.stack.imgur.com/Mz9y0.jpg") as img:
    img.format = 'png'
    with Color('#FDFDFD') as white:
        twenty_percent = int(65535 * 0.2)  # Note: percent must be calculated from Quantum
        img.transparent_color(white, alpha=0.0, fuzz=twenty_percent)
    img.save(filename="/tmp/Mz9y0.png")
Run Code Online (Sandbox Code Playgroud)

透明猫

在这个例子中,20% 的模糊可能过于激进