Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Count Number of Unique Colors in an Image

0.00/5 (No votes)
19 Feb 2011 1  
Determine the number of unique colors in an image
Got an image? Want to know how many unique colors are contained in it?

C#
//-------------------------------------------------------------------------
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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here