Home > Back-end >  Cutting out a mask from a image with ImageMagick
Cutting out a mask from a image with ImageMagick

Time:11-02

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:

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 ^.

  • Related