OpenCV之鼠标响应事件

xiaoxiao2021-02-28  127

用鼠标画框框。。

#include <opencv2/opencv.hpp> #include <opencv2/opencv_modules.hpp> #include <opencv2/highgui/highgui.hpp> #include <cstdio> using namespace cv; Mat org,dst,img,tmp; void on_mouse(int event,int x,int y,int flags,void *ustc){ static Point pre_pt=Point(-1,-1); static Point cur_pt=Point(-1,-1); char temp[16]; if (event==CV_EVENT_LBUTTONDOWN){ org.copyTo(img); sprintf(temp,"(%d,%d)",x,y); pre_pt=Point(x,y); putText(img,temp,pre_pt,FONT_HERSHEY_SIMPLEX,0.5,Scalar(0,0,0,255),1,8); circle(img,pre_pt,2,Scalar(255,0,0,0),CV_FILLED,CV_AA,0); // BGR imshow("img",img); } else if (event==CV_EVENT_MOUSEMOVE&&!(flags&CV_EVENT_FLAG_LBUTTON)){ img.copyTo(tmp); sprintf(temp,"(%d,%d)",x,y); cur_pt=Point(x,y); putText(tmp,temp,cur_pt,FONT_HERSHEY_SIMPLEX,0.5,Scalar(0,0,0,255)); imshow("img",tmp); } else if (event==CV_EVENT_MOUSEMOVE&&(flags&CV_EVENT_FLAG_LBUTTON)){ img.copyTo(tmp); sprintf(temp,"(%d,%d)",x,y); cur_pt=Point(x,y); putText(tmp,temp,cur_pt,FONT_HERSHEY_SIMPLEX,0.5,Scalar(0,0,0,255)); rectangle(tmp,pre_pt,cur_pt,Scalar(0,255,0,0),1,8,0); imshow("img",tmp); } else if (event==CV_EVENT_LBUTTONUP){ org.copyTo(img); sprintf(temp,"(%d,%d)",x,y); cur_pt=Point(x,y); putText(img,temp,cur_pt,FONT_HERSHEY_SIMPLEX,0.5,Scalar(0,0,0,255)); circle(img,pre_pt,2,Scalar(255,0,0,0),CV_FILLED,CV_AA,0); rectangle(img,pre_pt,cur_pt,Scalar(0,255,0,0),1,8,0); imshow("img",img); img.copyTo(tmp); int width=abs(pre_pt.x-cur_pt.x); int height=abs(pre_pt.y-cur_pt.y); if (width==0||height==0){ printf("width==0||height==0"); return; } dst=org(Rect(min(cur_pt.x,pre_pt.x),min(cur_pt.y,pre_pt.y),width,height)); namedWindow("dst",WINDOW_AUTOSIZE); imshow("dst",dst); waitKey(0); } } int main(){ org=imread("/Users/hxh/Desktop/1.jpg"); org.copyTo(img); org.copyTo(tmp); namedWindow("img"); setMouseCallback("img",on_mouse,0); imshow("img",img); waitKey(0); return 0; }
转载请注明原文地址: https://www.6miu.com/read-68279.html

最新回复(0)