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;
}