Get the most commonly used color in PNG

I need to get the most common color in a png image file using C #. This means that I can draw text with similar colors contained in the image.

+4
source share
4 answers

You can use the color histogram by sampling RGB or HSV values ​​(depending on your color space) in the category. However, if you want basically the color to be determined by the actual values, you will need to calculate the amount of each color separately.

+4
source

There may be some libraries that will do this for you, but if not, I think you can just iterate over all the pixels, map all the colors that you find with the number of events encountered, and, in the end, get the one that most used.

0
source

If you look at the actual pixel values, I would use a sorted dictionary:

SortedDictionary<Color,int>

and skip all the pixels. If you don’t know how to navigate pixels, check out Bitmap.LockBits . GetPixel will be too slow for your purposes.

Edit:

I am not 100% sure about sorting. I agree with CodeInChaos - a direct dictionary will probably be faster anyway. You will need to do one loop through the dictionary to get the most common meaning.

0
source

Each color can be counted using a histogram algorithm, but this is probably not what you are looking for. Colors that are very similar should be considered together.

I would suggest using Octree color quantization, which will automatically reduce the number of colors as it counts by grouping the same colors into one bucket. One description of the algorithm: http://www.cubic.org/docs/octree.htm

Forgot to mention: this tip is only for 24-bit PNG. For an 8-bit PNG, you already have a palette that groups colors. You only need to build a 256 value table and save the counter of each palette index when you meet it.

0
source

Source: https://habr.com/ru/post/1334267/


All Articles