opencv 鼠标交互
Posted LinuxC++计算机视觉
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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);
}
以上是关于opencv 鼠标交互的主要内容,如果未能解决你的问题,请参考以下文章
OpenCV 例程200篇217. 鼠标交互获取多边形区域(ROI)
youcans 的 OpenCV 例程200篇184.鼠标交互标记的分水岭算法