OpenCV Return value from mouse callback function

前端 未结 3 798
忘了有多久
忘了有多久 2021-01-14 06:39

In OpenCV I want to return the point position like Point(x,y) to the main() function that I click on the image in the mouse callback function . Is there anyway other than se

相关标签:
3条回答
  • 2021-01-14 06:48

    to expand Safirs idea there, apart from a class or such, you could just pass in the point itself:

    void on_mouse( int e, int x, int y, int d, void *ptr )
    {
        Point*p = (Point*)ptr;
        p->x = x;
        p->y = y;
    }
    
    Point p;
    namedWindow("win");
    setMouseCallback("win",on_mouse, (void*)(&p) );
    
    // changed value of p will be accessible here 
    
    0 讨论(0)
  • 2021-01-14 06:48

    No, this isn't possible, since the on_mouse() is a callback function. Here is the opencv documentation of it.

    So, "global" variables are the only way to solve this problem. Alternatively, if you're looking for a nicer solution, you can create a wrapper class in which you have the namedWindow and the MouseCallback and a private member variable, which is manipulated when mouse callback function is called.

    0 讨论(0)
  • 2021-01-14 06:50

    You can avoid using global variables by passing a pointer to your data as a parameter to setMouseCallback(). Agree with @berek, just wanted to show a full example below to avoid confusion about global variables.

    using namespace cv; 
    
    void on_mouse( int e, int x, int y, int d, void *ptr )
    {
        Point*p = (Point*)ptr;
        p->x = x;
        p->y = y;
    }
    
    in main() {
        Point p;
        namedWindow("window");
        Mat image = imread("someimage.jpg");
        imshow(image);
    
    
        //pass a pointer to `p` as parameter
        setMouseCallback("window",on_mouse, &p ); 
    
        // p will update with new mouse-click image coordinates 
        // whenever user clicks on the image window 
    }
    
    0 讨论(0)
提交回复
热议问题