我正在尝试使用 Python Wand 实现以下 ImageMagick 命令:
convert red_image.png green_image.png write_mask.png -composite masked_composite.png
这是图片中的示例:
有什么提示吗?
更新:如果有人想知道,这是我的解决方案。注意:不优雅,但有效。
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/