Opencv – Getting dominance color opencv


I have a image which is multi colored.

enter image description here

I want to calculate the dominant color of the image. the dominant color is red, i want to filter the red out. i am doing the following code in opencv but its not performing.

inRange(input_image, Scalar(0, 0, 0), Scalar(0, 0, 255), output);

How can i get the dominant color otherwise? My final project should determine the maximum color of the object on its own. What is the best method for this?

Best Solution

You should quantize (reduce number of colors) your image before searching the for the most frequent color.

Why? Imagine image that has 100 pixels of (0,0,255) (blue color int RGB), 100 pixels of (0,0,254) (almost blue - you even won't find the difference) and 150 pixels of (0,255,0) (green). What is the most frequent color here? Obviously, it's green. But after quantization you will got 200 pixels of blue and 150 pixels of green.

Read this discussion: How to reduce the number of colors in an image with OpenCV?. Here's simple example:

int coef = 200;
Mat quantized = img/coef;
quantized = quantized*coef;

And this is what I've got after applying it:

enter image description here

Also you can use k-means or mean-shift to do that (this is much efficient way).