Click here to Skip to main content
15,892,059 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need to find the majority color of an image using C#. Please anybody help me. Thank you...
Posted
Comments
BillWoodruff 2-Nov-13 6:14am    
Please explain exactly what you mean by "majority:" that could mean the "average" color, the "mean" color, the "modal" color, or, it could mean the most occurrences of a specific color among all specific colors used in whatever is the source of your picture data.
NISHAN SANDEEPA 2-Nov-13 6:24am    
Thanks for comment.Consider there is an image in a picturebox.Every pixel has an RGB value. Some RGB values are equal in that image. I need to find most used color in that image.
BillWoodruff 2-Nov-13 9:46am    
Okay, that's really a different goal than producing a histogram. I'll respond soon.

Are there any assumptions we can make about the format of the bitmaps you want to analyze: number of bits ? number of colors ?

If you have an eight bits-per-pixel RGB source, that's 16,777,216 potential colors.

Of course, it's doubtful that any image is likely to contain all of the possible colors (and our eyes can only see about 10 million colors) ! Still, if there's any way to "narrow the search space," that's a good thing.

Are you willing to use un-managed (unsafe) code in C# to speed-up the analysis ?
NISHAN SANDEEPA 2-Nov-13 13:28pm    
Thanks for reply.Images are selected by the user.So I think we cant define the format of the picture.Actually I havent an idea about that.Simply user select any image then I need to find the majority color of that image.If you can give me some advices to do this with examples that will be perfect.
BillWoodruff 3-Nov-13 1:32am    
I've posted some sample code for analyzing 24 bit-per-pixel images; you'll have to develop your own methods of analyzing the image the user has selected, determining their pixel depth, and accessing/analyzing the color values.

There's some good stuff on images and GDI+, from many years ago, by Bob Powell, that may be useful to you:

http://bobpowell.net/faqmain.aspx
http://bobpowell.net/creating_images.aspx
http://bobpowell.net/lockingbits.aspx

I am sure there's also a wealth of information and code here on CodeProject related to image analysis: just search.

For 24-bit-per-pixel images you can try the code below, which will make available the most frequently used color, how many times it is used, and also make available a list of the top ten most frequently used colors, and how many times they are used.

Disclaimer: this code is presented for educational purposes only; I developed it quickly (in a few hours), and it is not fully tested for accuracy. You use this code at your own risk.

To use this code you need to have a file-path to a 24 bit-per-pixel image:
private string filep = @"C:\Users\You\Desktop/SomeFileName.jpg";
And then turn the file reference into a Bitmap object and call the main method of the Class like this:
Bitmap bMap = Bitmap.FromFile(filep) as Bitmap;

if (bMap == null) throw new FileNotFoundException("Cannot open picture file for analysis");

YourNameSpace.PictureAnalysis.GetMostUsedColor(bMap);
Set a breakpoint after the call to 'GetMostUsedColor, and examine the results in the four public variables the Class exposes: MostUsedColor, MostUsedColorIncidence, TenMostUsedColors, TenMostUsedColors, TenMostUsedColorIncidences.
C#
using System.Collections.Generic;
using System.Linq;
using System.Drawing;

namespace YourNameSpace
{
    public static class PictureAnalysis
    {
        public static List<Color> TenMostUsedColors {get; private set;}
        public static List<int> TenMostUsedColorIncidences {get; private set;}

        public static Color MostUsedColor {get; private set;}
        public static int MostUsedColorIncidence {get; private set;}

        private static int pixelColor;

        private static Dictionary<int, int> dctColorIncidence;

