1.目的:鼠标绘制矩形
2.关键API介绍:setMouseCallback,为指定窗口设定鼠标回调函数
rectangle矩形绘制
3.main函数
Rect rect_angle = Rect(0, 0, 0, 0);
Mat src(600, 800, CV_8UC3);
Mat temple;
src = Scalar::all(0);
namedWindow(namewindow);
setMouseCallback(namewindow, onMousle, (void*)&src);
while (1)
{
src.copyTo(temple);
if (drawingbox)
{
DrawRectangle(temple, rect_angle);
}
imshow(namewindow, temple);
if (waitKey(10) == 27)break;
}
return 0;
}
其中onMouse为鼠标回调函数
4.关键点
在onMouse函数中各鼠标移动、鼠标左击时、鼠标左击后的设定
另需考虑当鼠标从右向左移动时rect_tangle.width/rect_tangle.height为负的情况。
颜色通过rng产生随机数
onmouse函数
void onMousle(int event, int x, int y, int flags, void* userdata)
{
Mat&image = *(Mat*)userdata;
switch (event)
{
case EVENT_MOUSEMOVE:
{
if (drawingbox)
{
rect_angle.width = x - rect_angle.x;
rect_angle.height = y - rect_angle.y;
}
}
break;
case EVENT_LBUTTONDOWN:
{
drawingbox = true;
rect_angle = Rect(x, y, 0, 0);
}
break;
case EVENT_LBUTTONUP:
{
drawingbox = false;
if (rect_angle.width < 0)
{
rect_angle.x += rect_angle.width;
rect_angle.width *= -1;
}
if (rect_angle.height < 0)
{
rect_angle.y+= rect_angle.height;
rect_angle.height *= -1;
}
DrawRectangle(image, rect_angle);
}
break;
}
}
绘制图像函数
void DrawRectangle(Mat& image,Rect box)
{
rectangle(image, box.tl(), box.br(), Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)));
}
5.结果展示
总体代码
#include
#include
#define namewindow "窗口名字"
using namespace cv;
using namespace std;
Rect rect_angle;
bool drawingbox=false;
RNG rng;
void onMousle(int event, int x, int y, int flags, void* userdata);
void DrawRectangle(Mat& image, Rect box);
int main()
{
Rect rect_angle = Rect(0, 0, 0, 0);
Mat src(600, 800, CV_8UC3);
Mat temple;
src = Scalar::all(0);
namedWindow(namewindow);
setMouseCallback(namewindow, onMousle, (void*)&src);
while (1)
{
src.copyTo(temple);
if (drawingbox)
{
DrawRectangle(temple, rect_angle);
}
imshow(namewindow, temple);
if (waitKey(10) == 27)break;
}
return 0;
}
void onMousle(int event, int x, int y, int flags, void* userdata)
{
Mat&image = *(Mat*)userdata;
switch (event)
{
case EVENT_MOUSEMOVE:
{
if (drawingbox)
{
rect_angle.width = x - rect_angle.x;
rect_angle.height = y - rect_angle.y;
}
}
break;
case EVENT_LBUTTONDOWN:
{
drawingbox = true;
rect_angle = Rect(x, y, 0, 0);
}
break;
case EVENT_LBUTTONUP:
{
drawingbox = false;
if (rect_angle.width < 0)
{
rect_angle.x += rect_angle.width;
rect_angle.width *= -1;
}
if (rect_angle.height < 0)
{
rect_angle.y+= rect_angle.height;
rect_angle.height *= -1;
}
DrawRectangle(image, rect_angle);
}
break;
}
}
void DrawRectangle(Mat& image,Rect box)
{
rectangle(image, box.tl(), box.br(), Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)));
}