OpenCV 4.12.0
開源計算機視覺
載入中...
搜尋中...
無匹配項
samples/cpp/kmeans.cpp

k-means 聚類示例

#include "opencv2/core.hpp"
#include <iostream>
using namespace cv;
using namespace std;
// static void help()
// {
// cout << "\n此程式演示了 kmeans 聚類。\n"
// "它生成一個帶有隨機點的影像,然後分配一個隨機數量的聚類\n"
// "中心,並使用 kmeans 將這些聚類中心移動到它們的代表位置\n"
// "呼叫\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;
/* 從多高斯分佈生成隨機樣本 */
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,
TermCriteria( TermCriteria::EPS+TermCriteria::COUNT, 10, 1.0),
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 << endl;
imshow("聚類", img);
char key = (char)waitKey();
if( key == 27 || key == 'q' || key == 'Q' ) // 'ESC'
break;
}
return 0;
}
n 維密集陣列類
定義 mat.hpp:830
_Tp & at(int i0=0)
返回指定陣列元素的引用。
int cols
定義 mat.hpp:2165
Mat rowRange(int startrow, int endrow) const
為指定的行跨度建立一個矩陣頭。
int rows
當矩陣具有超過 2 個維度時,行數和列數或 (-1, -1)
定義 mat.hpp:2165
_Tp y
點的 y 座標
定義 types.hpp:202
_Tp x
點的 x 座標
定義 types.hpp:201
隨機數生成器。
Definition core.hpp:2879
int uniform(int a, int b)
返回 [a,b) 範圍內均勻分佈的整數隨機數
void fill(InputOutputArray mat, int distType, InputArray a, InputArray b, bool saturateRange=false)
用隨機數填充陣列。
為迭代演算法定義終止標準的類。
定義 types.hpp:893
#define CV_32FC2
定義 interface.h:119
CV_8UC3
#define CV_8UC3
#define MIN(a, b)
定義 cvdef.h:514
int main(int argc, char *argv[])
定義 highgui_qt.cpp:3
定義 core.hpp:107
STL 名稱空間。