Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a majority color in an image?

Tags:

.net

windows

wpf

I want to retrieve the majority color in a background image in .NET. Is it possible?

like image 524
John Avatar asked Mar 30 '10 14:03

John


People also ask

How do you make a color dominant?

Contrast. Combining colors with a lot of contrast – blue on a white background, for example – will make one color dominate.


1 Answers

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.

like image 134
CeejeeB Avatar answered Oct 17 '22 08:10

CeejeeB