Skip to content

Instantly share code, notes, and snippets.

@acarabott
Last active January 17, 2017 18:06
Show Gist options
  • Save acarabott/ef1d12bc093db82f0e3a15fcbfccb452 to your computer and use it in GitHub Desktop.
Save acarabott/ef1d12bc093db82f0e3a15fcbfccb452 to your computer and use it in GitHub Desktop.
opencv mouse callback with c++11 lambda and capture
/*
if you don't need to do any captures you can just do
cv::setMouseCallback("win", [] (int event, int x, int y, int flags, void*userdata) {
std::cout << "mouse action!" << std::endl;
});
but if you need to do any captures, then you'll need to do this crap.
If you know of a better way then fork away...
*/
using MouseAction = std::function<void(int, int, int, int)>;
void setMouseAction(const std::string& winName, const MouseAction& action)
{
cv::setMouseCallback(winName,
[] (int event, int x, int y, int flags, void* userdata) {
(*(MouseAction*)userdata)(event, x, y, flags);
}, (void*)&action);
}
void userCode()
{
cv::namedWindow("win");
setMouseAction("win", [&] (int event, int x, int y, int flags) {
std::cout << "mouse action!" << std::endl;
});
}
@acarabott
Copy link
Author

this seems to crash in unpredictable ways...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment