美文网首页
OpenCV 画图程序

OpenCV 画图程序

作者: 善法 | 来源:发表于2018-10-12 10:32 被阅读0次
#include <windows.h>
#include <opencv/cv.h>
#include <opencv/highgui.h>

#define ON_CLICK 1
#define NOT_CLICK 0

int THICKNESS=2,mouseState;
CvMat *im;
CvPoint lastPoint;
CvScalar COLOR=cvScalar(0,0,0);

void drawPoint(CvMat *im,int x,int y,int radius,CvScalar color,int thickness,int line_type)
{
    CvPoint center;
    center.x=x;
    center.y=y;
    cvCircle(im,center,radius,color,thickness,line_type,0);
    cvShowImage("image",im);

    lastPoint.x=x;
    lastPoint.y=y;
}

void drawLine(CvMat *im,int px,int py,int x,int y,CvScalar color,int thickness,int line_type)
{
    CvPoint p;
    p.x=x;
    p.y=y;
    cvLine(im,lastPoint,p,color,thickness,line_type,0);
    cvShowImage("image",im);

    lastPoint.x=x;
    lastPoint.y=y;
}

void paint(int event,int x,int y,int flags,void *param)
{
    if (event==CV_EVENT_LBUTTONDOWN)
    {
        mouseState=ON_CLICK;
        drawPoint(im,x,y,THICKNESS,COLOR,-1,8);
    }
    else if (event==CV_EVENT_LBUTTONUP)
    {
        mouseState=NOT_CLICK;
        drawLine(im,lastPoint.x,lastPoint.y,x,y,COLOR,THICKNESS,8);
    }
    else if (mouseState && event==CV_EVENT_MOUSEMOVE)
        drawLine(im,lastPoint.x,lastPoint.y,x,y,COLOR,THICKNESS,8);
}

void clearScreen()
{
    for (int i=0;i<im->height;i++)
        for (int j=0;j<im->width;j++)
            cvSet2D(im,i,j,cvScalar(255, 255, 255));
    cvShowImage("image",im);
}

int main()
{
    im=cvCreateMat(300,400,CV_32F);
    clearScreen();
    cvShowImage("image",im);
    cvSetMouseCallback("image",paint,NULL);
    int key=cvWaitKey(0);
    while (key!=27)
    {
        switch(toupper(key))
        {
            case 'S':
                cvSaveImage("myImage.png",im,0);
                MessageBoxA(GetForegroundWindow(),"保存图片\"myImage.png\"成功!","保存图片",1);
                break;
            case 'C':
                clearScreen();
                break;
        }
        key=cvWaitKey(0);
    }
    cvDestroyAllWindows();
    cvReleaseMat(&im);
    return 0;
}

相关文章

网友评论

      本文标题:OpenCV 画图程序

      本文链接:https://www.haomeiwen.com/subject/olzmgftx.html