C ++在鼠标回调函数中使用push_back

时间:2014-05-29 09:30:17

标签: c++ opencv

我正在尝试编写一些代码来计划机器人的路径,方法是单击图像中的点并将它们存储在点矢量中。每次单击鼠标时,我都想使用push_back来增加向量的大小,并将新点附加到末尾。我的代码如下:

void planPath(cv::Mat& src) 
{

     vector<Point2f> path_checkpoints;

     //Create a window
     namedWindow("Draw path", CV_WINDOW_AUTOSIZE);
     //show the image
     imshow("Draw path", src);
      //set the callback function for any mouse event
     setMouseCallback("Draw path", CallBackFunc2, (void*)&path_checkpoints);

     // Wait until user press some key
     waitKey(0);
}

回调函数:

//Mouse callback function
void CallBackFunc2(int event, int x, int y, int flags, void* ptr)
{
    Point2f *p = (Point2f*)ptr;
    static int i = 0;

    while(waitKey(10) != 32) 
    {
        if  ( event == EVENT_LBUTTONDOWN ) //Accept new points until space is pressed
        {
                p.push_back(Point(x,y));

                cout << "Left button of the mouse is clicked - position (" << x << ", " << y << ")" << endl;
        }
    }
    destroyWindow("Draw path");
}

我得到的错误就在这一行:

p.push_back(Point(x,y));

“表达式必须具有类类型”

我的理解是我不能使用push_back,因为回调函数只传递了一个点,而不是整个向量。是否可以将点向量传递给回调函数?

1 个答案:

答案 0 :(得分:4)

ptr指的是vector<Point2f>不是 Point2f,您应该将其投放到vector<Point2f> *

vector<Point2f> *p = static_cast<vector<Point2f> *>(ptr);

p是指针,因此您必须取消引用才能访问vector<Point2f>成员:

p->push_back(Point2f(x,y))