开发者

obtain the most used color in PNG

开发者 https://www.devze.com 2023-02-03 01:26 出处:网络
I need to obtain the most common color in a png image file using c#. This is so I can draw some text with s开发者_如何学编程imilar colors contained within the image.You can use a colour histogram, sam

I need to obtain the most common color in a png image file using c#. This is so I can draw some text with s开发者_如何学编程imilar colors contained within the image.


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.


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消