First time here? Check out the FAQ!

Ask Your Question
0

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

asked Dec 13 '18

raisa_ gravatar image

updated Dec 13 '18

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 ?

Preview: (hide)

Comments

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 ?

berak gravatar imageberak (Dec 13 '18)edit
1

| can you explain some more about it ?

exactly count how many colors.

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

raisa_ gravatar imageraisa_ (Dec 13 '18)edit

1 answer

Sort by » oldest newest most voted
1

answered Dec 13 '18

berak gravatar image

updated Dec 13 '18

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[0] << 16) | (p[1] << 8) | (p[2]);
    unique.insert(n);
}

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

Question Tools

1 follower

Stats

Asked: Dec 13 '18

Seen: 955 times

Last updated: Dec 13 '18