code:
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
void onMouse(int event,int x,int y,int flags,void* param)
{
Mat* im = reinterpret_cast<Mat*>(param);
switch(event)
{
case EVENT_LBUTTONDOWN:
//左键按下显示像素值
if (static_cast<int>(im->channels())==1)
{
//若为灰度图,显示鼠标点击的坐标以及灰度值
cout<<"at("<<x<<","<<y<<")value is:"<<static_cast<int>(im->at<uchar>(x,y))<<endl;
}
else if (static_cast<int>(im->channels() == 3))
{
//若图像为彩色图像,则显示鼠标点击坐标以及对应的B, G, R值
cout << "at (" << x << ", " << y << ")"
<< " B value is: " << static_cast<int>(im->at<Vec3b>(x, y)[0])
<< " G value is: " << static_cast<int>(im->at<Vec3b>(x, y)[1])
<< " R value is: " << static_cast<int>(im->at<Vec3b>(x, y)[2])
<< endl;
}
}
}
int main()
{
Mat img = imread("demo1.jpg");
imshow("image",img);
setMouseCallback("image",onMouse,reinterpret_cast<void*>(&img));//鼠标响应函数
waitKey(0);
return 0;
}
运行效果: