Average image color excluding transparency with Imagemagick

荒凉一梦 提交于 2019-12-11 15:37:42

问题


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.


回答1:


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)




来源:https://stackoverflow.com/questions/53642910/average-image-color-excluding-transparency-with-imagemagick

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!