1 #include "opencv2/highgui/highgui.hpp"
2 #include "opencv2/core/core.hpp"
10 // cout << "\nThis program demonstrates kmeans clustering.\n"
11 // "It generates an image with random points, then assigns a random number of cluster\n"
12 // "centers and uses kmeans to move those cluster centers to their representitive location\n"
14 // "./kmeans\n" << endl;
17 int main( int /*argc*/, char** /*argv*/ )
19 const int MAX_CLUSTERS = 5;
29 Mat img(500, 500, CV_8UC3);
34 int k, clusterCount = rng.uniform(2, MAX_CLUSTERS+1);
35 int i, sampleCount = rng.uniform(1, 1001);
36 Mat points(sampleCount, 1, CV_32FC2), labels;
38 clusterCount = MIN(clusterCount, sampleCount);
41 /* generate random sample from multigaussian distribution */
42 for( k = 0; k < clusterCount; k++ )
45 center.x = rng.uniform(0, img.cols);
46 center.y = rng.uniform(0, img.rows);
47 Mat pointChunk = points.rowRange(k*sampleCount/clusterCount,
48 k == clusterCount - 1 ? sampleCount :
49 (k+1)*sampleCount/clusterCount);
50 rng.fill(pointChunk, RNG::NORMAL, Scalar(center.x, center.y), Scalar(img.cols*0.05, img.rows*0.05));
53 randShuffle(points, 1, &rng);
55 kmeans(points, clusterCount, labels,
56 TermCriteria( TermCriteria::EPS+TermCriteria::COUNT, 10, 1.0),
57 3, KMEANS_PP_CENTERS, centers);
61 for( i = 0; i < sampleCount; i++ )
63 int clusterIdx = labels.at<int>(i);
64 Point ipt = points.at<Point2f>(i);
65 circle( img, ipt, 2, colorTab[clusterIdx], FILLED, LINE_AA );
68 imshow("clusters", img);
70 char key = (char)waitKey();
71 if( key == 27 || key == 'q' || key == 'Q' ) // 'ESC'