首页 > 代码库 > opencv学习之路(5)、鼠标和滑动条操作

opencv学习之路(5)、鼠标和滑动条操作

一、鼠标事件

技术分享

 1 #include<opencv2/opencv.hpp>
 2 #include<iostream>
 3 using namespace cv;
 4 using namespace std;
 5 
 6 Mat img(500,500,CV_8UC3,Scalar(255,255,255));//定义成全局变量
 7 
 8 void onm ouse(int event,int x,int y,int flags,void* param){
 9     if(event==CV_EVENT_LBUTTONDOWN){//如果鼠标左键按下
10         cout<<"mouse down"<<endl;//控制台输出
11         circle(img,Point(x,y),80,Scalar(255,255,0),2,8);//在全局变量img上画圆
12     }
13 }
14 
15 void main(){
16     namedWindow("mouse",CV_WINDOW_AUTOSIZE);
17     setMouseCallback("mouse",OnMouse,0);
18     while(1){
19         imshow("mouse",img);
20         if(27==waitKey(10))//每隔10毫秒检测是否按下esc键
21             break;
22     }
23 }

技术分享

另外一种方法,不必将img图像设置为全局变量,只需传入其地址即可。

 1 #include<opencv2/opencv.hpp>
 2 #include<iostream>
 3 using namespace cv;
 4 using namespace std;
 5 
 6 Point pt;
 7 void onm ouse(int event,int x,int y,int flags,void* param){
 8     Mat img=*(Mat*)param;//将param强制转换为Mat指针,*(Mat*)=Mat,就如*(int*)=int一样
 9     switch(event){
10         case CV_EVENT_LBUTTONDOWN://鼠标左键按下时
11             pt.x=x;
12             pt.y=y;
13             break;
14         case CV_EVENT_LBUTTONUP://鼠标左键抬起时
15             rectangle(img,pt,Point(x,y),Scalar(0,255,0),2,8);
16             break;
17         default:
18             break;
19     }
20 }
21 
22 void main(){
23     Mat img(500,500,CV_8UC3,Scalar(255,255,255));
24     namedWindow("mouse",CV_WINDOW_AUTOSIZE);
25     setMouseCallback("mouse",OnMouse,&img);//传入img的地址,这样就不必将img设置成全局变量了
26 
27     while(1){
28         imshow("mouse",img);
29         if(27==waitKey(10))//每隔10毫秒检测是否按下esc键
30             break;
31     }
32 }

技术分享

二、滑动条操作

技术分享

 1 #include<opencv2/opencv.hpp>
 2 #include<iostream>
 3 using namespace cv;
 4 using namespace std;
 5 
 6 Mat dst;
 7 int value=http://www.mamicode.com/20;
 8 
 9 void onChange(int,void* param){
10     Mat src=http://www.mamicode.com/*(Mat*)param;
11     threshold(src,dst,value,255,THRESH_BINARY);//二值化
12     //Canny(src,dst,value,255);//canny边缘检测
13     imshow("TrackBar",dst);
14 }
15 
16 void main(){
17     Mat src=http://www.mamicode.com/imread("1.jpg",0);//读入灰度图
18     namedWindow("TrackBar",CV_WINDOW_AUTOSIZE);
19     createTrackbar("Threshold","TrackBar",&value,255,onChange,&src);
20 
21     threshold(src,dst,value,255,THRESH_BINARY);
22     //Canny(src,dst,value,255);
23     imshow("TrackBar",dst);//  21/22/23这三行代码如果去掉的话,在未调整滑动条的情况下,不会有画面显示
24 
25     waitKey(0);
26 }

技术分享

opencv学习之路(5)、鼠标和滑动条操作