《学习OpenCV》第四章5-a
#include<stdio.h>
#include"cv.h"
#include"highgui.h"
bool isLeftDown=false;
bool isRightDown=false;
CvRect rect;
//绘制线段
void drawingLine(IplImage* img,CvRect rect)
{
cvLine( img , cvPoint(rect.x, rect.y), cvPoint(rect.x+rect.width, rect.y+rect.height), cvScalar(255,0,0), 3, 8, 0 );
}
//绘制矩形
void drawingRect(IplImage* img, CvRect rect)
{
cvRectangle(img, cvPoint(rect.x, rect.y), cvPoint(rect.x+rect.width, rect.y+rect.height), cvScalar(0, 255, 0), 2, 8, 0);
}
//绘制圆形
void drawingCircle(IplImage* img, CvRect rect)
{
CvPoint centerPoint=cvPoint(rect.x,rect.y);
float radius=sqrt( (rect.width*rect.width +rect.height *rect.height) );
cvCircle( img, centerPoint, radius, cvScalar(0,0,255), 1, 8, 0 );
}
//绘制椭圆
void drawingEllipse(IplImage* img, CvRect rect)
{
CvPoint centerPoint=cvPoint(rect.x,rect.y);
CvSize size=cvSize(rect.width, rect.height);
cvEllipse(img, centerPoint, size, 0, 0, 360, cvScalar(255,255, 0), 1, 8, 0);
}
//鼠标回调函数
void myMouseCallBack(int even, int x, int y, int flags, void* param)
{
IplImage* srcImg=(IplImage*) param;
switch (even)
{
case CV_EVENT_LBUTTONDOWN:
rect=cvRect(x, y, 0, 0);
isLeftDown=true;
break;
case CV_EVENT_MOUSEMOVE:
if (isLeftDown)
{
rect.width=x- rect.x;
rect.height=y- rect.y;
}
else if(isRightDown)
{
IplImage* temp=cvCreateImageHeader( cvSize(20, 20), srcImg->depth, srcImg->nChannels );
temp->widthStep=srcImg->widthStep;
temp->imageData = srcImg->imageData+srcImg->widthStep* y +3*x;
cvSetZero(temp); //对所指定的区域清零
cvReleaseImageHeader(&temp);
}
break;
case CV_EVENT_LBUTTONUP:
isLeftDown=false;
if (rect.width<0)
{
rect.x +=rect.width;
rect.width *=-1;
}
if (rect.height<0)
{
rect.y +=rect.height;
rect.height *=-1;
}
break;
case CV_EVENT_RBUTTONDOWN:
isRightDown=true;
break;
case CV_EVENT_RBUTTONUP:
isRightDown=false;
break;
default:
break;
}
}
void main()
{
IplImage* img=cvCreateImage(cvSize(800, 600), IPL_DEPTH_8U, 3);
cvZero(img);
int selectFlag=3;
cvNamedWindow("Image", 1);
cvShowImage("Image", img);
cvSetMouseCallback("Image", myMouseCallBack, img);
while(1)
{
if (isLeftDown)
{
switch (selectFlag)
{
case 0: drawingLine(img, rect); break;
case 1:drawingCircle(img, rect); break;
case 2: drawingRect(img, rect); break;
case 3: drawingEllipse(img ,rect); break;
default:
break;
}
}
cvShowImage("Image", img);
if (cvWaitKey(40)==27) break;
}
cvWaitKey(-1);
}