1 #include <opencv2/opencv.hpp>
2 #include <iostream>
3
4 using namespace cv;
5 using namespace std;
6
7 int main(int argc, char** argv) {
8 Mat img(500, 600, CV_8UC3);//定义一张图
9 RNG rng(12345);//定义随机数
10 //不同类定义为不同颜色
11 Scalar colorTab[] = {
12 Scalar(0, 0, 255),
13 Scalar(0, 255, 0),
14 Scalar(255, 0, 0),
15 Scalar(0, 255, 255),
16 Scalar(255, 0, 255)
17 };
18
19 int numCluster = rng.uniform(2, 5);//定义分类种类数量块
20 printf("number of clusters : %d\n", numCluster);
21 //设置从原图像中抽取多少个数据点
22 int sampleCount = rng.uniform(5, 1000);
23 Mat points(sampleCount, 1, CV_32FC2);
24 Mat labels;
25 Mat centers;
26
27 // 生成随机数
28 for (int k = 0; k < numCluster; k++) {
29 Point center;
30 center.x = rng.uniform(0, img.cols);
31 center.y = rng.uniform(0, img.rows);
32 //得到不同小块
33 Mat pointChunk = points.rowRange(k*sampleCount / numCluster,
34 k == numCluster - 1 ? sampleCount : (k + 1)*sampleCount / numCluster);
35 //用随机数对小块点进行填充
36 rng.fill(pointChunk, RNG::NORMAL, Scalar(center.x, center.y), Scalar(img.cols*0.05, img.rows*0.05));
37 }
38 randShuffle(points, 1, &rng);
39
40 // 使用KMeans
41 kmeans(points, numCluster, labels, TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 10, 0.1), 3, KMEANS_PP_CENTERS, centers);
42
43 // 用不同颜色显示分类
44 img = Scalar::all(255);
45 for (int i = 0; i < sampleCount; i++) {
46 int index = labels.at<int>(i);
47 Point p = points.at<Point2f>(i);
48 circle(img, p, 2, colorTab[index], -1, 8);
49 }
50
51 // 每个聚类的中心来绘制圆
52 for (int i = 0; i < centers.rows; i++) {
53 int x = centers.at<float>(i, 0);
54 int y = centers.at<float>(i, 1);
55 printf("c.x= %d, c.y=%d", x, y);
56 circle(img, Point(x, y), 40, colorTab[i], 1, LINE_AA);
57 }
58
59 imshow("KMeans-Data-Demo", img);
60 waitKey(0);
61 return 0;
62 }
可见,随机生成的数据被分成了四块,每块的中心坐标如下: