[OpenCV] K-Means Clustering CvPoint


/ Published in: C++
Save to your folder(s)



Copy this code and paste it in your HTML
  1. void kMeans(vector<CvPoint> &dataVector, const int clusterCount,
  2. vector < vector<CvPoint> > &clusterContainer)
  3. {
  4. /*
  5.   * Pre: "dataVector" the data to be clustered by K-Means
  6.   * "clusterCount" how many clusters you want
  7.   *
  8.   * Post: "classContainer" I pack the points with the same cluster into vector, so it
  9.   * is a vetor of vector
  10.   */
  11.  
  12.  
  13. int dataLength = dataVector.size();
  14.  
  15.  
  16. // Put data into suitable container
  17. CvMat* points = cvCreateMat(dataLength, 1, CV_32FC2);
  18. CvMat* clusters = cvCreateMat(dataLength, 1, CV_32SC1 );
  19.  
  20. for (int row = 0; row < points->rows; row++) {
  21. float* ptr = (float*)(points->data.ptr + row*points->step);
  22. for (int col = 0; col < points->cols; col++) {
  23. *ptr = static_cast<float>(dataVector[row].x);
  24. ptr++;
  25. *ptr = static_cast<float>(dataVector[row].y);
  26. }
  27. }
  28.  
  29. // The Kmeans algorithm function (OpenCV function)
  30. cvKMeans2(points, clusterCount, clusters, cvTermCriteria(CV_TERMCRIT_EPS+CV_TERMCRIT_ITER, 1, 2));
  31.  
  32. // Pack result to 'classContainer', each element in 'classContainer' means one cluster,
  33. // each cluster is one vector<CvPoint> contain all points belong to this cluster
  34. int clusterNum;
  35. vector<CvPoint> tempClass;
  36.  
  37. for (int i = 0; i < clusterCount; i++) {
  38. tempClass.clear();
  39.  
  40. for (int row = 0; row < clusters->rows; row++) {
  41.  
  42.  
  43. float* p_point = (float*)(points->data.ptr + row*points->step);
  44. int X = static_cast<int>(*p_point) ;
  45. p_point++;
  46. int Y = static_cast<int>(*p_point);
  47.  
  48. clusterNum = clusters->data.i[row];
  49.  
  50. if (clusterNum == i)
  51. tempClass.push_back(cvPoint(X, Y));
  52.  
  53. }
  54.  
  55. clusterContainer.push_back(tempClass);
  56.  
  57. }
  58.  
  59. // Remove empty cluster
  60. for (vector< vector<CvPoint> >::size_type i = 0; i < clusterContainer.size(); ++i) {
  61.  
  62. bool isEmpty = clusterContainer[i].empty();
  63.  
  64. if (isEmpty) {
  65. vector< vector<CvPoint> >::iterator iter = clusterContainer.begin();
  66. iter = iter + i;
  67. clusterContainer.erase(iter);
  68. i = i - 1;
  69. }
  70. }
  71.  
  72. cvReleaseMat(&points);
  73. cvReleaseMat(&clusters);
  74.  
  75.  
  76. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.