Recently in the system of learning OPENCV basic knowledge, before the system to learn OpenCV Foundation, in the use of OPENCV will often encounter a variety of problems, it is necessary to learn the basis of the system, good Foundation will make the study and practice more smoothly;
The following code OPENCV the mouse interaction
#include <opencv2/opencv.hpp>
using namespace CV;
#define WINDONWNAME "Draw a rectangle"
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 Mouse Interaction