Mouse Events เป็นหนึ่งในคุณสมบัติที่มีประโยชน์ที่สุดของ OpenCV ใน OpenCV เราสามารถติดตามตำแหน่งของตัวชี้เมาส์และติดตามการคลิก (คลิกขวา ซ้าย และคลิกกลาง) OpenCV มีการใช้งานอย่างกว้างขวางในด้านวิทยาการหุ่นยนต์และคอมพิวเตอร์วิทัศน์ มักใช้ตัวชี้และคลิกเมาส์สำหรับติดตามการมองเห็นในวิทยาการหุ่นยนต์และคอมพิวเตอร์
ที่นี่เราจะเข้าใจวิธีการติดตามตำแหน่งของตัวชี้เมาส์บนรูปภาพและติดตามการคลิก
โปรแกรมต่อไปนี้สาธิตวิธีการติดตามตำแหน่งของตัวชี้เมาส์และการคลิก
ตัวอย่าง
#include<iostream>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
using namespace std;
using namespace cv;
void locator(int event, int x, int y, int flags, void* userdata){ //function to track mouse movement and click//
if (event == EVENT_LBUTTONDOWN){ //when left button clicked//
cout << "Left click has been made, Position:(" << x << "," << y << ")" << endl;
} else if (event == EVENT_RBUTTONDOWN){ //when right button clicked//
cout << "Rightclick has been made, Position:(" << x << "," << y << ")" << endl;
} else if (event == EVENT_MBUTTONDOWN){ //when middle button clicked//
cout << "Middleclick has been made, Position:(" << x << "," << y << ")" << endl;
} else if (event == EVENT_MOUSEMOVE){ //when mouse pointer moves//
cout << "Current mouse position:(" << x << "," << y << ")" << endl;
}
}
int main() {
Mat image = imread("bright.jpg");//loading image in the matrix//
namedWindow("Track");//declaring window to show image//
setMouseCallback("Track", locator, NULL);//Mouse callback function on define window//
imshow("Track", image);//showing image on the window//
waitKey(0);//wait for keystroke//
return 0;
} ผลลัพธ์

