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)
13 namedWindow("input image", CV_WINDOW_AUTOSIZE);
14 imshow("input image", src);
15
16 Scalar colorTab[] = ;
23
24 int width = srcols;//图像的列
25 int height = src.rows;//图像的行
26 int dims = srchannels();//图像的通道数
27
28 // 初始化定义
29 int sampleCount = width*height;//获取图像的像素点数
30 int clusterCount = 4;//要分类块数
31 Mat points(sampleCount, dims, CV_32F, Scalar(10));//定义样本数据
32 Mat labels;
33 Mat centers(clusterCount, 1, points.type());//定义中心点(浮点数)
34
35 // RGB 数据转换到样本数据
36 int index = 0;
37 for (int row = 0; row < height; row++)
45 }
46
47 // 运行KMeans
48 TermCriteria criteria = TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 10, 0.1);
49 kmeans(points, clusterCount, labels, criteria, 3, KMEANS_PP_CENTERS, centers);//尝试3次
50
51 // 显示图像分割结果
52 Mat result = Mat::zeros(src.size(), src.type());
53 for (int row = 0; row < height; row++)
61 }
62
for (int i = 0; i < centers.rows; i++)
68
69 imshow("KMeans Image Segmentation Demo", result);
70 waitKey(0);
71 return 0;
72 }
注:中心点是相对于图像RGB像素值而求定的位置。
上一篇:ITK 实例2 连接门限对脑部MHA文件进行三维分割下一篇:ITK 实例11 边缘保留平滑滤波对脑部MHA文件进行三维滤波
OpenCV