I want to retrieve the majority color in a background image in .NET. Is it possible?
Contrast. Combining colors with a lot of contrast – blue on a white background, for example – will make one color dominate.
You can loop through all the pixels in the image and use the getPixel method to determine the RGB value. You can then have a dictionary that store the ARGB value along with a count. You can then see which ARGB value is present most in the image.
var list = new Dictionary<int, int>();
Bitmap myImage = (Bitmap)Bitmap.FromFile("C:/test.jpeg");
for (int x = 0; x < myImage.Width; x++)
{
for (int y = 0; y < myImage.Height; y++)
{
int rgb = myImage.GetPixel(x, y).ToArgb();
if (!list.ContainsKey(rgb))
list.Add(rgb, 1);
else
list[rgb]++;
}
}
As pointed out this has no sympathy for similar colors. If you wanted a more 'general' majority color you could have a threshold on similarity. e.g. rather than:
if (!list.ContainsKey(rgb))
list.Add(rgb, 1);
else
list[rgb]++;
you could do:
var added = false;
for (int i = 0; i < 10; i++)
{
if (list.ContainsKey(rgb+i))
{
list[rgb+i]++;
added = true;
break;
}
if (list.ContainsKey(rgb-i))
{
list[rgb-i]++;
added = true;
break;
}
}
if(!added)
list.Add(rgb, 1);
You could up the threshold of 10 to whatever you needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With