OpenCV鼠標響應函數(setMouseCallback)


此處給出OpenCV中的鼠標回調函數,實現功能:將鼠標左鍵點擊處的圖像像素值顯示在終端。

/*
    void setMousecallback(const string& winname, MouseCallback onMouse, void* userdata=0)
    winname:窗口名
    onMouse:鼠標響應函數,原型:void on_Mouse(int event, int x, int y, int flags, void* param);
    userdata:可認為是傳給回調函數的參數
*/
#include <iostream>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

using namespace std;
using namespace cv;
const char* windows_name = "onMouseCallback";

void on_Mouse(int event, int x, int y, int flags, void* param);

int main(int argc, char* argv[])
{
    Mat src = imread("imgA.png",-1);
    if (src.empty())
    {
        cout << "The image is empty, please check it!" << endl;
        return -1;
    }
    namedWindow(windows_name);
    setMouseCallback(windows_name, on_Mouse,(void*)&src); //類型轉換
    imshow(windows_name, src);
    
    waitKey();
    return 0;
}
void on_Mouse(int event, int x, int y, int flags, void* param) {
    Mat depth_img = *(Mat*)param; // 先轉換類型,再取數據
    Vec3b depth;    // 初始化不可放在case內

    // 一般包含如下3個事件
    switch (event)
    {
    case EVENT_MOUSEMOVE:
        //cout << "Please select one point:" << endl;
        break;
    case EVENT_LBUTTONDOWN: // 鼠標左鍵按下
        depth = depth_img.at<Vec3b>(x, y);
        cout << "Position: (" << x << "," << y
            << ")—— depth = " << depth << endl;
        break;
    case EVENT_LBUTTONUP: // 鼠標左鍵釋放
        cout << "buttonup" << endl;
        break;
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM