Update to 2.0.0 tree from current Fremantle build
[opencv] / samples / octave / kmeans.m
1 #! /usr/bin/env octave
2 cv;
3 highgui;
4 MAX_CLUSTERS=5;
5
6 function ret = randint(v1, v2)
7   ret = int32(rand() * (v2 - v1) + v1);
8 end
9
10 color_tab = { \
11              CV_RGB(255,0,0), \
12              CV_RGB(0,255,0), \
13              CV_RGB(100,100,255), \
14              CV_RGB(255,0,255), \
15              CV_RGB(255,255,0)};
16 img = cvCreateImage( cvSize( 500, 500 ), 8, 3 );
17 rng = cvRNG(-1);
18
19 cvNamedWindow( "clusters", 1 );
20
21 while (true),
22   cluster_count = randint(2, MAX_CLUSTERS);
23   sample_count = randint(1, 1000);
24   points = cvCreateMat( sample_count, 1, CV_32FC2 );
25   clusters = cvCreateMat( sample_count, 1, CV_32SC1 );
26   
27   ## generate random sample from multigaussian distribution
28   for k=0:cluster_count-1,
29     center = CvPoint();
30     center.x = mod(cvRandInt(rng), img.width);
31     center.y = mod(cvRandInt(rng), img.height);
32     first = k*sample_count/cluster_count;
33     last = sample_count;
34     if (k != cluster_count)
35       last = (k+1)*sample_count/cluster_count;
36     endif
37
38     point_chunk = cvGetRows(points, first, last);
39     
40     cvRandArr( rng, point_chunk, CV_RAND_NORMAL, \
41               cvScalar(center.x,center.y,0,0), \
42               cvScalar(img.width*0.1,img.height*0.1,0,0));
43   endfor
44   
45
46   ## shuffle samples 
47   cvRandShuffle( points, rng );
48
49   cvKMeans2( points, cluster_count, clusters, \
50             cvTermCriteria( CV_TERMCRIT_EPS+CV_TERMCRIT_ITER, 10, 1.0 ));
51
52   cvZero( img );
53
54   for i=0:sample_count-1,
55     cluster_idx = clusters(i);
56     pt = points(i);
57     cvCircle( img, pt, 2, color_tab{cluster_idx + 1}, CV_FILLED, CV_AA, 0 );
58
59 cvCircle( img, pt, 2, color_tab{cluster_idx + 1}, CV_FILLED, CV_AA, 0 );
60   endfor
61   
62
63   cvShowImage( "clusters", img );
64
65   key = cvWaitKey(0);
66   if( key == 27 || key == 'q' || key == 'Q' )
67     break;
68   endif
69 endwhile
70
71
72 cvDestroyWindow( "clusters" );