Search code examples
imagemagickimagemagick-convert

Make transparent regions using a mask


I have a batch of images that need a transparent background. I am able to create a black/white mask of the lighter and darker regions and want to use this mask to keep the pixels, which are white in the mask unchanged and set all pixel to transparent, which are black. The best outcome so far I got with

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

But the last command just "ghosts" the whole image. How can I "cut out" the black pixels and keep the white pixels unchanged?

This is what I get so far.

Origin image Ghost result


Solution

  • You simply need to remove the "-mask" from your command line leaving your mask image (and add -alpha off). So the following works fine for me in ImageMagick 6.

    Input:

    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
    

    Mask:

    enter image description here

    Result:

    enter image description here

    Download the result to see that the background is fully transparent.

    If using Imagemagick 7, then change convert to magick

    ADDITION

    Here is one way to do that with MPR. Note the +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
    

    You can also do it with a clone and parentheses.

    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
    

    I get the same result as above.