C++でOpenCVを使ってK-Meansクラスタリングを行うサンプル。
OpenCVのインストール
- CentOSの場合
yum install -y opencv-devel
サンプルソース
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/flann/flann.hpp>
int main() {
cv::Mat samples = cv::Mat::zeros(5, 5, CV_32FC1);
samples.at<float>(0, 0) = 100.0;
samples.at<float>(1, 0) = 100.0;
samples.at<float>(2, 0) = 80.0;
samples.at<float>(3, 0) = 70.0;
samples.at<float>(4, 0) = 50.0;
std::cout << "samples=\n" << samples << std::endl;
int n_clusters = 3;
cv::Mat clusters = cv::Mat::zeros(samples.rows, 1, CV_32SC1);
cv::Mat centers;
cv::theRNG() = 19771228; //クラスタリングの結果を固定する場合
cv::kmeans(samples,
n_clusters,
clusters,
cvTermCriteria(CV_TERMCRIT_EPS|CV_TERMCRIT_ITER, 10, 1.0),
1,
cv::KMEANS_PP_CENTERS,
centers);
//std::cout << clusters << std::endl;
printf("clusters=\n");
for (int i = 0; i < clusters.rows; i++) {
printf("%d ", clusters.at<int>(i));
}
printf("\n");
//std::cout << centers << std::endl;
printf("centers=\n");
for (int i = 0; i < centers.rows; i++) {
for (int j = 0; j < centers.cols; j++) {
printf("%f ", centers.at<float>(i, j));
}
printf("\n");
}
return 0;
}
コンパイル
g++ -I /usr/include/opencv2 -lopencv_core -lopencv_flann kmeans.cpp -o kmeans
実行結果
./kmeans
samples=
[100, 0, 0, 0, 0;
100, 0, 0, 0, 0;
80, 0, 0, 0, 0;
70, 0, 0, 0, 0;
50, 0, 0, 0, 0]
clusters=
0 0 1 1 2
centers=
100.000000 0.000000 0.000000 0.000000 0.000000
75.000000 0.000000 0.000000 0.000000 0.000000
50.000000 0.000000 0.000000 0.000000 0.000000
参考