在图像中选择矩形区域并高亮显示

《学习OpenCV》书后习题4-3

允许用户在图像中选择一个矩形区域,然后通过按住鼠标按键画一个矩形,当鼠标键放开,高亮显示矩形框。

源代码:

#include "stdafx.h"
#include "cv.h"
#include "highgui.h"

 bool drawing_box=false;
 CvRect box;  

IplImage* rect_img(IplImage* img)
{
   cvRectangle(img,cvPoint(box.x,box.y),cvPoint(box.x+box.width,box.y+box.height),cvScalar(0x00,0x00,0x00));
	IplImage* head1=cvCreateImageHeader(cvSize(box.width,box.height),img->depth ,img->nChannels);
	head1->origin=img->origin ;
	head1->widthStep=img->widthStep;
	head1->imageData=img->imageData+box.y *img->widthStep+box.x*img->nChannels;
	cvNot(head1,head1);
	return img;
}

void mouseHandler(int event,int x,int y,int flags,void* param)
{	
	IplImage* img0,*img1;
	img0=(IplImage*) param;
	img1=cvCloneImage(img0);    //对副本进行操作
	switch( event )
	{
	case CV_EVENT_MOUSEMOVE:
		{
			if(drawing_box)
			{
				box.width=x-box.x;
				box.height=y-box.y;
			}
		}    break;
	case CV_EVENT_LBUTTONDOWN:
		{
			drawing_box=true;
			box=cvRect(x,y,0,0);
		}  break;
	case CV_EVENT_LBUTTONUP:
		{
			drawing_box=false;
			if(box.height<0)
			{
				box.y+=box.height;
				box.height*=-1;
			}
          IplImage* img2=rect_img(img1);
          cvShowImage( "Image", img2); 
		}  break;							
	}
}

int _tmain(int argc, _TCHAR* argv[])
{
    IplImage* img=cvLoadImage("lena.jpg",1);
    //载入图像
    assert(img);
    cvNamedWindow( "Image", 1 ); //创建窗口
	cvSetMouseCallback("Image",mouseHandler,(void*) img);
    cvShowImage( "Image", img ); //显示图像
    cvWaitKey(0); //等待按键
    cvDestroyWindow( "Image" );//销毁窗口
    cvReleaseImage( &img ); //释放图像
    return 0;
}

效果:



你可能感兴趣的:(openCV)