imagemagickoverlaycontour

How to overlay transparent shape with contour?


I have these 2 input images shown below. img1.png has a car in black and the rest transparent.

img1.png

img1.png

background.png

background.png

I and like to fill img1.png with the background.png image to get this output, with a white contour around the car (it could be different shapes) and the rest transparent, to get something like this:

Note: I'm showing the car with red contour just for example purposes to see better.

Desired output

enter image description here

Currently I'm doing this:

  1. Invert the alpha channel to make the car to transparent.

    convert img1.png -channel a -negate +channel -fill black -colorize 100% temp.png

  2. Overlay the car over the background.

    convert -composite -gravity center background.png temp.png temp1.png

  3. Convert black to transparent

    convert temp1.png -transparent black img1_out.png

The issue is if the background image has some part of black, then inside the car the black part would be transparent too.

I think that maybe adding a white contour to the car shape previous to step 2 would help in some way to isolate the black part that I want to convert to transparent but I don't know how to add that contour after invert the alpha channel and how to convert to transparent only the black part outside the car shape. I'm using IM 7 under Cygwin for Windows.

This is my current output img1_out.png

enter image description here

How can I do this? Thanks


Solution

  • Using IMv7 on Windows11, and using your example images, this command creates the output below...

    magick background.png img1.png ^
        -compose copyopacity -composite -compose over ^
        ( +clone -fill red -colorize 100 -morphology edgein disk:8x8 ) ^
        -composite result.png
    

    enter image description here

    You say you have IMv7 but you're using the "convert" command. For v7 you should be using the command "magick".

    To modify the syntax for Cygwin, almost certainly the continued-line carets "^" will need to be replaced with backslashes "\" and the parentheses will need to be escaped with backslashes "\(\)".