2017-04-08 09:31:34

Code:

```/*
*作者：att0206
*地点：上海师范大学
*时间：2017/04/06
*功能：实现对K-Means的学习
*/
#include
#include
#include
#include

using namespace::cv;
using namespace::std;

#define WINDOW_NAME1 "rstImage"
#define WINDOW_NAME2 "KMeans"

Mat rstImage;
Mat dstImage;

//声明K-Means
static void K_Means(Mat&,Mat&);
int main(int argc,char* argv[])
{
imshow("rstImage",rstImage);
K_Means(rstImage,dstImage);
//cvtColor(rstImage,rstImage,CV_BGR2GRAY);
//normalize(rstImage,dstImage,0,1,NORM_MINMAX);
imshow("dst",dstImage);
//HoughLines
while((char)(waitKey(1)) != 27) //按下Esc键退出程序
{}
return 0;
}

static void K_Means(Mat& rstImage,Mat& result)  //定义一个K_Means算法  用于计算离中心点的最近的聚为一类
{
int width = rstImage.cols;
int height = rstImage.rows;
int dims = rstImage.channels();
//初始化定义
int sampleCount = width*height;
int clusterCount = 4;
Mat points(sampleCount,dims,CV_32F,Scalar(10));
Mat labels;
Mat centers(clusterCount,1,points.type());

//图像RGB到数据集转换
int index = 0;
for(int row = 0;row(row,col);
points.at(index,0) = static_cast(rgb[0]);
points.at(index,1) = static_cast(rgb[1]);
points.at(index,2) = static_cast(rgb[2]);
}
}
//运行K-Means数据分类
TermCriteria criteria = TermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 10, 1.0);
kmeans(points, clusterCount, labels, criteria, 3, KMEANS_PP_CENTERS, centers);
result = Mat::zeros(rstImage.size(), CV_8UC3);
for(int row = 0; row < height; row++) {
for (int col = 0; col < width; col++) {
index = row*width + col;
int label = labels.at(index, 0);
if (label == 1) {
result.at(row, col)[0] = 255;
result.at(row, col)[1] = 0;
result.at(row, col)[2] = 0;
}
else if (label == 2) {
result.at(row, col)[0] = 0;
result.at(row, col)[1] = 255;
result.at(row, col)[2] = 0;
}
else if (label == 3) {
result.at(row, col)[0] = 0;
result.at(row, col)[1] = 0;
result.at(row, col)[2] = 255;
}
else if (label == 0) {
result.at(row, col)[0] = 0;
result.at(row, col)[1] = 255;
result.at(row, col)[2] = 255;
}
}
}
imshow("kmeans-demo", result);
}```

output: