GavinBrelstaff
GavinBrelstaff

Reputation: 3069

ImageMagick using alpha channel to control calculating min, max and mean image values

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.

Upvotes: 0

Views: 473

Answers (1)

fmw42
fmw42

Reputation: 53081

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


Upvotes: 2

Related Questions