opencv入门学习基础教程(-第12节-鼠标操作)
鼠标操作也是通过回调函数的方式来实现鼠标操作设置回调函数的函数,相当于创建11节中的滑动条函数。定义如下
Void setMouseCallback(“窗口名”,MouseCallback onMouse, void* userdata = 0)
onMOuse为回调函数指针,实际上就是回调函数名
userdata默认为0
回调函数定义如下:
Void Foo(int event,int x,int y,ing flags,void *param)
event 表示事件,是一些宏定义的选择,例如:EVENT_LBUTTONDOWN(鼠标左键按下);EVENT_MOUSEMOVE(鼠标移动);EVENT_LBUTTONUP(鼠标左键抬起)
(x,y)表示鼠标所在的图像中的坐标,而不是窗口中的坐标。flags是EVENT_FLAG的组合
param是userdata
案例:
#include <opencv2/opencv.hpp>
#include "opencv2/highgui/highgui.hpp"
using namespace cv;
#define WINDOW_NAME "程序窗口"
void on_MouseHandle(int event,int x,int y,int flags,void*param);
void DrawRectangle( Mat &img , Rect box);
void ShowHelpText();
Rect g_rectangle;
bool g_bDrawingBox=false;
RNG g_rng(12345);
int main( int argc, char** argv)
{
g_rectangle=Rect(-1,-1,0,0);
Mat srcImage(600,800,CV_8UC3),tempImage;
srcImage.copyTo(tempImage);
g_rectangle=Rect(-1,-1,0,0);
srcImage=Scalar::all(0);
namedWindow(WINDOW_NAME);
setMouseCallback(WINDOW_NAME,on_MouseHandle,(void*)&srcImage);
while(1)
{
srcImage.copyTo(tempImage);
if(g_bDrawingBox) DrawRectangle(tempImage,g_rectangle);
imshow(WINDOW_NAME,tempImage);
if(waitKey(10)==27)break;
}
return 0;
}
void on_MouseHandle(int event,int x, int y,int flags, void*param)
{
Mat &image=*(cv::Mat*)param;
switch(event)
{
case EVENT_MOUSEMOVE://鼠标移动事件
{
if(g_bDrawingBox)
{
g_rectangle.width=x-g_rectangle.x;
g_rectangle.height=y-g_rectangle.y;
}
}
break;
case EVENT_LBUTTONDOWN://左键被按下事件
{
g_bDrawingBox=true;
g_rectangle=Rect(x,y,0,0);
}
break;
case EVENT_LBUTTONUP://左键被抬起事件
{
g_bDrawingBox=false;
if(g_rectangle.width<0)
{
g_rectangle.x =g_rectangle.width;
g_rectangle.width*=-1;
}
if(g_rectangle.height<0)
{
g_rectangle.y =g_rectangle.height;
g_rectangle.height*=-1;
}
DrawRectangle(image,g_rectangle);
}
break;
}
}
void DrawRectangle(cv::Mat &img,cv::Rect box)//调用rectangle()画矩形
{
rectangle(img,box.tl(),box.br(),Scalar(g_rng.uniform(0,255),g_rng.uniform(0,255),g_rng.uniform(0,255)));
}
,
免责声明:本文仅代表文章作者的个人观点,与本站无关。其原创性、真实性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容文字的真实性、完整性和原创性本站不作任何保证或承诺,请读者仅作参考,并自行核实相关内容。文章投诉邮箱:anhduc.ph@yahoo.com