0

基本上,我有两个玩家位置点,我想将来自 Vec2f 的玩家位置聚集在一起。

我尝试了这个代码示例,但它不起作用,并且在调用 kmeans 函数时它给出了一个异常。

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;
4

1 回答 1

0

You have the cv::Mat API here. The constructor you're trying to use is the following, right?

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

So you should probably do the following:

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);
于 2012-05-30T09:34:24.223 回答