学习OpenCV2——用鼠标截取图像区域并显示

     用鼠标截取图像区域是一种常用操作,我参考了网上众多实现的方法,觉得以下方法最简洁。特此学习并分享。


     原文  http://www.cnblogs.com/tornadomeet/archive/2012/05/04/2483444.html


下面程序实现了从视频中选择一个区域并单独显示。

//**************本程序练习了鼠标回调函数*********************

#include <opencv2/highgui/highgui.hpp>
#include <opencv2/core/core.hpp>
#include <stdio.h>

using namespace cv;
using namespace std;

///--定义几个全局变量
Rect select;                 //鼠标选择的矩形框
bool mousedown_flag = false; //鼠标按下的标识符
bool select_flag = false;    //选择区域的标识符
Point origin;
Mat frame;

void onMouse(int event,int x,int y,int,void*)
{    
	//注意onMouse是void类型的,没有返回值!
	//为了把这些变量的值传回主函数,这些变量必须设置为全局变量	
	if(mousedown_flag)
	{
		select.x=MIN(origin.x,x);     //不一定要等鼠标弹起才计算矩形框,而应该在鼠标按下开始到弹起这段时间实时计算所选矩形框
		select.y=MIN(origin.y,y);
		select.width=abs(x-origin.x);                  //算矩形宽度和高度
		select.height=abs(y-origin.y);
		select&=Rect(0,0,frame.cols,frame.rows);       //保证所选矩形框在视频显示区域之内
	}
	if(event==CV_EVENT_LBUTTONDOWN)
	{
		mousedown_flag=true;        
		select_flag = false;                        
		origin=Point(x,y);             
		select=Rect(x,y,0,0);           //这里一定要初始化,宽和高为(0,0)是因为在opencv中Rect矩形框类内的点是包含左上角那个点的,但是不含右下角那个点
	}
	else if(event==CV_EVENT_LBUTTONUP)
	{
		mousedown_flag=false;
		select_flag = true;		
	}
}

int main(int argc, unsigned char* argv[])
{ 
	//打开摄像头
	VideoCapture cam(0);
	if (!cam.isOpened())
		return -1;

	//建立窗口
	namedWindow("camera",1);

	//捕捉鼠标
	setMouseCallback("camera",onMouse,0);

	Mat frameROI;      
	while(1)
	{
		//读取一帧图像
		cam>>frame;
		if(frame.empty())
			return -1;

		//显示选择的区域
		if(select_flag)
		{
			frameROI = frame(select);   //设置感兴趣区域ROI
			imshow("roi",frameROI);     //显示ROI
		}	 

		//在每一帧图像上画矩形框
		rectangle(frame,select,Scalar(255,0,0),1,8,0);
		//显示原视频帧
		imshow("camera",frame);

		//显示所选区域的值	 
		printf("\n X = %d, Y = %d, Width = %d, Height = %d",select.x, select.y, select.width, select.height);

		//键盘响应
		int c = waitKey(20);
		if(27==c)//ESC键
			return -1;
	}
	return 0;
}



你可能感兴趣的:(图像处理,opencv2,截取区域)