程序:
#include<opencv2/opencv.hpp>
#include<iostream>
using namespace cv;
using namespace std;
void on_mouse(int event, int x, int y, int flag,void*);
Mat src, img; /*showImg*/
Rect select;
bool select_flag = false;
int i = 1;
int main()
{
src = imread("E:/pictures/12.jpg");
namedWindow("input", WINDOW_AUTOSIZE);
imshow("input", src);
img = src.clone();//保持原图
setMouseCallback("input", on_mouse, 0);
waitKey(0);
return 0;
}
//利用鼠标画矩形
void on_mouse(int event, int x, int y, int flag, void*)
{
Point p1, p2;
if (x<0 || x>src.cols || y<0 || y>src.rows)
{
return;
}
if (event == EVENT_LBUTTONDOWN)
{
select.x = x;
select.y = y;
select_flag = true;
}
else if (event == EVENT_MOUSEMOVE&&select_flag)
{
img.copyTo(src);//不断把原图复制到src
p1 = Point(select.x, select.y);
p2 = Point(x, y);
rectangle(src, p1, p2, Scalar(0, 0, 255), 5, 8);
}
else if (select_flag&&event == EVENT_LBUTTONUP)
{
select_flag = false;
//提取感兴趣区域
Rect rect = Rect(Point(select.x, select.y), Point(x, y));
cout << rect.width << "and" <<rect.height<< endl;
if (rect.width&&rect.height)
{
Mat roi = img(rect);
imshow("output", roi);
String finlename = format("E:/%d.jpg", i);
imwrite(finlename, roi);//保存在E盘
i++;
}
}
imshow("input", src);
}
截图: