转载:https://blog.csdn.net/qq_52254197/article/details/115333959
#include <iostream>
#include<opencv2/opencv.hpp>
using namespace cv;
using namespace std;
Mat* img = 0;
void onMouse(int event, int x, int y, int flags, void* param)
{
Mat* im = reinterpret_cast<Mat*>(param);//reinterpret_cast 用于进行各种不同类型的指针之间、
//不同类型的引用之间以及指针和能容纳指针的整数类型之间的转换。转换时,执行的是逐个比特复制的操作。
switch (event)
{
case 1: //鼠标左键按下响应:返回坐标和灰度
std::cout << "at(" << x << "," << y << "), value is:"
<< (int) im->at<uchar>(Point(x, y)) << std::endl;
break;
case 2: //鼠标右键按下响应:输入坐标并返回该坐标的灰度
std::cout << "input(x,y)" << endl;
std::cout << "x =" << endl;
cin >> x;
std::cout << "y =" << endl;
cin >> y;
std::cout << "at(" << x << "," << y << ")value is:"
<< static_cast<int>(im->at<uchar>(cv::Point(x, y))) << std::endl;
break;
}
}
int main()
{
Mat src = imread("E:/picture/y1.bmp");
img = &src;
namedWindow("original image", WINDOW_AUTOSIZE);
setMouseCallback("original image", onMouse, reinterpret_cast<void*> (img));//注册鼠标操作(回调)函数
imshow("original image", src);
waitKey();
return 0;
}
减少代码
#include <iostream>
#include<opencv2\opencv.hpp>
#include<iostream>
using namespace std;
using namespace cv;
Point point;
Mat src;
void on_mouse(int EVENT, int x, int y, int flags, void* userdata);
void on_mouse(int EVENT, int x, int y, int flags, void* userdata)
{
point = Point(x, y);
if (EVENT == 1 ) {
circle(src, point, 8, Scalar(0, 0, 255));
cout << "(" << x << "," << y << ")" << endl;
}
}
int main()
{
namedWindow("【display】");
src = imread("D:/picture/1.png");
setMouseCallback("【display】", on_mouse, 0);
//以40ms刷新显示
while(1)
{
imshow("【display】", src);
waitKey(40);
}
}
指针
#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* m = (Mat*)param;
Point point = Point(x, y);
int value=(int)m->at<uchar>(y,x);
switch (event)
{
case 1: //鼠标左键按下响应:返回坐标和灰度
std::cout << "at(" << x << "," << y << "), value is:"<<value<<endl;
circle(*m, point, 4, Scalar(0, 0, 255));
break;
case 2: //鼠标右键按下响应:输入坐标并返回该坐标的灰度
std::cout << "input(x,y)" << endl;
std::cout << "x =" << endl;
cin >> x;
std::cout << "y =" << endl;
cin >> y;
std::cout << "at(" << x << "," << y << ")value is:" << value <<endl;
break;
}
}
int main()
{
Mat src = imread("E:/picture/y1.bmp");
Mat* img = &src;
namedWindow("original image", WINDOW_AUTOSIZE);
setMouseCallback("original image", onMouse, (void*)img);//注册鼠标操作(回调)函数
while (1)
{
imshow("original image", src);
waitKey(40);
}
return 0;
}