OpenCV 2.3 with VS 2008 - Mouse Events

前端 未结 2 1935
陌清茗
陌清茗 2021-02-15 14:31

Obligatory - I\'m a newbie. Have a job that involves programming and I\'m teaching myself as I go. Needless to say as a teacher I get things wrong frequently and thoroughly.

相关标签:
2条回答
  • 2021-02-15 14:50

    You can also use the onMouse method as a static method.

    class Graph
    {
    public:
         static void onMouse(int event, int x, int y, void* param)
         {
              //Your code here
         }
    
         //Everything else you may need
    }
    

    Now you should be able to call the onMouse method with:

    cv::setMouseCallback(windowName, onMouse, (void*) param);
    

    The param can be NULL or whatever you want to pass as parameter to the method, but you'll need to make a type-cast to the desired type.

    Hope this was useful. Bye.

    0 讨论(0)
  • Yes callback functions in C++ are a joy, aren't they? You actually have to give OpenCV a function (not a class method) as you've already found out. However, you can hack around this awfulness using the following technique:

    class MyClass
    {
    public:
         void realOnMouse(int event, int x, int y, int flags)
         {
             // Do your real processing here, "this" works fine.
         }
    };
    
    // This is a function, not a class method
    void wrappedOnMouse(int event, int x, int y, int flags, void* ptr)
    {
        MyClass* mcPtr = (MyClass*)ptr;
        if(mcPtr != NULL)
            mcPtr->realOnMouse(event, x, y, flags);
    }
    
    int main(int argv, char** argc)
    {
        // OpenCV setup stuff...
    
        MyClass processor;
        cv::setMouseCallback(windowName, wrappedOnMouse, (void*)&processor);
    
        // Main program logic
    
        return 0;
    }
    

    That last parameter on setMouseCallback is quite useful for overcoming some of the problems you usually encounter like this.

    0 讨论(0)
提交回复
热议问题