Click here to Skip to main content
11,433,901 members (65,314 online)
Click here to Skip to main content

Tagged as

Count Number of Unique Colors in an Image

, 19 Feb 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
Determine the number of unique colors in an image
Got an image? Want to know how many unique colors are contained in it?

//-------------------------------------------------------------------------
public static int CountImageColors(string fileName)
{
    int count = 0;
    HashSet<Color> colors = new HashSet<Color>();
    Bitmap bmp = null;
 
    if (File.Exists(fileName))
    {
        try
        {
            bmp = new Bitmap(fileName);
            if (bmp != null)
            {
                for (int y = 0; y < bmp.Size.Height; y++)
                {
                    for (int x = 0; x < bmp.Size.Width; x++)
                    {
                        colors.Add(bmp.GetPixel(x, y));
                    }
                }
                count = colors.Count;
            }
        }
        catch 
        {
            throw;
        }
        finally
        {
            colors.Clear();
            bmp.Dispose();
        }
    }
    return count;
}

Since a HashSet doesn't allow duplicate keys, we use the color as the key, and any duplicates will not be added. This will result in a collection of unique colors, and we use the Count property to get that value.

Keep in mind the example provided above is merely illustrating the technique of using a HashSet to keep track of unique colors, and is not necessarily a reasonable implementation of the method itself in your case.

It may not be the fastest way to do it, but it works great, and the general technique illustrated above can be used in pretty much any language that supports a HashSet-style collection.

License

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

Share

About the Author

John Simmons / outlaw programmer
Software Developer (Senior)
United States United States
I've been paid as a programmer since 1982 with experience in Pascal, and C++ (both self-taught), and began writing Windows programs in 1991 using Visual C++ and MFC. In the 2nd half of 2007, I started writing C# Windows Forms and ASP.Net applications, and have since done WPF, Silverlight, WCF, web services, and Windows services.

My weakest point is that my moments of clarity are too brief to hold a meaningful conversation that requires more than 30 seconds to complete. Thankfully, grunts of agreement are all that is required to conduct most discussions without committing to any particular belief system.

Comments and Discussions

 
QuestionI need to find the total no of dot images in the image file of the same color.How it can be possible..?? Pin
Member 1055062226-Jan-14 22:46
memberMember 1055062226-Jan-14 22:46 
AnswerRe: I need to find the total no of dot images in the image file of the same color.How it can be possible..?? Pin
John Simmons / outlaw programmer21-Jul-14 5:36
memberJohn Simmons / outlaw programmer21-Jul-14 5:36 
QuestionColor Counting - GetPixel is slow, so... Pin
jma24007-Mar-13 21:00
memberjma24007-Mar-13 21:00 
unsafe
public static int ColorCount(System.Drawing.Bitmap bmp)
{
if (bmp != null)
{
HashSet hs = new HashSet();

System.Drawing.Imaging. BitmapData bmpData = null;
uint* bmpStart = null;
bmpData = bmp.LockBits(new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging. ImageLockMode.ReadOnly, System.Drawing.Imaging. PixelFormat.Format32bppRgb);
bmpStart = (uint*)bmpData.Scan0;
uint currcol;
for (int x = 0; x < bmp.Width; x++)
{
for (int y = 0; y < bmp.Height; y++)
{
currcol = *(bmpStart + ((bmp.Width * y) + x));
hs.Add(currcol);
}
}
bmp.UnlockBits(bmpData);
return hs.Count;
}

return 0;
}
AnswerRe: Color Counting - GetPixel is slow, so... Pin
John Simmons / outlaw programmer8-Mar-13 0:34
memberJohn Simmons / outlaw programmer8-Mar-13 0:34 
GeneralRe: My mistake then - I didn't dive into the docs for HashSet de... Pin
Chris Maunder21-Feb-11 16:11
adminChris Maunder21-Feb-11 16:11 
GeneralReason for my vote of 5 I like this concept and solution, th... Pin
DrABELL22-Feb-11 17:49
memberDrABELL22-Feb-11 17:49 
GeneralReason for my vote of 5 I like it Pin
RaviRanjankr19-Feb-11 9:28
mvpRaviRanjankr19-Feb-11 9:28 
GeneralMost images are going to have many, many repeated colours so... Pin
Chris Maunder18-Feb-11 18:49
adminChris Maunder18-Feb-11 18:49 
GeneralRe: I don't understand your question. The try/catch was for the ... Pin
John Simmons / outlaw programmer19-Feb-11 1:56
mvpJohn Simmons / outlaw programmer19-Feb-11 1:56 
GeneralReason for my vote of 5 Thanks for Sharing. Pin
linuxjr18-Feb-11 10:46
memberlinuxjr18-Feb-11 10:46 
GeneralReason for my vote of 5 Sweet. Pin
Hans Dietrich18-Feb-11 7:51
mentorHans Dietrich18-Feb-11 7:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150428.2 | Last Updated 19 Feb 2011
Article Copyright 2011 by John Simmons / outlaw programmer
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid