#include <iostream>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
Mat image;
Rect xx;
bool draw_or_not=0;
RNG g_rng(12345);
void mouse_on(int event,int x,int y,int ,void*);
void draw_rect(Mat & im,Rect &rec);
int main()
{
image = imread("女神.jpg");
xx = Rect(-1,-1,0,0);
namedWindow("效果窗口");
setMouseCallback("效果窗口",mouse_on);
while (1)
{
imshow("效果窗口",image);
int c = waitKey(20);
if (c == 27)
break;
}
waitKey(0);
return 1;
}
void mouse_on(int event, int x, int y, int, void*)
{
if (event == EVENT_LBUTTONDOWN)
{
draw_or_not = 1;
xx.x = x;
xx.y = y;
}
if (draw_or_not==1&&event == EVENT_MOUSEMOVE)
{
xx.width = x - xx.x;
xx.height = y - xx.y;
}
if (draw_or_not == 1 && event == CV_EVENT_LBUTTONUP)
{
draw_or_not = 0;
if (xx.width < 0)
{
xx.x = xx.x + xx.width;
xx.width = -xx.width;
}
if (xx.height < 0)
{
xx.y = xx.y + xx.height;
xx.height *= -1;
}
draw_rect(image, xx);
}
}
void draw_rect(Mat& im, Rect& rec)
{
rectangle(im,rec,Scalar(g_rng.uniform(0,255), g_rng.uniform(0, 255), g_rng.uniform(0, 255)));
}
