image-processingimagemagickimagemagick-convert

Combining two ImageMagick commands for dynamic masking


I want to combine these two ImageMagick commands, the first one creates a greyscale mask by drawing and combining two gradients, then, combines the merged gradients with the extracted alpha channel from the original image. The second command applies the grayscale image mask produced by the first command, as an alpha channel into the original file:

# Generate right and bottom masks, then combine them with the object mask
magick \
  -size 3202x2724 xc:white \
  \( -size 3202x512 gradient:white-black \) -geometry +0+2212 -compose Bumpmap -composite \
  \( -size 512x2724 -define gradient:direction=East gradient:white-black \) -geometry +2690+0 -compose Bumpmap -composite \
  \( "object.tif" -alpha extract \) -compose Bumpmap -composite \
  "combinedmasks.tif"

# Apply mask to object
magick "object.tif" "combinedmasks.tif" -alpha off -compose copy_opacity -composite "object_masked.tif"

I tried with the following command but the applied alpha isn't right at all:

# Combined commands
magick "object.tif" \
\( -size 3202x2724 xc:white \
   \( -size 3202x512 gradient:white-black \) -geometry +0+2212 -compose Bumpmap -composite \
   \( -size 512x2724 -define gradient:direction=East gradient:white-black \) -geometry +2690+0 -compose Bumpmap -composite \
   \( "object.tif" -alpha extract \) -compose Bumpmap -composite \
\) \
-alpha off -compose copy_opacity -composite "failmerge.tif"

I attached a resized version of the results.

The mask:
Result of the first command

Image with the mask applied successfully:
Result of the second command

Result of combining the two commands:
Result of the third command


Solution

  • Here you go:

    magick "object.tif" -write MPR:orig -alpha extract \
      \( -size 3202x512 gradient:white-black -geometry +0+2212 \) -compose multiply -composite \
      \( -size 512x2724 -define gradient:direction=East gradient:white-black -geometry +2690+0 \) -compose multiply -composite \
      MPR:orig +swap -compose copyopacity -composite "object_masked.tif"
    

    Based on this answer: https://stackoverflow.com/a/40383400/4199855