You can scan all colors and use a hash table to track how many pixels of each color are.
Take these numbers and, remembering what colors they correspond to, sort them in descending order.
Look at the sorted list of numbers and find the difference between each consecutive pair of numbers. Keep track of the indices in the list of two numbers that led to each difference. Sort this list of differences.
Look at the maximum number in the difference list. You now have the biggest decline between two sets of pixels. Find how big it was. Everything with this number of pixels and above is the dominant color. All below is the sub-dominant color. Now you know how many dominant colors you have and what they are.
It should be pretty easy from there to do what you want to do.
The only time this did not work is if some noise was the same color as the strip, so much so that it distorted your data.
In this case, you would use a different approach, which you can also use in the first case - looking at the runs. Go through the pixels, and each time you find a new color, see how many of the following pixels are the same color.
Use the method described earlier to group colors into dominant and non-dominant for the same result.
In both cases, if you know that the image has vertical stripes, you can limit the number of horizontal color lines that you are looking at to speed things up.
source share