赞
踩
今天学习了下Kmeans算法,KMeans算法属于无监督学习的一种,主要通过不断迭代center中心点来使得cast损失函数最小化,即在方差最小的准则下进行不断迭代,当cast与上一次的迭代结果相同则终止迭代。但同时KMeans也存在相应缺点,即最后的聚类结果跟初始选定的中心点有关。
主要的公式如下所示:
主要的算法流程如下所示:
Code:
/*
*作者:att0206
*地点:上海师范大学
*时间:2017/04/06
*功能:实现对K-Means的学习
*/
#include<opencv2/opencv.hpp>
#include<opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
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[])
{
rstImage = imread("1.jpg");
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<height;row++)
{
for(int col = 0;col<width;col++)
{
index = row*width+col;
Vec3b rgb = rstImage.at<Vec3b>(row,col);
points.at<float>(index,0) = static_cast<int>(rgb[0]);
points.at<float>(index,1) = static_cast<int>(rgb[1]);
points.at<float>(index,2) = static_cast<int>(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<int>(index, 0);
if (label == 1) {
result.at<Vec3b>(row, col)[0] = 255;
result.at<Vec3b>(row, col)[1] = 0;
result.at<Vec3b>(row, col)[2] = 0;
}
else if (label == 2) {
result.at<Vec3b>(row, col)[0] = 0;
result.at<Vec3b>(row, col)[1] = 255;
result.at<Vec3b>(row, col)[2] = 0;
}
else if (label == 3) {
result.at<Vec3b>(row, col)[0] = 0;
result.at<Vec3b>(row, col)[1] = 0;
result.at<Vec3b>(row, col)[2] = 255;
}
else if (label == 0) {
result.at<Vec3b>(row, col)[0] = 0;
result.at<Vec3b>(row, col)[1] = 255;
result.at<Vec3b>(row, col)[2] = 255;
}
}
}
imshow("kmeans-demo", result);
}
output:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。