Last active
December 19, 2020 17:25
-
-
Save acarabott/39ec44eddd8df48fd8a34aaa1481ee27 to your computer and use it in GitHub Desktop.
using c++11 lambdas with opencv 3 trackbar callbacks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <functional> | |
using TrackbarAction = std::function<void(int)>; | |
cv::namedWindow("win"); | |
cv::TrackbarCallback trackbarCallback = [] (int pos, void* userdata) { | |
(*(TrackbarAction*)userdata)(pos); | |
}; | |
TrackbarAction action1 = [&](int pos) { | |
std::cout << "trackbar 1 action" << std::endl; | |
}; | |
cv::createTrackbar("trackbar 1", "win", &pos, posMax, trackbarCallback, (void*)&action1); | |
TrackbarAction action2 = [&](int pos) { | |
std::cout << "trackbar 2 action" << std::endl; | |
}; | |
cv::createTrackbar("trackbar 2", "win", &pos, posMax, trackbarCallback, (void*)&action2); |
It doesn't work if lambda takes some context from locally visible namespace e.g.:
Mat src; cv::TrackbarCallback doWholeMagicWrapper = [&src](int, void*){ do_something_here_with_src(src) };
gives compilation error:
error: cannot convert ‘main(int, char**)::<lambda(int, void*)>’ to ‘cv::TrackbarCallback {aka void (*)(int, void*)}’ in initialization cv::TrackbarCallback doWholeMagicWrapper = [&src](int, void*){};
Do you have any idea hot to go with it?
Use std::tuple
and pass the data as void pointer. Example usage
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It doesn't work if lambda takes some context from locally visible namespace e.g.:
gives compilation error:
Do you have any idea hot to go with it?