详情:Opencv函数setMouseCallback鼠标事件响应
1.设置MouseCallback函数,函数名可随意,但是参数要与MouseCallback的一致。
2.setMouseCallback()
可以先提取出矩形的区域,再利用mask提取圆形的区域。
#include
#include
#include
#include
using namespace cv;
using namespace std;
Point startp(-1, -1);
Point endp(-1, -1);
//绘制圆,需要中心坐标和半径
Point centerp(-1, -1);
int radius = 0;
Mat temp;
void MouseDraw(int event,int x,int y,int flag,void* usedata ) {
Mat image = *((Mat*)usedata);
Mat roi;
if (event == EVENT_LBUTTONDOWN) {//左键按下
centerp.x = x;
centerp.y = y;
cout << "center point: " << centerp << endl;
}
else if (event == EVENT_MOUSEMOVE) {//鼠标移动
if (centerp.x > 0 and centerp.y > 0) {
//得有这个判断条件,不然一开始 不按下鼠标左键时就已经有起始点了
endp.x = x;
endp.y = y;
int w = endp.x - centerp.x;
int h = endp.y - centerp.y;
radius = (int)sqrt(pow(w, 2) + pow(h, 2));
temp.copyTo(image);
//矩形可利用rectangle来实现
circle(image, centerp, radius, Scalar(0, 0, 255), 2);
imshow("mousedrawing", image);
}
}
else if (event == EVENT_LBUTTONUP) {//左键抬起
endp.x = x;
endp.y = y;
int w = endp.x - centerp.x;
int h = endp.y - centerp.y;
radius = (int)sqrt(pow(w, 2) + pow(h, 2));
circle(image, centerp, radius, Scalar(0, 0, 255), 2);
imshow("mousedrawing", image);
//截取该部分图像
//先截取矩形的部分,再用模取出圆形
Rect rec;
rec.x = centerp.x - radius;
rec.y = centerp.y - radius;
rec.width = 2 * radius;
rec.height = 2 * radius;
Mat Rec_roi = image(rec);//矩形的ROI区域
Mat roi = Mat::zeros(Rec_roi.size(), Rec_roi.type());
roi = Scalar(255, 255, 255);//将目标ROI背景置白
//利用mask提取圆形的ROI
Mat mask = Mat::zeros(Rec_roi.size(), Rec_roi.type());
circle(mask, Point(radius,radius), radius, Scalar(255, 255, 255), -1);
cvtColor(mask, mask, COLOR_BGR2GRAY);
imshow("mask", mask);
Rec_roi.copyTo(roi, mask);
imshow("ROI", roi);
//清空中心坐标,这样才会停止掉这一次的绘制
centerp.x = -1;
centerp.y = -1;
}
}
int main(int argc, char** argv) {
Mat image = imread("C:/Users/YY/Pictures/Saved Pictures/2.jpg");
namedWindow("mousedrawing");
setMouseCallback("mousedrawing", MouseDraw, &image);
imshow("mousedrawing", image);
temp=image.clone();
waitKey(0);
destroyAllWindows();
return 0;
}