用鼠标在图片上画矩形框,并确定矩形框坐标。代码中注意在类里用静态函数static void on_mouse( int event, int x, int y, int flags, void* ustc);
先来介绍两个函数cvPutText和cvInitFont:
1.cvPutText(CvArr* img, const char* text, CvPoint origin, const CvFont* font, CvScalar color);函数中各个参数的含义如下所示:
img---图片指针(需要说明的是,CvArr* 等价于void*,一般我们在这里传递一个IplImage*);
text---需要打印到图片上的字符串内容
origin---字符串在图片上打印的原点(即字符串的左下角在图片中的位置)
font---描述字体属性的变量;
color---字体的颜色;
2.void cvInitFont(CvFont* font, int font_face, double h_scale, double v_scale, double shear=0, int thickness=1, int line_type=8);
该函数中各个变量的含义如下所示:
font---传入及传出的字体属性类型指针
font_face---表示字体的类型,其取值只能为以下数值之一:
1. CV_FONT_HERSHEY_SIMPLEX
2. CV_FONT_HERSHEY_PLAIN
3. CV_FONT_HERSHEY_DUPLEX
4. CV_FONT_HERSHEY_COMPLEX
5. CV_FONT_HERSHEY_TRIPLEX
6. CV_FONT_HERSHEY_COMPLEX_SMALL
7. CV_FONT_HERSHEY_SCRIPT_SIMPLEX
8. CV_FONT_HERSHEY_SCRIPT_COMPLEX
h_scale -只能为1或0.5,表示水平方向字体的缩放系数;
v_scale -只能为1或0.5,表示垂直方向字体的缩放系数;
shear -取值从0到1,表示字体的倾斜程度,0表示不倾斜,1表示倾斜45度;
thichness, line_type这两个参数同OpenCV的其它绘图函数中定义的一样,表示线型的宽度和线条的类型;
void CImgProcess::OnLoadImage()
{
float scale = 0.25;
m_Frame = cvLoadImage("4m左移0.5cm1#.jpg");
CvSize dsize;
dsize.width = m_Frame->width * scale; //目标图像的宽为源图象宽的scale倍
dsize.height = m_Frame->height * scale; //目标图像的高为源图象高的scale倍
src=cvCreateImage(dsize,8,m_Frame->nChannels);
cvResize(m_Frame,src, CV_INTER_AREA );//原始图像缩放成m_Frame1
dst=cvCloneImage(src);
cvNamedWindow("src",1);
cvSetMouseCallback( "src", on_mouse, 0 );
cvShowImage("src",src);
cvWaitKey(0);
cvDestroyAllWindows();
cvReleaseImage(&src);
cvReleaseImage(&dst);
cvReleaseImage(&m_Frame);
}
void CImgProcess::on_mouse( int event, int x, int y, int flags, void* ustc)
{
static CvPoint pre_pt = {-1,-1};
static CvPoint cur_pt = {-1,-1};
CvFont font;
cvInitFont(&font, CV_FONT_HERSHEY_SIMPLEX, 0.5, 0.5, 0, 1, CV_AA);
char temp[16];
if( event == CV_EVENT_LBUTTONDOWN )
{
cvCopy(dst,src);
sprintf(temp,"(%d,%d)",x,y);
pre_pt = cvPoint(x,y);
cvPutText(src,temp, pre_pt, &font, cvScalar(0,0, 0, 255));
cvCircle( src, pre_pt, 3,cvScalar(255,0,0,0) ,CV_FILLED, CV_AA, 0 );
cvShowImage( "src", src );
cvCopy(src,dst);
}
else if( event == CV_EVENT_MOUSEMOVE && !(flags & CV_EVENT_FLAG_LBUTTON))
{
cvCopy(dst,src);
sprintf(temp,"(%d,%d)",x,y);
cur_pt = cvPoint(x,y);
cvPutText(src,temp, cur_pt, &font, cvScalar(0,0, 0, 255));
cvShowImage( "src", src );
}
else if( event == CV_EVENT_MOUSEMOVE && (flags & CV_EVENT_FLAG_LBUTTON))
{
cvCopy(dst,src);
sprintf(temp,"(%d,%d)",x,y);
cur_pt = cvPoint(x,y);
cvPutText(src,temp, cur_pt, &font, cvScalar(0,0, 0, 255));
cvRectangle(src, pre_pt, cur_pt, cvScalar(0,255,0,0), 1, 8, 0 );
cvShowImage( "src", src );
}
else if( event == CV_EVENT_LBUTTONUP )
{
sprintf(temp,"(%d,%d)",x,y);
cur_pt = cvPoint(x,y);
cvPutText(src,temp, cur_pt, &font, cvScalar(0,0, 0, 255));
cvCircle( src, cur_pt, 3,cvScalar(255,0,0,0) ,CV_FILLED, CV_AA, 0 );
cvRectangle( src, pre_pt, cur_pt, cvScalar(0,255,0,0), 1, 8, 0 );
cvShowImage( "src", src );
cvCopy(src,dst);
}
}