        public static void GetMostUsedColor(Bitmap theBitMap)
        {
            TenMostUsedColors = new List<Color>();
            TenMostUsedColorIncidences = new List<int>();

            MostUsedColor = Color.Empty;
            MostUsedColorIncidence = 0;

            // does using Dictionary<int,int> here
            // really pay-off compared to using
            // Dictionary<Color, int> ?

            // would using a SortedDictionary be much slower, or ?

            dctColorIncidence = new Dictionary<int, int>();

            // this is what you want to speed up with unmanaged code
            for (int row = 0; row < theBitMap.Size.Width; row++)
            {
                for (int col = 0; col < theBitMap.Size.Height; col++)
                {
                    pixelColor = theBitMap.GetPixel(row, col).ToArgb();

                    if (dctColorIncidence.Keys.Contains(pixelColor))
                    {
                        dctColorIncidence[pixelColor]++;
                    }
                    else
                    {
                        dctColorIncidence.Add(pixelColor, 1);
                    }
                }
            }

            // note that there are those who argue that a
            // .NET Generic Dictionary is never guaranteed
            // to be sorted by methods like this
            var dctSortedByValueHighToLow = dctColorIncidence.OrderByDescending(x => x.Value).ToDictionary(x => x.Key, x => x.Value);

            // this should be replaced with some elegant Linq ?
            foreach (KeyValuePair<int, int> kvp in dctSortedByValueHighToLow.Take(10))
            {
                TenMostUsedColors.Add(Color.FromArgb(kvp.Key));
                TenMostUsedColorIncidences.Add(kvp.Value);
            }

            MostUsedColor = Color.FromArgb(dctSortedByValueHighToLow.First().Key);
            MostUsedColorIncidence = dctSortedByValueHighToLow.First().Value;
        }

    }
}
Note: For possible issues with ordering a Generic Dictionary see discussion here: [^].
 
Share this answer
 
v2
Comments
NISHAN SANDEEPA 3-Nov-13 1:58am    
Thank you so much BillWoodruff
Bala Ji Vadivel 18-May-15 2:29am    
I just want to know how to do this.. can u pls help me to get over from this?
Member 11465518 11-Oct-15 23:31pm    
This is how I implemented BillWoodruff's code:

using System.Collections.Generic;
using System.Linq;
using System.Drawing;

namespace YourNameSpace
{
public class PictureAnalysis
{
public List<color> MostUsedColors {get; private set;}
public List<int> MostUsedColorIncidences {get; private set;}

public Color MostUsedColor {get; private set;}
public int MostUsedColorIncidence {get; private set;}

private int pixelColor;

private class Colors : List<colorincidence>
{

public override bool Contains (int Key)
{
foreach(ColorIncidence ind in this)
if (ind.Color == Key)
return true;
return false;
}

public override ColorIncidence this[int Key]
{
get
{
foreach (ColorIncidence ind in this)
if (ind.Color == Key)
return ind;
return null;
}
}

public Colors OrderedDesc
{
get
{
this.Sort((x, y) => y.Incidence.CompareTo(x.Incidence));
return this;
}
}
}

private class ColorIncidence
{
public int Color;

public int Incidence;
}

private Dictionary<int, int=""> dctColorIncidence;

public ImageProcess ProcessImage(Bitmap theBitMap, int ColorsToGet = 3)
{
MostUsedColors = new List<color>();
MostUsedColorIncidences = new List<int>();

MostUsedColor = Color.Empty;
MostUsedColorIncidence = 0;

Colors dctColorIncidence = new Colors();

// this is what you want to speed up with unmanaged code
for (int row = 0; row < theBitMap.Size.Width; row++)
{
for (int col = 0; col < theBitMap.Size.Height; col++)
{
pixelColor = theBitMap.GetPixel(row, col).ToArgb();

if (dctColorIncidence.Contains(pixelColor)) dctColorIncidence[pixelColor].Incidence++;
else dctColorIncidence.Add(new ColorIncidence(){ Color = pixelColor, Incidence = 1 });
}
}

foreach (ColorIncidence kvp in dctColorIncidence.OrderedDesc.Take(ColorsToGet))
{
MostUsedColors.Add(Color.FromArgb(kvp.Color));
MostUsedColorIncidences.Add(kvp.Incidence);
}

return this;
}

}

}
 
Share this answer
 
Check out this page, it fits to your question
http://www.vcskicks.com/dominant-color.php
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900