用鼠标在窗口中画方形

//用鼠标在窗口中画方形
//作者:sandy
//时间:2015-10-7

//user can draw boxes on the screen
#include <cv.h>
#include <highgui.h>
using namespace std;

CvRect box;
bool drawing_box=false;


//定义一个回调函数
//define our callback which we will install for mouse event
//
void my_mouse_callback(int event ,int x,int y,int flags,void* param);


//实现把方形画在一幅画上的小程序
//A little subroutine to draw a box into an image
//
void draw_box(IplImage* img ,CvRect rect);


int main(int argc,char* argv[]){

    box=cvRect(-1,-1,0,0);//(x,y,width,height)

    IplImage* image=cvCreateImage(cvSize(400,400),IPL_DEPTH_8U,3);//创建一个图像(画板)
    cvZero(image);//将数组中的所有通道的元素的值都设置为0.
    IplImage* temp=cvCloneImage(image);//image克隆到temp

    cvNamedWindow("mouse_rect_window");//定义一个视窗

    //在opencv中注册回调函数,传入图像参数,以便特定窗口被触发鼠标事件后,opencv可以正确调用
    //
    cvSetMouseCallback("mouse_rect_window",my_mouse_callback,(void*) image);//触发窗口为:mouse_rect_window,触发调用函数为:my_mouse_callback,传给触发调用函数的void * param值为(void*) image

    //The main program loop.here we copy the working image to the 'temp' image,
    //and if the user is drawing , then put the currently contemplated box onto the 
    //temp image.Display the temp image,and wait 15ms for a keystroke,then repeat...
    //
    while(1){
        cvCopyImage(image,temp);//把image复制到temp中
        if(drawing_box) draw_box(temp,box);
        cvShowImage("mouse_rect_window",temp);

        if(cvWaitKey(15)==27) break;
    }

    cvReleaseImage(&image);
    cvReleaseImage(&temp);
    cvDestroyWindow("mouse_rect_window");
}

//鼠标响应事件
void my_mouse_callback(int event ,int x,int y,int flags,void* param){
    IplImage* image=(IplImage*)param;

    switch(event){

        case CV_EVENT_MOUSEMOVE:{
            if(drawing_box){
                box.width=x-box.x;
                box.height =y-box.y;
                //cout<<x<<','<<y<<endl;
                //cout<<box.x<<','<<box.y<<endl;
            }    
        }
        break;
        case CV_EVENT_LBUTTONDOWN:{
            drawing_box=true;
            box=cvRect(x,y,0,0);//起点坐标,宽,高
            //cout<<x<<','<<y<<endl;
            //cout<<box.x<<','<<box.y<<endl;
        }
        break;
        case CV_EVENT_LBUTTONUP:{
            drawing_box=false;
            if(box.width<0){
                box.x +=box.width ;
                box.width  *=-1;
            }
            if(box.height<0){
                box.y +=box.height ;
                box.height *=-1;
            }
            draw_box(image,box);
        }
        break;

    }
}
//实现把方形画在一幅画上的小程序
//A little subroutine to draw a box into an image
//
void draw_box(IplImage* img ,CvRect rect){
    cvRectangle(
        img,
        cvPoint(box.x ,box.y),
        cvPoint(box.x +box.width,box.y +box.height),
         cvScalar(0, 120, 255)//画线的颜色
        );
}

原文地址:https://www.cnblogs.com/beihaidao/p/4870093.html