/* Region of Interest in an Image */
/*
auther:Miracle
date:二〇一六年 农历二月廿八
content:设置图片的感兴趣区域(鼠标)
*/
//该程序使用鼠标自定义感兴趣区域。
#include<iostream>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
using namespace std;
using namespace cv;
Mat src;
char* window_name = "Region of Interest";
bool ldown = false, lup = false;//点击行为
Point corner1, corner2;//开始点---结束点
Rect box;//ROI
static void mouse_callback(int event, int x, int y, int, void*)
{
//点击鼠标左键
if (event == EVENT_LBUTTONDOWN)
{
ldown = true;
corner1.x = x;
corner1.y = y;
cout << "corner1 recorded at" << corner1 << endl;
}
//释放鼠标左键
if (event == EVENT_LBUTTONUP)
{
if (abs(x - corner1.x) > 20 && abs(y - corner1.y) > 20)
{
lup = true;
corner2.x = x;
corner2.y = y;
cout << "corner2 recorded at" << corner2 << endl;
}
else
{
ldown = false;
cout << "Please Select a bigger region! " << endl;
}
}
if (ldown == true && lup == false)
{
Point pt;
pt.x = x;
pt.y = y;
Mat local_img = src.clone();
rectangle(local_img, corner1, pt, Scalar(0, 0, 255));
imshow(window_name, local_img);
}
//重新自定义
if (ldown == true && lup == true)
{
box.width = abs(corner1.x - corner2.x);
box.height = abs(corner1.y - corner2.y);
box.x = min(corner1.x, corner2.x);
box.y = min(corner1.y, corner2.y);
Mat crop(src, box);
imshow("Crop", crop);
ldown = false;
lup = false;
}
}
int main()
{
src = imread("跑跑卡丁车.jpg");
namedWindow(window_name);
imshow(window_name, src);
setMouseCallback(window_name, mouse_callback);
while ((char)waitKey(0) != 'q');
return 0;
}
<img src="https://img-blog.csdn.net/20160405212555207?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="" />