Search code examples
imageimagemagickimagemagick-convert

Cutting out a mask from a image with ImageMagick


I'm trying to cut out a shape from an image based on a mask I have. I tried a number of ways but I'm really struggling to get the result I need. I'm using ImageMagick 7.1.0-51 Q16-HDRI on Windows.

The "base" image:

https://i.sstatic.net/06t9S.jpg

The mask i'm using:

https://i.sstatic.net/vXRco.jpg

Expected result(photoshoped):

https://i.sstatic.net/Ij1eR.jpg

Edit: Reuploaded direct on imgur to maintain transparent background


Solution

  • In Imagemagick, you want to invert (negate) the polarity of black and white, then do a -compose difference -composite, then invert again.

    Hair:

    enter image description here

    Face:

    enter image description here

    magick hair.png face.png -alpha off -colorspace gray -negate -compose difference -composite -negate result.png
    

    Result:

    enter image description here

    If you want pure white in the face area, threshold the two images after the conversion to grayscale

    magick hair.png face.png -alpha off -colorspace gray -auto-threshold otsu -negate -compose difference -composite -negate result2.png

    Result 2:

    enter image description here

    ADDITION

    If your input images have transparent backgrounds, then you have to extract the alpha channels, combine them to do the difference and then put that alpha channel back on the input.

    Unix Syntax:

    magick hair.webp \
    \( +clone face_mask.webp -alpha extract -compose difference -composite \) \
    -alpha off -compose copy_opacity -composite result.png
    

    enter image description here

    For Windows,remove the \ in front of the parentheses and change the end of line \ to ^.