OpenCV的聚类函数cvKMeans2() - 当我使用centers参数时,为什么不起作用

时间:2011-09-08 21:47:47

标签: opencv k-means

我使用此代码。它应该打印簇标签然后打印质心。但是带有中心的'中心'矩阵似乎是空的,充满了零。我的朋友有什么不对?

 #include <iostream>
   #include <stdio.h>


     #include "cxcore.h"
      #include "highgui.h"
        using namespace cv;


       int main( int argc, char** argv )
       {

        int i,j;


              CvMat* points = cvCreateMat( 5, 2, CV_32FC1 );
                CvMat* centers2 = cvCreateMat( 5, 2, CV_32FC1 );
               CvMat* clusters = cvCreateMat( 5, 1, CV_32SC1 );

               cvSetReal2D( points, 0, 0,1);
                  cvSetReal2D( points, 0, 1,1);
                   cvSetReal2D( points, 1, 0,2);
                    cvSetReal2D( points, 1, 1,2);
                     cvSetReal2D( points, 2, 0,6);
                        cvSetReal2D( points, 2, 1,6);
                      cvSetReal2D( points, 3, 0,5);
                       cvSetReal2D( points, 3, 1,5);
                              cvSetReal2D( points, 4, 0,10);
                             cvSetReal2D( points, 4, 1,10);
 cvKMeans2(points,3,clusters,cvTermCriteria(CV_TERMCRIT_EPS,1000,0 ), 
 1000,0,KMEANS_RANDOM_CENTERS,centers2,0);

 for(i=0;i<5;i++)
  printf( " %lf \n", cvGetReal2D(clusters,i, 0));

       for(i=0;i<5;i++){
              for(j=0;j<2;j++){
        printf( "center %i %i = %f \n", i, j, cvGetReal2D(centers2,i, j));
    }
  }


          cvReleaseMat(&points);
               cvReleaseMat(&centers2);
                  cvReleaseMat(&clusters);
                      }

1 个答案:

答案 0 :(得分:3)

您的代码不起作用,因为centers2的大小比请求的群集数量大。但是,您似乎发现了一个OpenCV错误 - centers2必须重新分配,但事实并非如此。

将您的代码更改为

CvMat* centers2 = cvCreateMat( 3, 2, CV_32FC1 );

for(i=0;i<3;i++){
    for(j=0;j<2;j++){
        printf( "center %i %i = %f \n", i, j, cvGetReal2D(centers2,i, j));

但最好使用C ++接口(C版本的kmeans只是C ++实现的包装器):

float pointsdata[] = { 1,1, 2,2, 6,6, 5,5, 10,10};
Mat points(5, 2, CV_32F, pointsdata);
Mat labels, centers;

kmeans(points, 3, labels, TermCriteria(CV_TERMCRIT_EPS, 1000, 0), 1000, KMEANS_RANDOM_CENTERS, centers);

cout << "labels: " << labels << endl;
cout << "centers " << centers << endl;