opencv 鼠标交互
最近在系统的学习opencv的基础知识; 之前没有去系统学习opencv基础,在用opencv的的时候会经常遇到各种问题,很有必要系统学习基础; 好的基础会让后面的学习 和实践 更加顺利;
下面贴出 opencv 鼠标交互的 代码
#include <opencv2/opencv.hpp>
using namespace cv;
#define WINDONWNAME "画矩形"
void onMouse(int event, int x, int y, int flag, void* );
void DrawRectangle(Mat& img, Rect box);
Rect g_rectangle;
Point ptOrigin;
bool g_bDrawingBox = false;
Mat frame;
int main(int argc, char* argv[])
{
char ch;
VideoCapture cam(0);
if (!cam.isOpened())
{
return -1;
}
namedWindow(WINDONWNAME);
setMouseCallback(WINDONWNAME, onMouse, 0);
while (1)
{
cam>>frame;
DrawRectangle(frame, g_rectangle);
imshow(WINDONWNAME, frame);
ch = waitKey(10);
if (ch == 27)
{
return -1;
}
}
return 0;
}
void onMouse(int event, int x, int y, int flag, void* pagram)
{
switch (event)
{
case EVENT_LBUTTONDOWN:
{
g_bDrawingBox = true;
ptOrigin = Point(x, y);
g_rectangle = Rect(x, y, 0, 0);
break;
}
case EVENT_LBUTTONUP:
{
g_bDrawingBox = false;
break;
}
case EVENT_MOUSEMOVE:
{
if (g_bDrawingBox == true)
{
g_rectangle.x = MIN(ptOrigin.x, x);
g_rectangle.y = MIN(ptOrigin.y, y);
g_rectangle.width = abs(x - ptOrigin.x);
g_rectangle.height = abs(y - ptOrigin.y);
}
}
default:
break;
}
}
void DrawRectangle(Mat& img, Rect Box)
{
rectangle(img, g_rectangle, Scalar(255, 0, 0), 3, 8, 0);
}
posted on 2016-03-21 00:59 计算机视觉&机器视觉 阅读(1034) 评论(0) 编辑 收藏 举报