Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

วิธีใช้ Mouse Events ใน OpenCV ด้วย C++


ภาพรวม

Mouse Events เป็นฟีเจอร์สำคัญของ OpenCV ใช้ติดตามตำแหน่งเมาส์ และการคลิก (Left, Right, Middle) ใช้กันอย่างแพร่หลายใน Robotics และ Computer Vision

Callback Function

ใช้ setMouseCallback(windowName, callback, userdata) ลงทะเบียนฟังก์ชัน Callback

Signature: void callback(int event, int x, int y, int flags, void* userdata)

Event Types

  • EVENT_MOUSEMOVE - เมาส์เคลื่อนที่
  • EVENT_LBUTTONDOWN - คลิกซ้าย
  • EVENT_RBUTTONDOWN - คลิกขวา
  • EVENT_MBUTTONDOWN - คลิกกลาง
  • อื่นๆ: LBUTTONUP, RBUTTONUP, LBUTTONDBLCLK, etc.

โค้ดตัวอย่าง C++

#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) {
    if (event == EVENT_LBUTTONDOWN)
        cout << "Left click at (" << x << "," << y << ")" << endl;
    else if (event == EVENT_RBUTTONDOWN)
        cout << "Right click at (" << x << "," << y << ")" << endl;
    else if (event == EVENT_MBUTTONDOWN)
        cout << "Middle click at (" << x << "," << y << ")" << endl;
    else if (event == EVENT_MOUSEMOVE)
        cout << "Mouse position: (" << x << "," << y << ")" << endl;
}

int main() {
    Mat image = imread("bright.jpg");
    namedWindow("Track");
    setMouseCallback("Track", locator, NULL);
    imshow("Track", image);
    waitKey(0);
    return 0;
}

ผลลัพธ์

แสดงภาพ และพิมพ์ Event เมาส์ทุกครั้งใน Console (ตำแหน่ง และประเภท Event)

วิธีใช้ Mouse Events ใน OpenCV ด้วย C++
วิธีใช้ Mouse Events ใน OpenCV ด้วย C++