如何给一个回调函数传数据?

在openCV的canny检测中,我想用一个类完成这个事,但是传参的时候出现若干问题


class MyCanny{
private:
    Mat src, src_gray;
    Mat dst, detected_edges; // input and output matrix
    int lowThreshold = 0;
    const int max_lowThreshold = 100;
    const int ratio = 3;
    const int kernel_size = 3;
    const char* window_name = "Edge Map"; // some parameters

public:
    explicit MyCanny(const Mat &img); // 构造函数,用于对类的对象赋值,由于数据是private的,只能通过此种方式赋值
    MyCanny(); // constructor
    Mat get_dst(); // 可以不需要通过static静态就获得dst矩阵
    void canny_process(); // 用于进行主要的CannyEdge处理过程
    void canny_threshold(int pos, void* userdata);
}

然后是函数成员


void MyCanny::canny_process() {

    createTrackbar("Min Threshold:", window_name, &lowThreshold, max_lowThreshold, canny_threshold);
    //(Reference to non-static function member must be called, so I have to make this function static, 
    //but static function can't access data from class)
    canny_threshold(0, nullptr);
    waitKey(0);
}

void MyCanny::canny_threshold(int pos, void *userdata) {
    //(how to send data from class to this function if I made this function static)
    blur(src_gray, detected_edges, Size(3, 3));
    Canny(detected_edges, detected_edges, lowThreshold, lowThreshold * ratio, kernel_size);
    dst = Scalar::all(0);
    src.copyTo(dst, detected_edges);
    imshow(window_name, dst);
}
  • 如果canny_threshold这个函数不是静态static的,createTrackbar的最后一个参数就不能引用
  • 如果它静态了,就没法获得类的数据了

所以我该怎么给他传参?,肯定是通过这个void* userdata了

canny_threshold的第二个参数,把类的this指针传过去就行了。在该函数内能过类指针 访问

类成员作为回调的时候需要是静态函数,详细的解释和解决方法可以看这个
类成员函数作为回调函数的方法及注意点_hanxiucaolss的博客-CSDN博客_类成员函数作为回调函数 编程中遇到一个错误,提示为error C2597: illegal reference to non-static member即因为一个类的静态成员函数调用了类的非静态成员变量,而报错。下面具体介绍一些相关知识点,以防下次再出错。类成员函数当回调函数的方法参考自:https://blog.csdn.net/this_capslock/article/details/1700100... https://blog.csdn.net/hanxiucaolss/article/details/89500738

忘了放源代码了, 链接 https://gitee.com/hazyparker/learn_slam/blob/master/1_OpenCV/mCode/myEdge.cpp

img


关于createTrackbar这个函数,和OpenCV这一部分的源码
OpenCV: Canny Edge Detector https://docs.opencv.org/4.5.2/da/d5c/tutorial_canny_detector.html

这是结题的总结:
写文章-CSDN博客 https://editor.csdn.net/md/?articleId=120182595