Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

there you go..

vector<Point2f> points;
points.push_back(Point2f(1,1));
points.push_back(Point2f(3,1));
points.push_back(Point2f(1,5));
points.push_back(Point2f(2,5));

Mat labels,centers;
int K=2, attempts=3, flags=cv::KMEANS_RANDOM_CENTERS; // hey, just guessing here
TermCriteria tc;

kmeans(points,K,labels,tc,attempts,flags, centers);   // points will get cast implicitly to Mat

for ( int i=0; i<labels.rows; i++ )
{
    int idx = labels.at<int>(i);
    Point2f original_point = points[i];
    Point2f clustered_center;
    clustered_center.x = centers.at<float>( idx,0 ); // yea, weird, i'd expect a Mat_<Point2f>
    clustered_center.y = centers.at<float>( idx,1 );
    cerr << i << " " << idx << " " << original_point << " " << clustered_center << endl;
}

0 1 [1, 1] [2, 1]
1 1 [3, 1] [2, 1]
2 0 [1, 5] [1.5, 5]
3 0 [2, 5] [1.5, 5]

there you go..

vector<Point2f> points;
points.push_back(Point2f(1,1));
points.push_back(Point2f(3,1));
points.push_back(Point2f(1,5));
points.push_back(Point2f(2,5));

Mat labels,centers;
int K=2, attempts=3, flags=cv::KMEANS_RANDOM_CENTERS; // hey, just guessing here
TermCriteria tc;

kmeans(points,K,labels,tc,attempts,flags, centers);   // points will get cast implicitly to Mat

for ( int i=0; i<labels.rows; i++ )
{
    int idx = labels.at<int>(i);
    Point2f original_point = points[i];
    Point2f clustered_center;
    clustered_center.x = centers.at<float>( idx,0 ); // yea, weird, i'd expect a Mat_<Point2f>
     clustered_center.y = centers.at<float>( idx,1 );
    cerr << i << " " << idx << " " << original_point << " " << clustered_center << endl;
}

0 1 [1, 1] [2, 1]
1 1 [3, 1] [2, 1]
2 0 [1, 5] [1.5, 5]
3 0 [2, 5] [1.5, 5]

you could also make the centers a Mat of Point2f again:

    Mat centers_point = centers.reshape(2,centers.rows);
    ...
        clustered_center = centers_point.at<Point2f>( idx );