OpenCV 2.3 with VS 2008 - Mouse Events

Necessarily - I'm a beginner. Have a job that includes programming, and I teach myself when I go. Needless to say as a teacher, I often make mistakes and carefully.

Where am I now: I created the "Graph" class, it (surprisingly enough) makes graphs. But now I want to make it so that when I click the mouse I change the schedule. But I cannot force the mouse handler to be a member function of the class.

cv::setMouseCallback(windowName, onMouse, 0); // Set mouse handler to be onMouse 

Does not work with

 cv::setMouseCallback(windowName, Graph::onMouse, 0); 

This gives me a lack of options. Accordingly , I cannot make it a member function. After executing the above answer, it compiles, but my this pointer is nullified. Ugh.

OnMouse looks like this:

 void onMouse(int event, int x, int y,int, void*) { if (event == CV_EVENT_LBUTTONDOWN) { cvMoveWindow("Window", 500, 500); //Just to see if stuff happened } return; } 

I do not need to move the window, I want to change the graph itself, which is stored as the variable cv :: Mat in the Graph object. And I can’t figure out how to do this.

Any help would be appreciated, and I really hope that it was not just gibberish.

+8
c ++ opencv mouseevent
source share
2 answers

Yes, callback functions in C ++ are a joy, aren't they? In fact, you need to give OpenCV a function (and not a class method), as you already learned. However, you can crack this horror using the following technique:

 class MyClass { public: void realOnMouse(int event, int x, int y, int flags) { // Do your real processing here, "this" works fine. } }; // This is a function, not a class method void wrappedOnMouse(int event, int x, int y, int flags, void* ptr) { MyClass* mcPtr = (MyClass*)ptr; if(mcPtr != NULL) mcPtr->realOnMouse(event, x, y, flags); } int main(int argv, char** argc) { // OpenCV setup stuff... MyClass processor; cv::setMouseCallback(windowName, wrappedOnMouse, (void*)&processor); // Main program logic return 0; } 

This last parameter in setMouseCallback is very useful for overcoming some problems that you usually encounter.

+11
source share

You can also use the onMouse method as a static method.

 class Graph { public: static void onMouse(int event, int x, int y, void* param) { //Your code here } //Everything else you may need } 

Now you can call the onMouse method with:

 cv::setMouseCallback(windowName, onMouse, (void*) param); 

The parameter can be NULL or whatever you want to pass as a parameter to the method, but you need to make a cast-type for the desired type.

Hope this was helpful. Bye

+1
source share

All Articles