opencv鼠标操作

转载: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;	
}
	

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值