Opencv打开相机,并在上面用鼠标画框

 

#include <opencv.hpp>
#include <iostream>

using namespace std; 
using namespace cv;


------------- 
#define WINDOW_NAME "【程序窗口】"        //为窗口标题定义的宏 


//-----------------------------------【全局变量声明部分】-----------------------------------
//		描述:全局变量的声明
//-----------------------------------------------------------------------------------------------
Rect g_rectangle;
bool g_bDrawingBox = false;//是否进行绘制
Mat g_srcImage;
Mat g_grayImage;
int g_nThresh = 80;
int g_nThresh_max = 255;


//-----------------------------------------------------------------------------------------------
void DrawRectangle(cv::Mat& img, cv::Rect box)
{
	cv::rectangle(img, box.tl(), box.br(), cv::Scalar(0, 0, 255));//随机颜色
}


//--------------------------------【on_MouseHandle( )函数】-----------------------------
//		描述:鼠标回调函数,根据不同的鼠标事件进行不同的操作
//-----------------------------------------------------------------------------------------------
void on_MouseHandle(int event, int x, int y, int flags, void* param)
{

	Mat& image = *(cv::Mat*) param;
	switch (event)
	{
		//鼠标移动消息
	case EVENT_MOUSEMOVE:
	{
		if (g_bDrawingBox)//如果是否进行绘制的标识符为真,则记录下长和宽到RECT型变量中
		{
			g_rectangle.width = x - g_rectangle.x;
			g_rectangle.height = y - g_rectangle.y;
		}
	}
	break;

	//左键按下消息
	case EVENT_LBUTTONDOWN:
	{
		g_bDrawingBox = true;
		g_rectangle = Rect(x, y, 0, 0);//记录起始点
	}
	break;

	//左键抬起消息
	case EVENT_LBUTTONUP:
	{
		g_bDrawingBox = false;//置标识符为false
		//对宽和高小于0的处理
		if (g_rectangle.width < 0)
		{
			g_rectangle.x += g_rectangle.width;
			g_rectangle.width *= -1;
		}

		if (g_rectangle.height < 0)
		{
			g_rectangle.y += g_rectangle.height;
			g_rectangle.height *= -1;
		}
		//调用函数进行绘制
		DrawRectangle(image, g_rectangle);
	}
	break;

	}
}



void main()
{
	VideoCapture openCamera(0);

	if (openCamera.isOpened())
	{
		Mat camFrame;				//jjdjkfjajfjl
		Mat drawImage;             //jjdjkfjajfjl

		while (true)
		{
			openCamera >> camFrame;


			////【2】设置鼠标操作回调函数
			namedWindow(WINDOW_NAME);
			setMouseCallback(WINDOW_NAME, on_MouseHandle, (void*)&camFrame);


			//【3】程序主循环,当进行绘制的标识符为真时,进行绘制
			while (g_bDrawingBox)
			{
				camFrame.copyTo(drawImage);//拷贝源图到临时变量
				DrawRectangle(drawImage, g_rectangle);//当进行绘制的标识符为真,则进行绘制
				imshow("DrawLines", drawImage);
				if (waitKey(10) == 27) break;//按下ESC键,程序退出
			}
		
	
			//【5】  
			imshow(WINDOW_NAME, camFrame);
			//waitKey(30);
			if (waitKey(10) == 27) break;//按下ESC键,程序退出



		}
	}

}

 

上一篇:#Leetcode# 223. Rectangle Area


下一篇:c++学习(类、内联、构造、析构)