使用本代碼可以打印出鼠標所在的坐標和像素大醒揭场(黑白圖片)
使用函數(shù)setMouseCallback帕识,輸入?yún)?shù)1是窗口名字,輸入?yún)?shù)2是調(diào)用的函數(shù)沙咏。
語言是C++币旧,OpenCV版本是3.1.0践险。
#include "opencv2/core.hpp"
#include <opencv2/core/utility.hpp>
#include "opencv2/imgproc.hpp"
#include "opencv2/calib3d.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/videoio.hpp"
#include "opencv2/highgui.hpp"
#include<iostream>
using namespace cv;
using namespace std;
void OnMouseAction(int event,int x,int y,int flags,void *ustc); //鼠標回調(diào)事件函數(shù)
int static times; //記錄調(diào)用次數(shù)
Mat image;
int main(int argc,char*argv[])
{
image=imread("left01.jpg", IMREAD_GRAYSCALE);
imshow("image",image);
setMouseCallback("image",OnMouseAction);
waitKey();
system("pause");
}
//*******************************************************************//
//鼠標回調(diào)函數(shù)
void OnMouseAction(int event,int x,int y,int flags,void *ustc)
{
//cout<<"第 "<<times<<" 次回調(diào)鼠標事件"<<endl;
if(event==CV_EVENT_LBUTTONDOWN)
{
cout<<"觸發(fā)左鍵按下事件"<<endl;
cout<<"location: "<<x<<", "<<y<<endl;
unsigned char* row_ptr = image.ptr<unsigned char> ( y ); // row_ptr是第y行的頭指針
unsigned char* data_ptr = &row_ptr[ x*image.channels() ]; // data_ptr 指向待訪問的像素數(shù)據(jù)
// 輸出該像素的每個通道,如果是灰度圖就只有一個通道
for ( int c = 0; c != image.channels(); c++ )
{
unsigned char data = data_ptr[c]; // data為I(x,y)第c個通道的值
cout << (int)data << endl;
}
}
/*
if(event==CV_EVENT_MOUSEMOVE)
{
cout<<"觸發(fā)鼠標移動事件"<<endl;
}
if(event==CV_EVENT_LBUTTONUP)
{
cout<<"觸發(fā)左鍵抬起事件"<<endl;
}
if(event==CV_EVENT_RBUTTONDOWN)
{
cout<<"觸發(fā)右鍵按下事件"<<endl;
}
if(event==CV_EVENT_RBUTTONUP)
{
cout<<"觸發(fā)右鍵抬起事件"<<endl;
}
if(event==CV_EVENT_LBUTTONDBLCLK)
{
cout<<"觸發(fā)左鍵雙擊事件"<<endl;
}
if(event==CV_EVENT_RBUTTONDBLCLK)
{
cout<<"觸發(fā)右鍵雙擊事件"<<endl;
}*/
}