首页 > 解决方案 > 使用蒙版制作透明区域

问题描述

我有一批需要透明背景的图像。我能够创建较亮和较暗区域的黑色/白色蒙版,并希望使用此蒙版来保持蒙版中的白色像素不变,并将所有像素设置为透明,即黑色。迄今为止我得到的最好的结果

convert $FILE -rotate "-90<" $ROTATED
convert $ROTATED \
  +dither \
  -colors 2 \
  -fill black \
  -draw 'color 0,0 floodfill' \
  -flop \
  -draw 'color 0,0 floodfill' \
  -flop \
  -white-threshold 0 \
  $MASK
convert $ROTATED -mask $MASK -compose copy-opacity -composite $OUT

但是最后一个命令只是“重影”了整个图像。如何“切掉”黑色像素并保持白色像素不变?

这是我到目前为止所得到的。

原图 鬼结果

标签: imagemagickimagemagick-convert

解决方案


您只需从命令行中删除“-mask”,留下您的掩码图像(并添加 -alpha 关闭)。所以以下在 ImageMagick 6 中对我来说很好。

输入:

在此处输入图像描述

convert star.png \
+dither \
-colors 2 \
-fill black \
-draw 'color 0,0 floodfill' \
-flop \
-draw 'color 0,0 floodfill' \
-flop \
-white-threshold 0 \
mask.png
convert star.png mask.png -alpha off -compose copy-opacity -composite out.png

面具:

在此处输入图像描述

结果:

在此处输入图像描述

下载结果可以看到背景是完全透明的。

如果使用 Imagemagick 7,则更convert改为magick

添加

这是使用 MPR 执行此操作的一种方法。注意+交换。

convert star.png \
-write mpr:star \
+dither \
-colors 2 \
-fill black \
-draw 'color 0,0 floodfill' \
-flop \
-draw 'color 0,0 floodfill' \
-flop \
-white-threshold 0 \
mpr:star \
+swap \
-alpha off \
-compose copy-opacity -composite \
out.png

您也可以使用克隆和括号来完成。

convert star.png \
\( +clone  \
+dither \
-colors 2 \
-fill black \
-draw 'color 0,0 floodfill' \
-flop \
-draw 'color 0,0 floodfill' \
-flop \
-white-threshold 0 \) \
-alpha off \
-compose copy-opacity -composite \
out.png

我得到与上面相同的结果。


推荐阅读