Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Tetragramm
GitHub Repository: Tetragramm/opencv
Path: blob/master/samples/cpp/kmeans.cpp
16337 views
1
#include "opencv2/highgui.hpp"
2
#include "opencv2/core.hpp"
3
#include "opencv2/imgproc.hpp"
4
#include <iostream>
5
6
using namespace cv;
7
using namespace std;
8
9
// static void help()
10
// {
11
// cout << "\nThis program demonstrates kmeans clustering.\n"
12
// "It generates an image with random points, then assigns a random number of cluster\n"
13
// "centers and uses kmeans to move those cluster centers to their representitive location\n"
14
// "Call\n"
15
// "./kmeans\n" << endl;
16
// }
17
18
int main( int /*argc*/, char** /*argv*/ )
19
{
20
const int MAX_CLUSTERS = 5;
21
Scalar colorTab[] =
22
{
23
Scalar(0, 0, 255),
24
Scalar(0,255,0),
25
Scalar(255,100,100),
26
Scalar(255,0,255),
27
Scalar(0,255,255)
28
};
29
30
Mat img(500, 500, CV_8UC3);
31
RNG rng(12345);
32
33
for(;;)
34
{
35
int k, clusterCount = rng.uniform(2, MAX_CLUSTERS+1);
36
int i, sampleCount = rng.uniform(1, 1001);
37
Mat points(sampleCount, 1, CV_32FC2), labels;
38
39
clusterCount = MIN(clusterCount, sampleCount);
40
std::vector<Point2f> centers;
41
42
/* generate random sample from multigaussian distribution */
43
for( k = 0; k < clusterCount; k++ )
44
{
45
Point center;
46
center.x = rng.uniform(0, img.cols);
47
center.y = rng.uniform(0, img.rows);
48
Mat pointChunk = points.rowRange(k*sampleCount/clusterCount,
49
k == clusterCount - 1 ? sampleCount :
50
(k+1)*sampleCount/clusterCount);
51
rng.fill(pointChunk, RNG::NORMAL, Scalar(center.x, center.y), Scalar(img.cols*0.05, img.rows*0.05));
52
}
53
54
randShuffle(points, 1, &rng);
55
56
double compactness = kmeans(points, clusterCount, labels,
57
TermCriteria( TermCriteria::EPS+TermCriteria::COUNT, 10, 1.0),
58
3, KMEANS_PP_CENTERS, centers);
59
60
img = Scalar::all(0);
61
62
for( i = 0; i < sampleCount; i++ )
63
{
64
int clusterIdx = labels.at<int>(i);
65
Point ipt = points.at<Point2f>(i);
66
circle( img, ipt, 2, colorTab[clusterIdx], FILLED, LINE_AA );
67
}
68
for (i = 0; i < (int)centers.size(); ++i)
69
{
70
Point2f c = centers[i];
71
circle( img, c, 40, colorTab[i], 1, LINE_AA );
72
}
73
cout << "Compactness: " << compactness << endl;
74
75
imshow("clusters", img);
76
77
char key = (char)waitKey();
78
if( key == 27 || key == 'q' || key == 'Q' ) // 'ESC'
79
break;
80
}
81
82
return 0;
83
}
84
85