Page 1 of 1

Detecting "nearly" grayscale

Posted: 2018-05-22T14:28:56-07:00
by Devpool
I noticed that "convert" will automatically change the colorspace from RGB (or sRGB) to Gray with some images. AFAICT, it does this when all of the channels are identical.

However, I often come across RGB images that are essentially grayscale, but the channel statistics are not *quite* identical (differing by a decimal place or so.) I'd like to identify these images and force them to grayscale, but I'm not sure (a) which channel statistic(s) would be best to compare (e.g., standard deviation?) or (b) how to extract individual statistic values.

I'm using
ImageMagick 7.0.7-34 Q16 x86_64 2018-05-21
on macOS High Sierra 10.13

Re: Detecting "nearly" grayscale

Posted: 2018-05-22T14:48:08-07:00
by snibgo
The S channel of HLS (or C channel of HCL) gives the saturation (or chroma), on a scale of 0.0 to 1.0. If the mean of this is low, the image is close to gray.

However, an image that is totally gray except for a few high-saturation pixels will be, on average, nearly gray, so you might prefer to find the maximum saturation instead.

Code: Select all

f:\web\im>%IMG7%magick toes.png -colorspace HCL -format %[fx:mean.g] info:
0.114103

f:\web\im>%IMG7%magick toes.png -colorspace HCL -format %[fx:maxima.g] info:
0.380179

Re: Detecting "nearly" grayscale

Posted: 2018-05-22T15:37:50-07:00
by fmw42
Doing what you want could cause problems if a just one or a few intended pixels were colored and you needed those to be colored as indicators of something at those locations. So do that with caution knowing what your image content is.

Re: Detecting "nearly" grayscale

Posted: 2018-05-23T09:38:56-07:00
by Devpool
snibgo wrote: 2018-05-22T14:48:08-07:00 The S channel of HLS (or C channel of HCL) gives the saturation (or chroma), on a scale of 0.0 to 1.0. If the mean of this is low, the image is close to gray.

However, an image that is totally gray except for a few high-saturation pixels will be, on average, nearly gray, so you might prefer to find the maximum saturation instead.

Code: Select all

f:\web\im>%IMG7%magick toes.png -colorspace HCL -format %[fx:mean.g] info:
0.114103

f:\web\im>%IMG7%magick toes.png -colorspace HCL -format %[fx:maxima.g] info:
0.380179
Thanks, that's exactly what I was looking for. I think I'm going to use both, with the maxima setting a flag for manual checking if it otherwise appears grayscale.