Search code examples
imagemagickimagemagick-convert

Average image color excluding transparency with Imagemagick


Using IM's CLI, I'm trying to get the average image color for an image, excluding any transparent pixels. The normally used -resize 1x1 info:- is not useful in this case, as obviously transparent pixels will affect the result (and you end up with a totally transparent pixel in some cases)

My fallback right now is extracting them using -define histogram:unique-colors=true -format %c histogram:info:- and manually excluding the transparent ones, but this feels complex for something IM might already provide.


Solution

  • In ImageMagick you can get the average (mean) color excluding transparency by

    convert image -scale 1x1! -alpha off -format "%[pixel:u.p]" info:
    

    Example:

    convert logo: -transparent white -scale 1x1! -alpha off -format "%[pixel:u.p]\n" info:
    
    srgb(100,81,99)
    


    If using ImageMagick 7, then replace convert with magick.

    ADDITION: Here is the long way. Compute the mean of each channel of the image. Compute the mean of the alpha channel. Then divide.

    convert logo: -transparent white logot.png
    convert logot.png -alpha extract mask.png
    
    declare `convert logot.png -alpha remove -format "IR=%[fx:mean.r]\nIG=%[fx:mean.g]\nIB=%[fx:mean.b]\n" info:`
    echo "IR=$IR; IG=$IG; IB=$IB"
    IR=0.0651798; IG=0.0529989; IB=0.0641607
    
    MM=`convert mask.png -format "%[fx:mean]\n" info:`
    echo "MM=$MM"
    MM=0.165872
    
    convert xc: -format "srgb(%[fx:round(255*$IR/$MM)],%[fx:round(255*$IG/$MM)],%[fx:round(255*$IB/$MM)])\n" info:
    srgb(100,81,99)