2012-05-30 40 views
0

基本上,我有两个玩家位置点,我想聚集来自Vec2f的玩家位置。在opencv中的Kmean聚类

我试过的代码这个样本,但它不工作,并调用k均值功能时,它提供一个exceptin。

float *pointsdata = new float[10]; 

    for (std::map< unsigned int, Player >::iterator it = players.begin(); it != players.end(); ++it) 
    { 
     for (int i =0; i< players.size(); i++) 
     { 
      pointsdata[i] = it->second.m_Position.x; 
      pointsdata[i+1] = it->second.m_Position.y; 

     } 
    } 

    //float pointsdata[] = { 1,1, 2,2, 6,6, 5,5, 10,10}; 
    cv::Mat points(10, 2, CV_32F, *pointsdata); 
    cv::Mat labels, centers; 

    cv::kmeans(points, 3, labels, cv::TermCriteria(CV_TERMCRIT_EPS, 1000, 0), 1000, cv::KMEANS_RANDOM_CENTERS, centers); 


    cout << "labels: " << labels << endl; 
    cout << "centers " << centers << endl; 
+0

我们可以看到堆栈跟踪?如果在linux上,使用gdb执行它并在崩溃后输入bt。 – Brady

+0

我怀疑pointsdata数组是否正确?我只想要一个拥有玩家x和y位置的数组并将其馈送到矩阵 – Andre

+0

您确定'players.size()'不会大于9吗? – juanchopanza

回答

0

您有cv :: Mat API here。你正在尝试使用的构造函数如下,对吧?

Mat (int _rows, int _cols, int _type, void *_data, size_t _step=AUTO_STEP) 
constructor for matrix headers pointing to user-allocated data 

所以,你应该做到以下几点:

if(players.size() > 10) 
{ 
    cout << "ERROR, too many players\n"; 
    // Do some error handling here 
    return; 
} 

//float pointsdata[10][2]; // use this if it doesnt need to be dynamic 
/* 2D definition, but we need to create it as a 1D array with room for the 2d 
float **pointsdata = new float*[10]; 
for(int i = 0; i < 10; ++i) 
{ 
    pointsdata[i] = new float[2]; 
} 
*/ 
float *pointsdata = new float[10*2]; 

for (std::map< unsigned int, Player >::iterator it = players.begin(); 
    it != players.end(); 
    ++it) 
{ 
    for (int i =0; i< players.size() && i < 10; i++) 
    { 
     pointsdata[i] = it->second.m_Position.x; 
     pointsdata[i + 10*i] = it->second.m_Position.y; 
    } 
} 

cv::Mat points(10, 2, CV_32F, pointsdata); 
+0

谢谢,我该如何使用玩家位置x,y初始化积分数据? – Andre

+0

@AhmedSalehMohamed,更新的答案为初始化位置 – Brady

+0

没有与这样的错误: 浮子* pointsdata =新的浮动[10] [2]; – Andre