c++opencvvoid-pointerstrackbar

How to pass user data using OpenCV trackbar


Currently I have a number of sliders that are used to change image values. I am using the OpenCV track bar for the slider which has a callback to a different function for each of my sliders. I would like to have my sliders callback point to a single callback function and then use the user data to identify which track bar made the call.

Here is the documentation for the track bar

I am unsure what values i should be passing to void*, and also how to then retrieve this value form my callback function Below is an example of my track bar which compiles.

int ref = 1;
createTrackbar("Name","Window",0, 1, myFunc, &ref);

In my callback function I try and retrieve the value of ref.

void myFunc(int value, void *userdata)
{
    int val = *((int*)&userdata);
    cout << val << endl;
}

I had issues trying to convert the pointer back to an int, this is a solution i found online which gives me val as the address of ref.

int val = *((int*)&userdata);

This seems a lot of hassle, as i then have to get the value back form the address at val. Is there an easier way to do this?


Solution

  • No, there is no simplier way. It's nessesary minimum for functionality you want.