image-processingimagemagickimagemagick-convert

ImageMagick - trouble masking an image with '-compose CopyOpacity' and then combining with '-layers flatten' afterwards when nested in parentheses


I have an image that I'm trying to mask using a second image (black and white), which then needs to be combined with other layers using -layers flatten

Here's the command that I'm receiving unexpected output for:

convert -size 1920x1080 xc:transparent \( 1_positioned.png 2_matte.png -compose CopyOpacity -composite \) -background none -layers flatten -colorspace sRGB 3_output.png

This is resulting in the 1_positioned.png content not showing through and being replaced with solid black somehow.

Some observations

If I run only the part in parentheses, it does mask the image correctly as expected:

convert 1_positioned.png 2_matte.png -compose CopyOpacity -composite 3_this_works.png

Also if I remove the -layers flatten so that it outputs the layers as separate images, each individual file looks right.


If I use the 3_this_works.png file from above in place of the part in parentheses like this:

convert -size 1920x1080 xc:transparent 3_this_works.png -background none -layers flatten -colorspace sRGB 3_output.png

...then it works correctly. Not sure why it is behaving differently when using an intermediary file vs. putting it all in 1 command.

I'm planning on adding additional layers to the command to be combined with -layers flatten so that's why it is being combined with a transparent 1920x1080 layer currently instead of only running the part in parentheses by itself.

Images:

1_positioned.png: 1_positioned.png

2_matte.png 2_matte.png

Using ImageMagick v6

Version: ImageMagick 6.9.13-25 Q16 aarch64 18639 https://legacy.imagemagick.org
Copyright: (C) 1999 ImageMagick Studio LLC
License: https://imagemagick.org/script/license.php
Features: Cipher DPC Modules 
Delegates (built-in): bzlib fontconfig freetype jng jp2 jpeg lcms ltdl lzma png tiff webp xml zlib

Solution

  • It seems like the -compose option persists across the command and is not contained only in the part in parentheses. So what was happening was it was using CopyOpacity as the method for merging the layers with -layers flatten instead. This is fixed by setting -compose back to over before running -layers flatten.

    Updated command:

    convert -size 1920x1080 xc:transparent \( 1_positioned.png 2_matte.png -compose CopyOpacity -composite \) -compose over -background none -layers flatten -colorspace sRGB 3_output.png