使用遮罩制作透明区域

时间:2021-05-20 07:53:49

标签: imagemagick imagemagick-convert

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

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

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

这是我目前得到的。

Origin image Ghost result

1 个答案:

答案 0 :(得分:1)

您只需要从命令行中删除“-mask”,留下您的蒙版图像(并添加-alpha 关闭)。因此,以下在 ImageMagick 6 中对我来说效果很好。

输入:

enter image description here

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

面具:

enter image description here

结果:

enter image description here

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

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

添加

这是使用 MPR 做到这一点的一种方法。注意 +swap。

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

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