-------------------------------------------------------------------------------------------------------------------------------
【图像算法】彩色图像分割专题九:基于KCM的彩色分割
SkySeraph July 31st 2011 HQU
Email:[email protected] QQ:452728574
Latest Modified Date:July 31st 2011 HQU
-------------------------------------------------------------------------------------------------------------------------------
》原理
提出者: http://www.cs.uwf.edu/~jbezdek/
原理相关: http://home.dei.polimi.it/matteucc/Clustering/tutorial_html/index.html
http://en.wikipedia.org/wiki/K-means_clustering
-------------------------------------------------------------------------------------------------------------------------------
》源码
利用OpenCV函数(cvKMeans2)
cvKMeans2说明:
void cvKMeans2(
const CvArr* samples, //输入样本的浮点矩阵,每个样本一行。
int cluster_count, //所给定的聚类数目
* labels, //输出整数向量:每个样本对应的类别标识
CvTermCriteria termcrit //指定聚类的最大迭代次数和/或精度(两次迭代引起的聚类中心的移动距离)
);
执行源码:
1 void CColorImgSftDlg::OnKcm() //Kmeans
2 {
3 if(!(ToDisplayCtr1))
4 {
5 MessageBox("Please Load Pic!");
6 return;
7 }
8
9 BeginWaitCursor();
10 int64 begin_count = cvGetTickCount();
11
12 IplImage* src;
13 src = ToDisplayCtr1;
14
15 int width = src->width;
16 int height = src->height;
17 int channel = src->nChannels;
18 int lenth = width*height;
19
20 CvMat *samples=cvCreateMat(width*height,1,CV_32FC3);
21 CvMat *clusters=cvCreateMat(width*height,1,CV_32SC1);
22
23 int k=0;
24 for (int i=0;i<width;i++)
25 {
26 for (int j=0;j<height;j++)
27 {
28 CvScalar s;
29 s.val[0]=(float)cvGet2D(src,j,i).val[0];
30 s.val[1]=(float)cvGet2D(src,j,i).val[1];
31 s.val[2]=(float)cvGet2D(src,j,i).val[2];
32 cvSet2D(samples,k++,0,s);
33 }
34 }
35
36 int nCuster=2;
37 cvKMeans2(samples,nCuster,clusters,cvTermCriteria(CV_TERMCRIT_ITER,100,1.0));
38 IplImage *bin=cvCreateImage(cvSize(width,height),IPL_DEPTH_8U,1);
39 k=0;
40 int val=0;
41 float step=255/(nCuster-1);
42
43 for (i=0;i<width;i++)
44 {
45 for (int j=0;j<height;j++)
46 {
47 val=(int)clusters->data.i[k++];
48 CvScalar s;
49 s.val[0]=255-val*step;
50 cvSet2D(bin,j,i,s);
51 }
52 }
53 SetDlgItemInt(IDC_TimeCost, (unsigned int)((cvGetTickCount() - begin_count)/cvGetTickFrequency()/1000 ));
54
55 if(ToDisplayCtr3)
56 cvZero(ToDisplayCtr3);
57 cvCopyImage(bin,ToDisplayCtr3);
58 DrawPicToHDC(ToDisplayCtr3,IDC_ImgShowCtrl3);
59
60 cvReleaseImage(&bin);
61 EndWaitCursor();
62 }
-------------------------------------------------------------------------------------------------------------------------------
》效果
还是采用Meanshift中那位MM来分割下:
运行时间199ms
原图:
分割图:
-------------------------------------------------------------------------------------------------------------------------------
Author: SKySeraph
Email/GTalk: [email protected] QQ:452728574
From: http://www.cnblogs.com/skyseraph/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.
-------------------------------------------------------------------------------------------------------------------------------