OpenCV  4.5.2
Open Source Computer Vision
samples/cpp/kmeans.cpp

An example on K-means clustering

#include "opencv2/core.hpp"
#include <iostream>
using namespace cv;
using namespace std;
// static void help()
// {
// cout << "\nThis program demonstrates kmeans clustering.\n"
// "It generates an image with random points, then assigns a random number of cluster\n"
// "centers and uses kmeans to move those cluster centers to their representitive location\n"
// "Call\n"
// "./kmeans\n" << endl;
// }
int main( int /*argc*/, char** /*argv*/ )
{
const int MAX_CLUSTERS = 5;
Scalar colorTab[] =
{
Scalar(0, 0, 255),
Scalar(0,255,0),
Scalar(255,100,100),
Scalar(255,0,255),
Scalar(0,255,255)
};
Mat img(500, 500, CV_8UC3);
RNG rng(12345);
for(;;)
{
int k, clusterCount = rng.uniform(2, MAX_CLUSTERS+1);
int i, sampleCount = rng.uniform(1, 1001);
Mat points(sampleCount, 1, CV_32FC2), labels;
clusterCount = MIN(clusterCount, sampleCount);
std::vector<Point2f> centers;
/* generate random sample from multigaussian distribution */
for( k = 0; k < clusterCount; k++ )
{
Point center;
center.x = rng.uniform(0, img.cols);
center.y = rng.uniform(0, img.rows);
Mat pointChunk = points.rowRange(k*sampleCount/clusterCount,
k == clusterCount - 1 ? sampleCount :
(k+1)*sampleCount/clusterCount);
rng.fill(pointChunk, RNG::NORMAL, Scalar(center.x, center.y), Scalar(img.cols*0.05, img.rows*0.05));
}
randShuffle(points, 1, &rng);
double compactness = kmeans(points, clusterCount, labels,
3, KMEANS_PP_CENTERS, centers);
img = Scalar::all(0);
for( i = 0; i < sampleCount; i++ )
{
int clusterIdx = labels.at<int>(i);
Point ipt = points.at<Point2f>(i);
circle( img, ipt, 2, colorTab[clusterIdx], FILLED, LINE_AA );
}
for (i = 0; i < (int)centers.size(); ++i)
{
Point2f c = centers[i];
circle( img, c, 40, colorTab[i], 1, LINE_AA );
}
cout << "Compactness: " << compactness << endl;
imshow("clusters", img);
char key = (char)waitKey();
if( key == 27 || key == 'q' || key == 'Q' ) // 'ESC'
break;
}
return 0;
}
cv::RNG::uniform
int uniform(int a, int b)
returns uniformly distributed integer random number from [a,b) range
cv::Mat::rows
int rows
the number of rows and columns or (-1, -1) when the matrix has more than 2 dimensions
Definition: mat.hpp:2096
cv::Point_< int >
cv::Scalar_< double >::all
static Scalar_< double > all(double v0)
returns a scalar with all elements set to v0
cv::TermCriteria
The class defining termination criteria for iterative algorithms.
Definition: types.hpp:852
cv::Mat::at
_Tp & at(int i0=0)
Returns a reference to the specified array element.
cv::waitKey
int waitKey(int delay=0)
Waits for a pressed key.
cv::TermCriteria::COUNT
@ COUNT
the maximum number of iterations or elements to compute
Definition: types.hpp:860
cv::TermCriteria::EPS
@ EPS
the desired accuracy or change in parameters at which the iterative algorithm stops
Definition: types.hpp:862
cv::KMEANS_PP_CENTERS
@ KMEANS_PP_CENTERS
Definition: core.hpp:217
cv::Point_::y
_Tp y
y coordinate of the point
Definition: types.hpp:187
cv::Point_::x
_Tp x
x coordinate of the point
Definition: types.hpp:186
cv::randShuffle
void randShuffle(InputOutputArray dst, double iterFactor=1., RNG *rng=0)
Shuffles the array elements randomly.
highgui.hpp
core.hpp
cv::Scalar_< double >
cv::Mat::cols
int cols
Definition: mat.hpp:2096
CV_8UC3
#define CV_8UC3
Definition: interface.h:90
cv::FILLED
@ FILLED
Definition: imgproc.hpp:813
MIN
#define MIN(a, b)
Definition: cvdef.h:485
CV_32FC2
#define CV_32FC2
Definition: interface.h:119
cv::kmeans
double kmeans(InputArray data, int K, InputOutputArray bestLabels, TermCriteria criteria, int attempts, int flags, OutputArray centers=noArray())
Finds centers of clusters and groups input samples around the clusters.
cv::RNG::NORMAL
@ NORMAL
Definition: core.hpp:2786
cv::imshow
void imshow(const String &winname, InputArray mat)
Displays an image in the specified window.
cv::Mat::rowRange
Mat rowRange(int startrow, int endrow) const
Creates a matrix header for the specified row span.
cv::Scalar
Scalar_< double > Scalar
Definition: types.hpp:669
cv::RNG
Random Number Generator.
Definition: core.hpp:2782
cv::Mat
n-dimensional dense array class
Definition: mat.hpp:801
cv
"black box" representation of the file storage associated with a file on disk.
Definition: affine.hpp:51
imgproc.hpp
cv::RNG::fill
void fill(InputOutputArray mat, int distType, InputArray a, InputArray b, bool saturateRange=false)
Fills arrays with random numbers.
cv::LINE_AA
@ LINE_AA
antialiased line
Definition: imgproc.hpp:816
cv::circle
void circle(InputOutputArray img, Point center, int radius, const Scalar &color, int thickness=1, int lineType=LINE_8, int shift=0)
Draws a circle.