Having trouble creating a class based implementation of OpenCV's mouseCallback function

后端 未结 2 1475
遥遥无期
遥遥无期 2021-02-09 23:11

As the title suggest, I\'m having some trouble implementing OpenCV\'s mouseCallback function in a class based C++ structure. Allow me to explain. I have defined a class called B

相关标签:
2条回答
  • 2021-02-10 00:05

    I was using this method too, however I realized that the static helper class was quite rigid and type and method bound.

    Just for further reference I've defined a templated free function that looks like:

    template<typename TClass, void (TClass::*MouseClickType)(int, int, int, int)>
    void FreeOnMouseCallback(int event, int x, int y, int flags, void* ptr)
    {
        auto* mcPtr = static_cast<TClass*>(ptr);
        if(mcPtr != NULL)
        {
          (mcPtr->*MouseClickType)(event, x, y, flags);
        }
    }
    

    And I can now call arbitrary functions (matching the signature, but not the name) inside classes with

     cv::setMouseCallback( WindowName, FreeOnMouseCallback<Calibrator, &Calibrator::OnMouseCallback>, this );
    

    It might be extended if the void* ptr is also required, but I've omitted it here.

    0 讨论(0)
  • 2021-02-10 00:16

    Since a member function takes a this pointer, you will need a static wrapper function. Typically, you use the param parameter to be the address of the object that the member function belongs to, so you end up with something like this:

    ...
    static void mouseCallback(int event, int x, int y, int flags, void *param);
    
    void doMouseCallback(int event, int x, int y, int flags);
    

    And then inside the mouseCallback:

    void BriskMatching::mouseCallback(int event, int x, int y, int flags, void *param)
    {
        BriskMatching *self = static_cast<BriskMatching*>(param);
        self->doMouseCallback(event, x, y, flags);
    }
    
    0 讨论(0)
提交回复
热议问题