#include opencv2/opencv.hpp>
#include vector>
using namespace std;
using namespace cv;
int main()
{
Mat3b img = imread("test.jpg");
imshow("Original", img);
// Cluster
int K = 8;
int n = img.rows * img.cols;
Mat data = img.reshape(1, n);
data.convertTo(data, CV_32F);
Mat labels;
Mat1f colors;
kmeans(data, K, labels, cv::TermCriteria(), 1, cv::KMEANS_PP_CENTERS, colors);
for (int i = 0; i < n; ++i)
{
data.at<float>(i, 0) = colors(labels.at<int>(i), 0);
data.at<float>(i, 1) = colors(labels.at<int>(i), 1);
data.at<float>(i, 2) = colors(labels.at<int>(i), 2);
}
Mat reduced = data.reshape(3, img.rows);
reduced.convertTo(reduced, CV_8U);
imshow("Reduced", reduced);
waitKey(0);
return 0;
}