Search code examples
image-processingimagemagickimagemagick-convert

Compose image with mask image using ImageMagick


Suppose I have some image a.jpg and some other image b.jpg. The desired output out.jpg should be obtained by copying all the pixels from b.jpg that are not black onto a.jpg, all other pixels shall remain untouched.

I tried using composite but had no success whatsoever.


Solution

  • EDITED TO ADD: A solution here can be quite simple and generic, but going forward, please remember to always include your version of ImageMagick and which OS or platform you're working on. There are some syntax differences that can make that important.

    At the very simplest, using ImageMagick v6, you should be able to do something like this...

    convert b.jpg -background none -transparent black a.jpg +swap -composite out.jpg
    

    That reads in the B image, changes all the pure black pixels to transparent, then reads in the A image, swaps the images so they're in the right order, then composites the modified B image over the A image and writes the output.

    You can add a fuzz value like "-fuzz 5%" ahead of the "-transparent" operation to expand the selection to include near-black pixels, also.

    To use with IMv7 change "convert" to "magick".