1. 程式人生 > >【opencv3的滑鼠事件選取ROI區域操作】

【opencv3的滑鼠事件選取ROI區域操作】

  1. 選取影象中的ROI區域:
#include<opencv2\opencv.hpp>
#include <stdio.h>  
using namespace cv;
using namespace std;
Mat org, dst, img, tmp;

	void on_mouse(int event, int x, int y, int flags, void *)

	{

		static Point pre_pt = (-1, -1);

		static Point cur_pt = (-1, -1);

		if (event == CV_EVENT_LBUTTONDOWN)

		{
			pre_pt = Point(x, y);

		}

		else if (event == CV_EVENT_MOUSEMOVE && flags)//摁下左鍵,flags為1 

		{

			org.copyTo(tmp);

			cur_pt = Point(x, y);

			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);

			//cur_pt = Point(x, y);

			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);

			dst = org(Rect(min(cur_pt.x, pre_pt.x), min(cur_pt.y, pre_pt.y), width, height));

			namedWindow("dst");

			imshow("dst", dst);

		}

	}

	void main(){

		org = imread("123捕獲.PNG");

		org.copyTo(img);

		namedWindow("img");
		imshow("img", img);
		setMouseCallback("img", on_mouse, 0);
		waitKey();
		cvtColor(dst, dst, CV_BGR2GRAY);
		imshow("gray", dst);
		//imshow("img", img);

		waitKey(0);

	}