3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

C++でOpenCVを使ってK-meansクラスタリング

Last updated at Posted at 2016-12-07

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

参考

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?