// ConsoleApplication5.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<opencv2\highgui\highgui.hpp>
#include<opencv\cv.h>
#include<opencv2\core\core.hpp>
#include<opencv2\opencv.hpp>
#include "opencv2/imgproc/imgproc.hpp"
#include<iostream>
#include "imgproc/imgproc.hpp"
using namespace cv;
using namespace std;
void on_MouseHandle(int evev, int x, int y, int flags, void* param);
void DrawRectangle(Mat& img, Rect box);
bool g_bDrawingBox = false;
Rect g_rectangle;
int main()
{
string name = "原图";
Mat qq = imread("D:\\test11.jpg");
Mat qq1,qq2;
namedWindow(name);
setMouseCallback(name, on_MouseHandle, (void*)&qq);//鼠标回调函数
while (1)
{
qq.copyTo(qq1);//复制源图到临时变量
if (g_bDrawingBox)//如果进行绘制的标识符为真时,则进行绘制
{
DrawRectangle(qq1, g_rectangle);
qq2.create(g_rectangle.size(), qq.type());//分割出图像
qq(g_rectangle).copyTo(qq2);
}
imshow(name, qq1);
if (qq2.cols!=0)
{
imshow("QQ2", qq2);
qq2.cols = 0;
}
if (waitKey(10) == 27)
break;//按下ESC键程序退出 }
}
waitKey(0);
return 0;
}
void on_MouseHandle(int event, int x, int y, int flags, void* param)
{
Mat& image = *(Mat*)param; switch (event)
{ //鼠标移动消息
case EVENT_MOUSEMOVE:
{ if (g_bDrawingBox)//如果是否进行绘制的标识符为真,则记录下长和框到Rect类型变量中
{ g_rectangle.width = x - g_rectangle.x;
g_rectangle.height = y - g_rectangle.y;
}
}
break; //左键按下消息
case EVENT_LBUTTONDOWN:
{
g_bDrawingBox = true;
g_rectangle = Rect(x, y, 0, 0); }
break; //左键抬起消息
case EVENT_LBUTTONUP:
{
g_bDrawingBox = false;//置标识符为false //对宽和高小于0的处理
if (g_rectangle.width < 0)
{
g_rectangle.x += g_rectangle.width;
g_rectangle.width *= -1;
}
if (g_rectangle.height < 0)
{
g_rectangle.y += g_rectangle.height;
g_rectangle.height *= -1;
} //调用函数进行绘制
DrawRectangle(image, g_rectangle);
}
break;
}
}
void DrawRectangle(Mat& img, Rect box)
{
rectangle(img, box.tl(), box.br(), Scalar(0,255,255));
}