/**
*Copyright (c) 2018 Young Fan.All Right Reserved.
*Filename: 5 鼠标操作
*Author: Young Fan
*Date: 2018.4.6
*OpenCV version: 3.4.1
*IDE: Visual Studio 2017
*Description: 鼠标操作
*/
#include<opencv2/opencv.hpp>
using namespace cv;
#define WINDOW_NAME "程序窗口"
//---------------------【全局函数声明部分】-----------
void on_MouseHandle(int event,int x,int y,int flags,void* parma);
void DrawRectangle(cv::Mat &img,cv::Rect box);
//----------------------【全局变量声明】---------------
Rect g_rectangle;
bool g_bDrawingBox = false;//是否进行绘制,标志符
RNG g_rng(12345);
int main(int argc,char** argv)
{
//1.准备参数
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);
//2.设置鼠标操作回调函数
namedWindow(WINDOW_NAME);
setMouseCallback(WINDOW_NAME,on_MouseHandle,(void*) &srcImage);
//3.程序主循环,当进行绘制的标识为真时,进行绘制
while (1)
{
srcImage.copyTo(tempImage);//复制原图到临时变量
if (g_bDrawingBox)
DrawRectangle(tempImage, g_rectangle);//当标志符为真时,则进行绘制
imshow(WINDOW_NAME, tempImage);
if (waitKey(10) == 27)
break;//按下Esc键,程序退出
}
return 0;
}
//---------------------------【on_MouseHandle()函数】----------------------
//描述:鼠标回调函数,根据不同的鼠标事件进行不同的操作
//-------------------------------------------------------------------------
void on_MouseHandle(int event, int x, int y, int flags, void* parma)
{
Mat &image = *(cv::Mat*) parma;
switch (event)
{
//鼠标移动消息
case EVENT_MOUSEMOVE:
{
if (g_bDrawingBox) //如果绘制标志符为真,则记录下长和宽到RECT型变量中
{
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);//记录起始点
printf("左键按下了\n");
}
break;
//左键抬起消息
case EVENT_LBUTTONUP:
{
g_bDrawingBox = false;//置标志符为false
printf("左键抬起了\n");
//对宽和高小于0的处理
if (g_rectangle.width < 0)
{
g_rectangle.x += g_rectangle.width;
g_rectangle.width *= -1;//a *= b,即a = a*b;
}
if (g_rectangle.height < 0)
{
g_rectangle.y += g_rectangle.height;
g_rectangle.height *= -1;//a *= b,即a = a*b;
}
//调用函数进行绘制
DrawRectangle(image,g_rectangle);
}
break;
}
}
//-------------------------【DrawRectangle()函数】-----------------
//描述:自定义的矩形绘制函数
//-----------------------------------------------------------------
void DrawRectangle(cv::Mat &img, cv::Rect box)
{
rectangle(img,box.tl(),box.br(),Scalar(g_rng.uniform(0,255),
g_rng.uniform(0,255),g_rng.uniform(0,255)));//随机颜色
}
3.5 鼠标操作
最新推荐文章于 2020-07-25 23:13:04 发布