使用鼠标绘制矩形

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

using namespace std;

void mouse_draw(int event, int x, int y, int flag, void* img);

IplImage* draw_board;
IplImage* last_img;
bool is_drawing = false;
CvPoint p1;
CvPoint p2;

int main()
{
    draw_board = cvCreateImage(cvSize(500, 500), IPL_DEPTH_8U, 3);
    cvSet(draw_board, cvScalar(255, 255, 255));
    last_img = cvCloneImage(draw_board);

    cvNamedWindow("DrawWindow");
    cvShowImage("DrawWindow", draw_board);
    cvSetMouseCallback("DrawWindow", mouse_draw, draw_board);

    int key;
    while((key = cvWaitKey(1))!=27)
    {
        if(key>0)
            cvSet(last_img, cvScalar(255, 255, 255));

        cvCopy(last_img, draw_board);

        if(is_drawing)
            cvRectangle(draw_board, p1, p2, cvScalar(0, 0, 0), 2);

        cvShowImage("DrawWindow", draw_board);
    }

    cvReleaseImage(&draw_board);
    cvReleaseImage(&last_img);
    cvDestroyWindow("DrawWindow");
    return 0;
}

void mouse_draw(int event, int x, int y, int flag, void* img)
{
    IplImage* draw_board = (IplImage*)img;
    switch(event)
    {
    case CV_EVENT_LBUTTONDOWN:
        if(is_drawing == false)
        {
            is_drawing = true;
            if(x<0) x = 0;
            if(x>=draw_board->width) x = draw_board->width-1;
            if(y<0)y=0;
            if(y>=draw_board->height) y = draw_board->height-1;
            p1 = cvPoint(x, y);
            p2 = p1;
        }
        break;
    case CV_EVENT_LBUTTONUP:
        is_drawing = false;
        cvCopy(draw_board, last_img);
        break;
    case CV_EVENT_MOUSEMOVE:
        if(is_drawing)
        {
            if(x<0) x = 0;
            if(x>=draw_board->width) x = draw_board->width-1;
            if(y<0)y=0;
            if(y>=draw_board->height) y = draw_board->height-1;
            p2 = cvPoint(x, y);
        }
        break;
    }
}


修改了下书中的代码,能够保存之前绘制的图形,键盘用于重置绘板


你可能感兴趣的:(OpenCV)