#include "opencv2/highgui.hpp"
#include "opencv2/core.hpp"
#include "opencv2/imgproc.hpp"
#include <iostream>
using namespace cv;
using namespace std;
// static void help()
// {
// cout << "\nThis program demonstrates kmeans clustering.\n"
// "It generates an image with random points, then assigns a random number of cluster\n"
// "centers and uses kmeans to move those cluster centers to their representitive location\n"
// "Call\n"
// "./kmeans\n" << endl;
// }
int main(int /*argc*/, char** /*argv*/)
{
const int MAX_CLUSTERS = 5;
Scalar colorTab[] =
{
Scalar(0, 0, 255),
Scalar(0, 255, 0),
Scalar(255, 100, 100),
Scalar(255, 0, 255),
Scalar(0, 255, 255)
};
Mat img(500, 500, CV_8UC3);
RNG rng;
for (;;)
{
int k, clusterCount = rng.uniform(2, MAX_CLUSTERS + 1);//聚类数
int i, sampleCount = rng.uniform(100, 2000);//样点数
Mat points(sampleCount, 1, CV_32FC2), labels;//建立一个2通道的一维数组
clusterCount = MIN(clusterCount, sampleCount);//聚类数
Mat centers;
/* generate random sample from multigaussian distribution */
for (k = 0; k < clusterCount; k++)
{
Point center;
center.x = rng.uniform(0, img.cols);//聚类中心的x坐标
center.y = rng.uniform(0, img.rows);//聚类中心的y坐标
Mat pointChunk = points.rowRange(k*sampleCount / clusterCount,//设置样本范围
k == clusterCount - 1 ? sampleCount :
(k + 1)*sampleCount / clusterCount);
rng.fill(pointChunk, RNG::NORMAL, Scalar(center.x, center.y), Scalar(img.cols*0.05, img.rows*0.05));//产生样本
}
randShuffle(points, 1, &rng);
kmeans(points, clusterCount, labels,
TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 10, 1.0),
3, KMEANS_PP_CENTERS, centers);
img = Scalar::all(0);
for (i = 0; i < sampleCount; i++)
{
int clusterIdx = labels.at<int>(i);
Point ipt = points.at<Point2f>(i);
circle(img, ipt, 1, colorTab[clusterIdx], FILLED, LINE_AA);
}
imshow("clusters", img);
char key = (char)waitKey();
if (key == 27 || key == 'q' || key == 'Q') // 'ESC'
break;
}
return 0;
}
这个程序是opencv官方自带的源程序
位置是opencv/sources/samples/cpp kmeans.cpp
定义了一个RNG 随机数产生器 Mat image用于显示分类结果
MAX_CLUSTERS 分类数目
Scalar colorTab[] 因为分了5类多以用5种颜色表示
uniform(a,b) 用于产生随机数,a,b表示产生随机数的范围
sampleCount 产生的随机样点数
fill()填充随机数,可以用高斯分布和均匀分布填充,如果采用均匀分布后边的参数表示范围,如果是高斯分布,后边的参数分别是均值和方差
<pre name="code" class="cpp">randShuffle()将随机数打乱
kmeans()第一个参数是样本数,第二个参数是聚类数,第三个参数是每个样本数的指数,例如样本中的第一个数属于第一类,对应的指数为1,第四个参数是终止条件,第五个参数是聚类次数,第六个参数是type这个可以查看opencv手册,第六个参数是聚类中心