天天看點

《OpenCV:滑鼠操作(繪制直線、矩形、圓)簡單示例》

《OpenCV:滑鼠操作(繪制直線、矩形、圓)簡單示例》
#include<opencv2/opencv.hpp>
#include<iostream>

void on_mouse(int event, int x, int y, int flags, void* ustc);
void drawRectangle(cv::Mat src, cv::Point pt1, cv::Point pt2);
void drawCircle(cv::Mat src, cv::Point pt_center, int pt_radius);
void drawLine(cv::Mat src, cv::Point pt1, cv::Point pt2, cv::Scalar color);

cv::Point pre_pt= cv::Point(-1,-1), cur_pt= cv::Point(-1, -1);//滑鼠點

#define WINDOW_NAME "image"

int main()
{
	cv::Mat srcImage;
	cv::Point center;
	int radius=0;
	cv::VideoCapture capture(0);
	capture.set(CV_CAP_PROP_FRAME_WIDTH, 640);
	capture.set(CV_CAP_PROP_FRAME_HEIGHT, 480);
	cv::namedWindow(WINDOW_NAME, cv::WINDOW_AUTOSIZE);
	if (!capture.isOpened())//判斷攝像頭是否打開
	{
		std::cout << "視訊加載失敗 !" << std::endl;
	}

	while (true)
	{
		capture >> srcImage;
		if (srcImage.empty())
		{
			std::cout << "視訊加載失敗 !" << std::endl;
			return -1;
		}
		cv::setMouseCallback(WINDOW_NAME, on_mouse, 0);
		if (cur_pt.x!=-1&& cur_pt.y != -1)
		{
			drawLine(srcImage, pre_pt, cur_pt, cv::Scalar(0,255,0));
			drawRectangle(srcImage, pre_pt, cur_pt);
			drawCircle(srcImage, center, radius);
		}
		
		imshow(WINDOW_NAME, srcImage);
		if (cv::waitKey(25)==27)
		{
			break;
		}
	}
	capture.release();
	//按ESC退出時銷毀所有視窗
	cv::destroyAllWindows();
	return 0;
}

//畫線
void drawLine(cv::Mat src, cv::Point pt1, cv::Point pt2, cv::Scalar color)
{
	cv::line(src, pt1, pt2, color, 1, CV_AA);
}

//畫框
void drawRectangle(cv::Mat src, cv::Point pt1, cv::Point pt2)
{
	cv::rectangle(src, pt1, pt2, cv::Scalar(0, 255, 0), 1, CV_AA, 0);
}
//畫圓
void drawCircle(cv::Mat src, cv::Point pt_center, int pt_radius)
{
	pt_center.x = (pre_pt.x < cur_pt.x) ? pre_pt.x + abs(cur_pt.x - pre_pt.x) / 2 : cur_pt.x + abs(cur_pt.x - pre_pt.x) / 2;
	pt_center.y = (pre_pt.y < cur_pt.y) ? pre_pt.y + abs(cur_pt.y - pre_pt.y) / 2 : cur_pt.y + abs(cur_pt.y - pre_pt.y) / 2;
	pt_radius = std::sqrt((cur_pt.x- pre_pt.x)*(cur_pt.x - pre_pt.x)+ (cur_pt.y - pre_pt.y)*(cur_pt.y - pre_pt.y))/2;
	cv::circle(src, pt_center, pt_radius, cv::Scalar(0, 255, 0), 1, CV_AA, 0);
}

//滑鼠操作
void on_mouse(int event, int x, int y, int flags, void* ustc)
{
	//左鍵按下
	if (event == CV_EVENT_LBUTTONDOWN)
	{
		cv::Point pt= cv::Point(x, y);
		pre_pt = pt;
	}
	//左鍵按下并且滑鼠移動
	else if (event == cv::EVENT_MOUSEMOVE && (flags & cv::EVENT_FLAG_LBUTTON))
	{
		cv::Point pt = cv::Point(x, y);
		cur_pt = pt;
	}
	//左鍵彈起
	else if (event == CV_EVENT_LBUTTONUP)
	{
		cv::Point pt = cv::Point(x, y);
		cur_pt = pt;
	}
}