0
votes

ImageMagick command identify prints to screen the min, max and mean values of all the pixels in an image - e.g. for an RGB TIF image we can see the mean thus:

identify -verbose -quiet image.tif | grep mean

which lists (for Red Green Blue and Gray):

mean: 122.974 (0.48225)
mean: 107.722 (0.422438)
mean: 84.1278 (0.329913)
mean: 104.941 (0.411534)

Q: if my image has a boolean alpha channel can I use it to limit the calculations to include only those pixels where alpha was set to 1?

I tried using the clip-mask option with either leading - or + but the means didn't change as would be expected.

1
I'm not at a computer, but you know how to count the on and off alpha pixels, yes? And if you multiply the RGB channels by the alpha channel all transparent pixels will go to black so you can find the max. And if you multiply by (255-alpha) you can find the min.Mark Setchell
Good idea, Mark!fmw42
thanks also to Mark!GavinBrelstaff

1 Answers

2
votes

In ImageMagick, the -scale 1x1! function can be used to compute the mean without including alpha so that you get the mean of only opaque values. So you could do the following:

Create test transparent image:

convert logo: -transparent white logot.png


Compute mean values:

convert logot.png -scale 1x1! -alpha off -format "%[fx:255*u.r], %[fx:255*u.g], %[fx:255*u.b]" info:

100.202, 81.4747, 98.6342


Alternately, you can use the alpha channel as a mask to get the means. You compute the mean of each channel without the alpha channel and the background under the alpha set to black. Then compute the mean of the alpha channel. Then divide each channel mean by the mean of the alpha channel.

convert logo: -transparent white logot.png
convert logot.png -alpha extract alpha.png

means_rgb=$(convert logot.png -background black -alpha background -alpha off -format "%[fx:mean.r],%[fx:mean.g],%[fx:mean.b]" info:)
mean_r=$(echo $means_rgb | cut -d, -f1)
mean_g=$(echo $means_rgb | cut -d, -f2)
mean_b=$(echo $means_rgb | cut -d, -f3)

mean_alpha=$(convert alpha.png -format "%[fx:mean]" info:)

mean_r=$(convert xc: -format "%[fx:255*$mean_r/$mean_alpha]" info:)
mean_g=$(convert xc: -format "%[fx:255*$mean_g/$mean_alpha]" info:)
mean_b=$(convert xc: -format "%[fx:255*$mean_b/$mean_alpha]" info:)

echo "$mean_r, $mean_g, $mean_b"

100.203, 81.4768, 98.6362


To get the min and max, taking the cue from Mark Setchell's idea:

convert logot.png -background black -alpha background -alpha off -format "%[fx:255*maxima.r], %[fx:255*maxima.g], %[fx:255*maxima.b]\n" info:

255, 250, 244


convert logot.png -background white -alpha background -alpha off -format "%[fx:255*minima.r], %[fx:255*minima.g], %[fx:255*minima.b]\n" info:

4, 0, 0