kmean.cpp
上传用户:banwdc
上传日期:2016-06-25
资源大小:2871k
文件大小:2k
源码类别:

OpenCV

开发平台:

Visual C++

  1. #include "cxcore.h"
  2. #include "highgui.h"
  3. int main( int argc, char** argv )
  4. {
  5.     #define MAX_CLUSTERS 5
  6.     CvScalar color_tab[MAX_CLUSTERS];
  7.     IplImage* img = cvCreateImage( cvSize( 500, 500 ), 8, 3 );
  8.     CvRNG rng = cvRNG(0xffffffff);
  9.     
  10.     color_tab[0] = CV_RGB(255,0,0);
  11.     color_tab[1] = CV_RGB(0,255,0);
  12.     color_tab[2] = CV_RGB(100,100,255);
  13.     color_tab[3] = CV_RGB(255,0,255);
  14.     color_tab[4] = CV_RGB(255,255,0);
  15.     cvNamedWindow( "clusters", 1 );
  16.     for(;;)
  17.     {
  18.         int k, cluster_count = cvRandInt(&rng)%MAX_CLUSTERS + 1;
  19.         int i, sample_count = cvRandInt(&rng)%1000 + 1;
  20.         CvMat* points = cvCreateMat( sample_count, 1, CV_32FC2 );
  21.         CvMat* clusters = cvCreateMat( sample_count, 1, CV_32SC1 );
  22.         /* generate random sample from multigaussian distribution */
  23.         for( k = 0; k < cluster_count; k++ )
  24.         {
  25.             CvPoint center;
  26.             CvMat point_chunk;
  27.             center.x = cvRandInt(&rng)%img->width;
  28.             center.y = cvRandInt(&rng)%img->height;
  29.             cvGetRows( points, &point_chunk, k*sample_count/cluster_count, 
  30.                     k == cluster_count - 1 ? sample_count : (k+1)*sample_count/cluster_count );
  31.             cvRandArr( &rng, &point_chunk, CV_RAND_NORMAL,
  32.                        cvScalar(center.x,center.y,0,0),
  33.                        cvScalar(img->width/6, img->height/6,0,0) );
  34.         }
  35.         /* shuffle samples */
  36.         for( i = 0; i < sample_count/2; i++ )
  37.         {
  38. CvPoint2D32f* pt1 = (CvPoint2D32f*)points->data.fl +
  39.  cvRandInt(&rng)%sample_count;
  40. CvPoint2D32f* pt2 = (CvPoint2D32f*)points->data.fl +
  41.  cvRandInt(&rng)%sample_count;
  42.             CvPoint2D32f temp;
  43.             CV_SWAP( *pt1, *pt2, temp );
  44.         }
  45.         cvKMeans2( points, cluster_count, clusters,
  46.                    cvTermCriteria( CV_TERMCRIT_EPS+CV_TERMCRIT_ITER, 
  47. 10, 1.0 ));
  48.         cvZero( img );
  49.         for( i = 0; i < sample_count; i++ )
  50.         {
  51.             CvPoint2D32f pt = ((CvPoint2D32f*)points->data.fl)[i];
  52.             int cluster_idx = clusters->data.i[i];
  53.             cvCircle( img, cvPointFrom32f(pt), 2, color_tab[cluster_idx], CV_FILLED );
  54.         }
  55.         cvReleaseMat( &points );
  56.         cvReleaseMat( &clusters );
  57.         cvShowImage( "clusters", img );
  58.         int key = cvWaitKey(0);
  59.         if( key == 27 ) // 'ESC'
  60.             break;
  61.     }
  62. }