OpenCV trackbar callback in C++ class

Wim Vanhenden picture Wim Vanhenden · Dec 26, 2011 · Viewed 12k times · Source

I have a question about how to define the callback for trackbars in OpenCV when working with classes in C++.

When I define my trackbar let's say in the constructor method of my .cpp class how can I define the callback?

I have been trying to work with function pointers but it doesn't work out. I guess I must be doing something very wrong :-)

This is my header file:

class SliderwithImage {

public:
    SliderwithImage(void);
    ~SliderwithImage(void); 

    void sliderCallBack(int pos);
};

This is the implementation file:

#include "SliderwithImage.h"

void SliderwithImage::sliderCallBack(int pos) {


}

SliderwithImage::SliderwithImage(void)  {

    const char* windowName = "window";
    int lowvalue  =1;

    namedWindow(windowName,  CV_GUI_EXPANDED);

    createTrackbar("mytrackbar", windowName, &lowvalue, 255, sliderCallBack);

}

SliderwithImage::~SliderwithImage(void) {

}

Obviously the createTrackbar method does not recognize sliderCallBack... I guess it's a problem of scope. But I am not sure how to solve this?

Any help would be appreciated.

Thank you very much.

Answer

Daniel picture Daniel · May 10, 2012

The callback function must be static or global, but you can pass it a reference to an object you want to operate on (see this post on the OpenCV Users mailing list).

The createTrackbar method has a userdata parameter which is passed to the calling function. In C there is an undocumented cvCreateTrackbar2 method, defined in highgui_c.h, which has the same functionality:

CVAPI(int) cvCreateTrackbar2( const char* trackbar_name, const char* window_name,
    int* value, int count, CvTrackbarCallback2 on_change,
    void* userdata CV_DEFAULT(0));

These methods let you create a class with a static callback function that takes a pointer to an object of that class. You can create the trackbar like so:

cv:createTrackbar("Label", "Window" &variable, MAX_VAL, &MyClass::func, this);

The callback would look something like this:

void MyClass:func(int newValue, void * object) {
    MyClass* myClass = (MyClass*) object;
    // ...do stuff.
}

Note that you don't need to explicitly update the variable yourself as long as you provided a pointer to it when creating the trackbar (as above), but if you need to process it first I suggest you set it explicitly in the callback function.