Opencv: how does the "centers" option in cv :: kmeans work?

I am collecting points using kmeans from C ++. Clustering and plotting each point works well, I can get something like this:

enter image description here

but I cannot access the centers of each cluster (I want to build them). How can I get the positions of the centers without calculating them myself?

I am calling the function like this:

vector<Point2f> points;
...
// clustering
int K = 4; // number of clusters
Mat labels; // cluster each point belongs to
Mat centers; // center of each cluster
kmeans(points, K, labels, TermCriteria( TermCriteria::EPS+TermCriteria::COUNT, 50, 1.0), 3, KMEANS_PP_CENTERS, centers);

      

and I draw them like this:

for(unsigned int i = 0; i < points.size(); i++ ){
      int clusterIdx = labels.at<int>(i);
      Point ipt = points[i];
      circle(cluster_image, ipt, 10, colorTab[clusterIdx], -1, 8);
    }

      

+3


source to share


1 answer


You may want to look at the contents of your center matrix.

Size2i centersSize = centers.size();
std::list<Poind2f> centerPoints;
for(int i=0; i<centers.size(0); i++) {
    Point2f pt = centers.row(i);
    centerPoints.push_back(pt);
}

      



Even though the above code is untested, I hope it clears up the idea.

0


source







All Articles