# C++: Counting Labels in K-Means Clustering

**URL:** <https://forum.opencv.org/t/c-counting-labels-in-k-means-clustering/8336>\
**Category:** C++\
**Tags:** kmeans\
**Created:** [April 9, 2022, 3:43am UTC](https://forum.opencv.org/t/c-counting-labels-in-k-means-clustering/8336 "2022-04-09T03:43:32Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![MaestroFries](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.opencv.org/maestrofries/32/5336_2.png) [@MaestroFries](https://forum.opencv.org/u/MaestroFries)\
**Post date:** [April 9, 2022, 3:43am UTC](https://forum.opencv.org/t/c-counting-labels-in-k-means-clustering/8336/1 "2022-04-09T03:43:32Z")

</div>

I want to create a program which takes an image, analyzes it, and creates a percentage of RGB colours present. I am using K-Means clustering for that:

```auto
double compactness = kmeans(data, k, labels, TermCriteria(TermCriteria::MAX_ITER, 10, 1.0), 3, KMEANS_PP_CENTERS, centers);

```

I understand that I have to count how many times a “0”, “1”, and so forth is found in the variable labels. However, I tried using std::count but it has not worked since labels doesn’t seem to be a real array.

`std::count(labels.at<int>(0, 0), labels.at<int>(data.total(), 0), 0); // NOT WORKING`

How would I be able to count each label?

---

<div class="post-metadata">

**Author:** ![crackwitz](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.opencv.org/crackwitz/32/14_2.png) [@crackwitz](https://forum.opencv.org/u/crackwitz)\
**Post date:** [April 9, 2022, 8:27am UTC](https://forum.opencv.org/t/c-counting-labels-in-k-means-clustering/8336/2 "2022-04-09T08:27:27Z")

</div>

you know k. are the labels 1…k, and 0 is background? then you could, for i = 0 to k, calculate `cv::countNonZero(labels == i)`

there’s also `calcHist`, and calculating a histogram is generally what you want to do here, but I hate OpenCV’s function because it’s so awkward to call.

or use `std::count` and give it the flat data from the Mat. you can use `ptr()` to get the data: [OpenCV: cv::Mat Class Reference](https://docs.opencv.org/3.4/d3/d63/classcv_1_1Mat.html#a5a9ffc908ac90604f36a8b6a1038747d)
