Search code examples
pythonopencvimage-processingimagemagickpython-imaging-library

Apply linear transparent gradient to a portion of image with transparent background in python


I need to apply linear transparent gradient to only bottom 5% of the image. I have some idea that first I need to create mask on alpha channel. But I'm not sure how I can do that which affects only bottom 5% of the image. I've tried different methods bud no luck so far. The gradient should start at 5% height of the image at 100% alpha and 0% alpha at the end. Also, the images can be non-rectangular PNG with transparent background. I would really appreciate any help. Thank you. Here is an example of what I need. But it can be either a rectangular or non-rectangular image.


Solution

  • Here is how to do that in ImageMagick 7 if you have an existing alpha channel in the input or not. It is slightly different. You basically extract the alpha channel from the input and multiply it with the one containing the gradient. Then put that new one into the original image replacing the existing alpha channel.

    Input:

    enter image description here

    magick lena_circle.png \
    -alpha set \
    -set option:wd "%w" \
    -set option:ht "%h" \
    -set option:ht2 "%[fx:round(0.25*ht)]" \
    -set option:ht3 "%[fx:ht-ht2]" \
    \( -size "%[wd]x%[ht3]" xc:white \) \
    \( -size "%[wd]x%[ht2]" gradient:white-black \) \
    \( -clone 1,2 -append \) \
    -delete 1,2 \
    \( -clone 0 -alpha extract \) \
    \( -clone 1,2 -compose multiply -composite \) \
    -delete 1,2 \
    -alpha off -compose copy_opacity -composite \
    lena_circle_fade3.png
    

    Resulting Image:

    enter image description here