《学习OpenCV》第四章课后题3-a

题目说明:
创建一个程序读入并显示一幅图像。
a.允许用户在图像中选择一个矩形区域,然后通过按住鼠标按键画一个矩形。当鼠标键放开,高亮显示矩形框。注意,在内存中保留一个原始图像的副本,图像恢复为原始图像并重新开始绘矩形。

#include <highgui.h>
#include <cv.h>

/* 矩形框 */
CvRect rect;

bool draw = false;   // 标记是否在画

IplImage* img;
IplImage * temp;
IplImage * original;

void draw_rect(IplImage* img, CvRect rect)
{
    cvRectangle( img, 
        cvPoint( rect.x, rect.y ),
        cvPoint( rect.x + rect.width, rect.y + rect.height),
        cvScalar( 0x00, 0x00, 0xff) );
    printf("draw\n");
}

// 鼠标回调函数
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(draw)
            {
                rect.width = x - rect.x;
                rect.height = y - rect.y;
            }
        }
        break;
    case CV_EVENT_LBUTTONDOWN:
        {
            draw = true;
            rect = cvRect( x, y, 0, 0 );
        }
        break;
    case CV_EVENT_LBUTTONUP:
        {
            draw = false;
            if(rect.width < 0)
            {
                rect.x += rect.width;
                rect.width *= -1;
            }
            if(rect.height < 0)
            {
                rect.y += rect.height;
                rect.height *= -1;
            }
            // draw
            draw_rect(image, rect);
        }
        break;
        // 在右键按下时清除
    case CV_EVENT_RBUTTONDOWN:
        cvCopyImage(original, img);
        printf("clear.\n");
        break;
    }
}

int main()
{
    img = cvLoadImage( "E:/shark.jpg", 1 );

    rect = cvRect( -1, -1, 0, 0);

    // 副本
    temp = cvCloneImage( img );
    original = cvCloneImage(img);

    cvNamedWindow("draw rect");
    cvSetMouseCallback("draw rect", my_mouse_callback, (void*)img);

    while(1)
    {
        cvCopyImage(img, temp);

        if(draw)
        {
            draw_rect( temp , rect );
        }

        cvShowImage( "draw rect", temp);

        if(cvWaitKey(15) == 27)
            break;
    }
    cvReleaseImage(&img);
    cvReleaseImage(&temp);
    cvReleaseImage(&original);
    cvDestroyAllWindows();

    return 0;
}

引用:qdsclove的专栏
http://blog.csdn.net/stk_overflow/article/details/8760086

发布了19 篇原创文章 · 获赞 13 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/windxf/article/details/46944247