Arnold Roa
Arnold Roa

Reputation: 7738

obtain the most used color in PNG

I need to obtain the most common color in a png image file using c#. This is so I can draw some text with similar colors contained within the image.

Upvotes: 4

Views: 1876

Answers (4)

Mark Ransom
Mark Ransom

Reputation: 308432

Counting each color can be done with a histogram algorithm, but that's probably not what you're looking for. Colors that are extremely similar should be counted together.

I would suggest using an Octree Color Quantization, which will automatically reduce the number of colors as it counts thereby grouping similar colors into a single bucket. One description of the algorithm: http://www.cubic.org/docs/octree.htm

Forgot to mention: this advice is only for 24-bit PNG. For 8-bit PNG, you already have a palette that does the color grouping. It's only necessary to build a 256 value table and keep a count of each palette index as you encounter it.

Upvotes: 0

Charlie Salts
Charlie Salts

Reputation: 13498

If you're looking at the actual pixel values, I'd use a sorted dictionary:

SortedDictionary<Color,int>

and loop through all the pixels. If you don't know how to loop through the pixels, check out Bitmap.LockBits. For your purposes, GetPixel would be way too slow.

Edit:

I'm not 100% sure about the sorting. I agree with CodeInChaos - a straight dictionary is likely to be faster anyways. You'll have to then do a single loop through the dictionary to get your most common value.

Upvotes: 0

Femaref
Femaref

Reputation: 61477

You can use a colour histogram, sampling the RGB or HSV (depending on your colour space) values into categories. However, if you want the mostly colour identified by actual values, you'll have to count the occurance of each colour seperately.

Upvotes: 4

Sebastiaan van den Broek
Sebastiaan van den Broek

Reputation: 6351

Maybe there are some libraries that will do it for you, but if not, I guess you can just cycle through all pixels, make a map of all colours you find with the number of occurances and in the end get the one that's most used.

Upvotes: 0

Related Questions