Opencv 鼠标画矩形

 此文转载自 http://www.geek-workshop.com/thread-1604-1-1.html

 网上大多数都把 一堆代码写在外部 void on_mouse (...) 里面。 但实际用到时写在里面会有很多局限性。

 我们只需要鼠标带来的点的坐标信息就可以。 

 所以可以用1个或多个CvPoint 把里面的鼠标点击信息提取出来就达到了这个函数的目的了。

#include "stdafx.h"
#include "cv.h"
#include "highgui.h"
 
//第一个点 point_c 是矩形起始左上角的定点
//第二个点 point 用来确立矩形大小宽和高
CvPoint point_c;
CvPoint point;
void on_mouse(int event, int x, int y, int flags, void* dr)
{
        //左键点击 按下
        if (event == CV_EVENT_LBUTTONDOWN)
        {
                point_c.x = x;
                point_c.y = y;
        }
        //左键拖拽 flags 
        if (flags == CV_EVENT_FLAG_LBUTTON)
        {
                point.x = x;
                point.y = y;
        }
}
 
int _tmain(int argc, _TCHAR* argv[])
{
 
        cvNamedWindow("Rectangle", 1);
 
        IplImage *img_rect = cvCreateImage(cvSize(400, 400), 8, 3);
 
        cvSetMouseCallback("Rectangle", on_mouse, 0);
 
        for (;;)
        {                
                cvZero(img_rect);
 
                if (point.x > 0 && point.y > 0)
                {
                        cvRectangle(img_rect,point_c,point,CV_RGB(0,0,255),2);
                }
 
 
                cvShowImage("Rectangle", img_rect);
 
                char c = cvWaitKey(1);
 
                if (c == 27)
                {
                        break;
                }
        }
 
        cvDestroyAllWindows();
        cvReleaseImage(&img_rect);
 
        return 0;
}

 

posted @ 2013-03-15 23:55  Liqun Liu  阅读(380)  评论(0编辑  收藏  举报