0
votes

I am new to C++ and OpenCV. Currently I am studying the chapter about User Interface which includes waitKey function and setMouseCallBack function. I am curious why setMouseCallBack does not need a loop for multiple mouse events, while waitKey needs a loop for multiple keyboard inputs. The codes written below are the sample codes from the book.

If the first code does not have the while loop, then only the first keyboard input will be read and the code finishes.

#include "opencv2/opencv.hpp"
#include <iostream>

using namespace cv;
using namespace std;

int main(void)
{
    Mat img = imread("D://alpaca.jpg");

    if (img.empty()) {
        printf("Image load failed");
        return -1;
    }

    namedWindow("Alpaca", WINDOW_NORMAL);
    imshow("Alpaca", img);

    while (1) {
        int keycode = waitKey();

        if (keycode == 'i' || keycode == 'I') {
            img = ~img;
            imshow("Alpaca", img);
        }
        else if (keycode == 'q' || keycode == 'Q' || keycode == 27) {
            break;
        }
    }
    return 0;
}

However, in the second code, each mouse event calls on_mouse function without any loop.

#include "opencv2/opencv.hpp"
#include <iostream>

using namespace cv;
using namespace std;

Mat img;
Point pt0ld;

void on_mouse(int event, int x, int y, int flags, void*)
{

    switch (event) {
    case EVENT_LBUTTONDOWN:
        pt0ld = Point(x, y);
        cout << "Event_LBUTTONDOWN: " << x << "," << y << endl;
        break;
    case EVENT_LBUTTONUP:
        cout << "Event_LBUTTONUP: " << x << "," << y << endl;
        break;
    case EVENT_MOUSEMOVE:
        if (flags & EVENT_FLAG_LBUTTON) {
            line(img, pt0ld, Point(x, y), Scalar(0, 255, 255), 2);
            imshow("img", img);
            pt0ld = Point(x, y);
        }
        break;
    default:
        break;
    }
}

int main(void)
{

    img = imread("D://alpaca.jpg");

    if (img.empty()) {
        printf("Image Load  Failed!");
        return -1;
    }

    namedWindow("img");
    setMouseCallback("img", on_mouse);

    imshow("img", img);
    waitKey();

    return 0;
}
1

1 Answers

1
votes

The difference is that waitKey is a function. You have a direct call to that. In this case the function will block until a key is pressed.

setMouseCallback as the name suggest is used to register a callback function, in this case on_mouse. Someone else will call on_mouse when a mouse event will occur. So you don't need to call the function on_mouse on your own.

The first approach is called polling because you check continuity if something happen.

The second one is event based because when an event will occur, the function will be called.