python - 使用 Python Wand 进行合成掩蔽

标签 python imagemagick wand

我正在尝试使用 Python Wand 实现以下 ImageMagick 命令:

convert red_image.png  green_image.png  write_mask.png -composite masked_composite.png

这是图片中的示例:

enter image description here

有什么提示吗?

更新:如果有人想知道,这是我的解决方案。注意:不优雅,但有效。

bash_command = "convert "+str(red_image.png)+" "+str(green_image.png)+" write_mask.png -   composite "+str(red_image.png)+str(green_image.png)+".jpg"
os.system(bash_command)

最佳答案

解决方案是使用 copy_opacity composite operator ,它采用黑白源图像并用其内容替换目标图像的 alpha channel 。

这是我在项目中使用的 apply_mask 函数:

def apply_mask(image, mask, invert=False):
    image.alpha_channel = True
    if invert:
        mask.negate()
    with Image(width=image.width, height=image.height, background=Color("transparent")) as alpha_image:
        alpha_image.composite_channel(
            "alpha",
            mask,
            "copy_opacity",
            0, 0)
        image.composite_channel(
            "alpha",
            alpha_image,
            "multiply",
            0, 0)

首先,我要确保我们要应用蒙版的图像有一个 alpha channel ,然后检查我们是否要反转蒙版。然后我们使用蒙版替换新透明图像的 alpha channel 。我们这样做是为了将生成的 alpha channel 与目标图像上已经存在的任何 alpha channel 组合起来。如果我们在没有这个中间步骤的情况下直接将带有 copy_opacity 的蒙版应用到我们的图像,它将替换它的 alpha channel (而不是合并它们),破坏它的任何原始 alpha channel 数据。

关于python - 使用 Python Wand 进行合成掩蔽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18938614/

相关文章:

python - 使用 Wand 以预定义图案填充图像

python - 报告 qweb 未显示

python - 快速申请 : AttributeError: 'DataFrame' object has no attribute 'name'

c - MagicWand 用于 C : Lack of documentation means more errors for me

ubuntu - 在 Ubuntu 上手动安装返回 "gcc: internal compiler error: Killed (program cc1)"

python 魔杖 : how to get the text bolded?

python - ImageMagick可以用python程序打包吗?怎么做?

python - 使用 Python 从 URL 下载图像给出损坏的结果

Python循环遍历一系列变量

node.js - Graphicsmagick Node 不写入 jpg