The code below will convert an image to a bitmap and return the count of pixels that fall within a range of hues. The value of the hues are in degrees and must fall between 0.0 and 360.0. This method supports using a higher minimum value than maximum so you can wrap the range around zero degrees. You must also specify a range of acceptible saturation values between 0 and 1.0.
This allows you to select all pixels in a fuzzy manor instead of just one RGB value.
int GetPixelsForHueRange(Image image, float lowerHue, float upperHue, float minSaturation, float maxSaturation)
{
Bitmap bmp = new Bitmap(image);
if (lowerHue > upperHue)
{
return GetPixelsForHueRange(image, lowerHue, 360.0f, minSaturation, maxSaturation) +
GetPixelsForHueRange(image, 0.0f, upperHue, minSaturation, maxSaturation);
}
int count = 0;
for (int i = 0; i < bmp.Size.Width; i++)
for (int j = 0; j < bmp.Size.Height; j++)
{
System.Drawing.Color c = bmp.GetPixel(i, j);
float hue = c.GetHue();
float sat = c.GetSaturation();
if ((hue >= lowerHue && hue <= upperHue) &&
(sat >=minSaturation && sat <= maxSaturation))
{
count++;
}
}
return count;
}
Usage:
Image img = Image.FromFile(@"C:\Users\me\Pictures\rainbow.jpg");
int pixelCount = GetPixelsForHueRange(img, 350.0f, 10.0f, 0.30f,1.0f);