OpenCV入門:ROI関心領域(マウスイベント選択領域)


OpenCV入門:ROI関心領域(マウスイベント選択領域)
ブログhttp://blog.csdn.net/qq_23968185/article/details/51335291
#include 
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"

using namespace std;
using namespace cv;

bool draw;
Mat src;//      
Mat roi;//ROI  
Point cursor;//       
Rect rect;//  ROI    

/*
	void onMouse(int event, int x, int y, int flags, void *param);
	     ,           , opencv ,event       10 , 0-9      :

	EVENT_MOUSEMOVE      =0,    //  
	EVENT_LBUTTONDOWN    =1,    //    
	EVENT_RBUTTONDOWN    =2,    //    
	EVENT_MBUTTONDOWN    =3,    //    
	EVENT_LBUTTONUP      =4,    //    
	EVENT_RBUTTONUP      =5,    //    
	EVENT_MBUTTONUP      =6,    //    
	EVENT_LBUTTONDBLCLK  =7,    //    
	EVENT_RBUTTONDBLCLK  =8,    //    
	EVENT_MBUTTONDBLCLK  =9     //    

	     ,         (x,y)    ,          ,   x ,   y ;
	     ,         ,          ,   32   ,      。
	     ,       。
*/
void onMouse(int event, int x, int y, int flags, void *param)
{
	Mat img = src.clone();
	switch (event)
	{
		//      
	case CV_EVENT_LBUTTONDOWN:
		//       ,    ROI         
		cvDestroyWindow("ROI");
		//        
		cursor = Point(x, y);
		//          
		rect = Rect(x, y, 0, 0);
		draw = true;
		break;

		//            
	case CV_EVENT_LBUTTONUP:
		if (rect.height > 0 && rect.width > 0)
		{
			// img         roi,    SignROI   
			roi = img(Rect(rect.x, rect.y, rect.width, rect.height));
			rectangle(img, rect, Scalar(0, 0, 255), 2);
			namedWindow("SignROI");
			imshow("SignROI", img);

			//                 
			src.copyTo(img);
			imshow("SrcImage", img);

			//  ROI  
			namedWindow("ROI");
			imshow("ROI", roi);
			waitKey(0);
		}
		draw = false;
		break;

		//    
	case CV_EVENT_MOUSEMOVE:
		if (draw)
		{
			// MIN               ,      ,               
			rect.x = MIN(x, cursor.x);
			rect.y = MIN(y, cursor.y);
			rect.width = abs(cursor.x - x);
			rect.height = abs(cursor.y - y);
			//               
			rect &= Rect(0, 0, src.cols, src.rows);
		}
		break;
	}
}

int main()
{
	src = imread("C:\\Users\\Phajaan\\Desktop\\bylw\\opencv\\  .jpg");
	if (src.data == 0)
	{
		cout << "     " << endl;
		return -1;
	}
	namedWindow("SrcImage");
	imshow("SrcImage", src);
	/*
		void setMouseCallback(const string& winname, MouseCallback onMouse, void* userdata=0 );
		Parameters:
		     ,windows    ,   winname         ;
		     ,        ,       ,  ,  ,         ,          ;
		     ,         ID,              ,        0   。
	*/
	setMouseCallback("SrcImage", onMouse, NULL);
	waitKey();
	return 0;
}

効果図:
OpenCV入门:ROI感兴趣区域(鼠标事件选定区域)_第1张图片