Error

# HOWTO: Determine if an Image with a Color Byte Order is Greyscale

#1 Posted : Friday, June 2, 2017 4:13:35 PM(UTC)

Posts: 163

Was thanked: 9 time(s) in 9 post(s)

Typically, the RasterByteOrder of an image can be checked to determine the color range in an image. However, sometimes a color image may only contain greyscale information: that is, the intensity value for each pixel has the same values for Red, Green, and Blue.

The quickest way to determine this is to examine the histogram of the image. If any of the intensity values differ, the image is not greyscale.

Code:
``````
public static bool IsFastGray(string input)
{
using (RasterCodecs codecs = new RasterCodecs())
{

HistogramCommand hc = new HistogramCommand();
hc.Channel = HistogramCommandFlags.Red;
hc.Run(image);
long[] h_red = hc.Histogram;

hc.Channel = HistogramCommandFlags.Green;
hc.Run(image);
long[] h_green = hc.Histogram;

hc.Channel = HistogramCommandFlags.Blue;
hc.Run(image);
long[] h_blue = hc.Histogram;

for (int i = 0; i < h_red.Length; i++)
{
long red = h_red[i];
long green = h_green[i];
long blue = h_blue[i];

if (red != green || red != blue || green != blue)
{
return false;
}
}
}

return true;
}
``````

Note this method, while quick, is not necessarily foolproof. There is an edge case that can occur such that if a color image has an equal distribution of all red, yellow, and blue pixels. While such images typically only exist in contrived situations, these can still be accommodated by examining the individual pixels and comparing their color values. In this case, a single pixel having a color intensity value in one channel differing from the others is sufficient to determine the image is actually "color".

Code:
``````
input)
{
using (RasterCodecs codecs = new RasterCodecs())
{

for (int i = 0; i < image.Width; i++)
{
for (int j = 0; j < image.Height; j++)
{
RasterColor cl = image.GetPixelColor(i, j);

if (cl.R != cl.G || cl.R != cl.B || cl.G != cl.B)
{
return false;
}
}
}
}

return true;
}
``````

Note examining each pixel in the image will be considerably slower than the histogram, but will produce a more accurate response to accommodate edge cases.

Edited by moderator Monday, June 5, 2017 8:51:03 AM(UTC)  | Reason: Not specified

Nick Crook
Developer Support Engineer