KMeans and Hu-Moments

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

KMeans and Hu-Moments

dwickeroth
Hi,

In my code I calculate the Hu-Moments of about 200 contours and store
these in a QVector. Then I want to cluster these moments using
KMeans2, which works, but there is a problem: no matter in which order
the Hu-Moments are given, the last 70 moments or so always and up in
the same cluster. Since the order is randomized (the images the
contours come from are opened in a random order) there must be
something wrong.

Below is the code I use. Any help is very much appreciated!!

Cheers,
Daniel

--------------------
void MomentMaker::makeClusters(){

   //huMomentVector is a QVector<CvHuMoments*>
   int numOfMoments = huMomentVector.size();

   //create a big matrix with all of the Hu-Moments
   //one row per moment
   CvMat* sampleMat = cvCreateMat( numOfMoments, 7, CV_32FC2 );
   float * sampleData = sampleMat->data.fl;

   for(int i = 0; i < numOfMoments; i++){
      sampleData[i*7+0] = (float)(huMomentVector.at(i)->hu1);
      sampleData[i*7+1] = (float)(huMomentVector.at(i)->hu2);
      sampleData[i*7+2] = (float)(huMomentVector.at(i)->hu3);
      sampleData[i*7+3] = (float)(huMomentVector.at(i)->hu4);
      sampleData[i*7+4] = (float)(huMomentVector.at(i)->hu5);
      sampleData[i*7+5] = (float)(huMomentVector.at(i)->hu6);
      sampleData[i*7+6] = (float)(huMomentVector.at(i)->hu7);
   }


   //create the matrix with the indices, telling which moments belongs
to which cluster
   CvMat* clusters = cvCreateMat(numOfMoments, 1, CV_32SC1 );

   //use KMeans to split Hu-Moments to clusters
   cvKMeans2(sampleMat, MAX_CLUSTERS, clusters, cvTermCriteria(
CV_TERMCRIT_EPS+CV_TERMCRIT_ITER, clusterIter, clusterEpsilon ));  


   //How many elements does each cluster have?
   //MAX_CLUSTERS is defined as 10
   int clusterElemCount[MAX_CLUSTERS];
   for(int i = 0; i < MAX_CLUSTERS; i++){
      clusterElemCount[i] = 0;
   }
   for(int i = 0; i < numOfMoments; i++){
      clusterElemCount[clusters->data.i[i]]++;
   }

   //print data
   for(int i = 0; i < numOfMoments; i++){
      textEdit->append(QString("Moment %1 belongs to Cluster
%2").arg(i).arg(clusters->data.i[i]));
   }
   for(int i = 0; i < MAX_CLUSTERS; i++){
      textEdit->append(QString("Cluster %1 has %2
elements").arg(i).arg(clusterElemCount[i]));
   }
}