# Count color using calcHist, how exactly to read the histogram ?

Hi, I want to count colors in an image. I read many suggestion to use Histogram, so I followed instruction from OpenCV docs Histogram Calculation. But how exactly to read this histogram to get information about how many color is in there ?

edit retag close merge delete

I want to count colors in an image.

can you explain some more about it ?

But how exactly to read this histogram to get information about how many color is in there

basically, hstograms count color occurences into bins. (and there are as many colour, as yoou gave it bins.) is that really, what you wanted ?

did you want to find out, how many unique combinations of B,G,R are present in your image ?

1

| can you explain some more about it ?

exactly count how many colors.

(edit) yes, unique colors. is that possible with histogram ?

Sort by » oldest newest most voted

histograms are not really useful for what you wanted. sure, for a single channel you could count the non-zero bins, but if you have 2 channels, your histogram is a 2d matrix, and for 3 channels a 3d cube, that's not practical.

but we can make integer (hex) numbers from our pixels, and collect them in a std::set, which will only keep the unique values:

std::set<int> unique;
// iterate over pixels (assummes: CV_8UC3 !)
for (Vec3b &p : cv::Mat_<Vec3b>(image)) {
// "hash" representation of the pixel
int n = (p << 16) | (p << 8) | (p);
unique.insert(n);
}

cout << "we have " << unique.size() << " unique colors:" << endl;
for (int i: unique)
cout << format("%06x", i) << endl;

more

Official site

GitHub

Wiki

Documentation