Move the sources to trunk
[opencv] / samples / c / kmeans.c
1 #ifdef _CH_
2 #pragma package <opencv>
3 #endif
4
5 #ifndef _EiC
6 #include "cv.h"
7 #include "highgui.h"
8 #endif
9
10 int main( int argc, char** argv )
11 {
12     #define MAX_CLUSTERS 5
13     CvScalar color_tab[MAX_CLUSTERS];
14     IplImage* img = cvCreateImage( cvSize( 500, 500 ), 8, 3 );
15     CvRNG rng = cvRNG(-1);
16     CvPoint ipt;
17
18     color_tab[0] = CV_RGB(255,0,0);
19     color_tab[1] = CV_RGB(0,255,0);
20     color_tab[2] = CV_RGB(100,100,255);
21     color_tab[3] = CV_RGB(255,0,255);
22     color_tab[4] = CV_RGB(255,255,0);
23
24     cvNamedWindow( "clusters", 1 );
25         
26     for(;;)
27     {
28         char key;
29         int k, cluster_count = cvRandInt(&rng)%MAX_CLUSTERS + 1;
30         int i, sample_count = cvRandInt(&rng)%1000 + 1;
31         CvMat* points = cvCreateMat( sample_count, 1, CV_32FC2 );
32         CvMat* clusters = cvCreateMat( sample_count, 1, CV_32SC1 );
33         
34         /* generate random sample from multigaussian distribution */
35         for( k = 0; k < cluster_count; k++ )
36         {
37             CvPoint center;
38             CvMat point_chunk;
39             center.x = cvRandInt(&rng)%img->width;
40             center.y = cvRandInt(&rng)%img->height;
41             cvGetRows( points, &point_chunk, k*sample_count/cluster_count,
42                        k == cluster_count - 1 ? sample_count :
43                        (k+1)*sample_count/cluster_count, 1 );
44                         
45             cvRandArr( &rng, &point_chunk, CV_RAND_NORMAL,
46                        cvScalar(center.x,center.y,0,0),
47                        cvScalar(img->width*0.1,img->height*0.1,0,0));
48         }
49
50         /* shuffle samples */
51         for( i = 0; i < sample_count/2; i++ )
52         {
53             CvPoint2D32f* pt1 = (CvPoint2D32f*)points->data.fl + cvRandInt(&rng)%sample_count;
54             CvPoint2D32f* pt2 = (CvPoint2D32f*)points->data.fl + cvRandInt(&rng)%sample_count;
55             CvPoint2D32f temp;
56             CV_SWAP( *pt1, *pt2, temp );
57         }
58
59         cvKMeans2( points, cluster_count, clusters,
60                    cvTermCriteria( CV_TERMCRIT_EPS+CV_TERMCRIT_ITER, 10, 1.0 ));
61
62         cvZero( img );
63
64         for( i = 0; i < sample_count; i++ )
65         {
66             int cluster_idx = clusters->data.i[i];
67             ipt.x = (int)points->data.fl[i*2];
68             ipt.y = (int)points->data.fl[i*2+1];
69             cvCircle( img, ipt, 2, color_tab[cluster_idx], CV_FILLED, CV_AA, 0 );
70         }
71
72         cvReleaseMat( &points );
73         cvReleaseMat( &clusters );
74
75         cvShowImage( "clusters", img );
76
77         key = (char) cvWaitKey(0);
78         if( key == 27 || key == 'q' || key == 'Q' ) // 'ESC'
79             break;
80     }
81     
82     cvDestroyWindow( "clusters" );
83     return 0;
84 }
85
86 #ifdef _EiC
87 main(1,"kmeans.c");
88 #endif