#include<opencv2/opencv.hpp>
using namespace cv;
#define WINDOW_NAME "[程序窗口]"
Rect g_rectangle;
bool g_bDrawingBox = false;//是否进行绘制
RNG g_rng(12345);//RNG( )函数的作用为初始化随机数状态的生成器;
void DrawRectangle(cv::Mat &img, cv::Rect box)
{
/*
构造函数 Rect(x,y,width,height),x, y 为左上角坐标, width, height 则为长和宽。
利用对角线两点来画矩形:
void rectangle(Mat& img, Point pt1,Point pt2,const Scalar& color, int thickness=1, int lineType=8, int shift=0)
传入矩形参数来画矩形:
void rectangle(Mat& img, Rect rec, const Scalar& color, int thickness=1, int lineType=8, int shift=0 )
*/
rectangle(img, box.tl(), box.br(),Scalar(g_rng.uniform(0, 255), g_rng.uniform(0, 255), g_rng.uniform(0, 255)));//随机颜色
}
void on_MouseHandle(int event, int x, int y, int flags, void *param)
{
Mat &image = *(cv::Mat*)param;
switch (event)
{
//鼠标移动消息
case EVENT_MOUSEMOVE:
{
//如果是否进行绘制的标识符为真,则记录下长宽到RECT变量中
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;//抬起就不画了
//对于宽或高小于0
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;
default:
break;
}
}
int main()
{
g_rectangle = Rect(-1, -1, 0, 0);//起始位置
Mat srcImage(600, 800, CV_8UC3), tempImage;
/*
使用Mat( )构造函数
Mat M(2,2,CV_8UC3,Scalar(0,0,255));
参数:
1)行数和列数;
2)存储元素的数据类型以及每个矩阵点的通道数;CV_8UC3表示使用8位的unsigned char型,每个元素由三个元素组成三通道。
3)Scalar是个short型的向量,能够用指定的定制化的值来初始化矩阵,还可以用于表示颜色。
*/
srcImage.copyTo(tempImage);//将srcImage拷贝到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)//按esc退出
break;
}
return 0;
}
效果图: