C++: Counting Labels in K-Means Clustering

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:

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?

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