0

我使用此代码。它应该打印集群标签然后是质心。但是带有质心的“中心”矩阵似乎是空的,充满了零。我的朋友们怎么了?

 #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);
                      }
4

1 回答 1

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;
于 2011-09-09T11:13:02.463 回答