opencv kmeans返回错误的结果

时间:2014-12-24 10:13:47

标签: c++ opencv

我试图用OpenCV kmeans聚集十个二维点。守则如下:

vector<Point2f>data( 10 );
data[0] = {118.90323, 1088.7419};
data[1] = {143.5, 1064.5};
data[2] = {110, 1054};
data[3] = {662, 645};
data[4] = {650, 625.5};
data[5] = {94, 363};
data[6] = {60, 360};
data[7] = {103.97369, 315.71054};
data[8] = {70.5, 313};
data[9] = {1466, 278.55554};
cout << "data:" << data << endl;
Mat labels;
int cluster_number = 4;
TermCriteria criteria = TermCriteria( CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 40, 0.1 );
Mat centers;
kmeans(data, cluster_number, labels, criteria, 1, KMEANS_RANDOM_CENTERS, centers);
cout << "centers:" << centers << endl;
cout << "labels:" << labels << endl;

输出结果为:

data: 
[118.90323, 1088.7419; 143.5, 1064.5; 110, 1054; 662, 645; 650, 625.5; 94, 363; 60, 360; 103.97369, 315.71054; 70.5, 313; 1466, 278.55554]

centers: 
[1.9113665e-38, 2.4802983e-43; 0, 0; 118.90323, 1088.7419; 0, 0]

labels: 
[2; 0; 0; 0; 0; 0; 0; 0; 3; 1]

这显然是错误的。我想要标签

[0,0,0,1,1,2,2,2,2,3]

非常感谢你的帮助!!

1 个答案:

答案 0 :(得分:0)

此测试对我有用:

void main()
{
    float data[10][2]=
    {{118.90323, 1088.7419},
    {143.5, 1064.5},
    {110, 1054},
    {662, 645},
    {650, 625.5},
    {94, 363},
    {60, 360},
    {103.97369, 315.71054},
    {70.5, 313},
    {1466, 278.55554}};


    Mat points(10,2, CV_32FC1,*data);
    cout << points << endl;
    Mat labels, centers;
    int k =4;
    cv::kmeans(points,k, labels,TermCriteria( CV_TERMCRIT_EPS+CV_TERMCRIT_ITER, 10, 1.0),3, KMEANS_PP_CENTERS, centers);
    std::cout << "labels: " << labels << endl;
    std::cout << "centers " << centers << endl;
    cv::waitKey(0);
    getchar();
}