#include <cv.h>
#include <highgui.h>
#include <stdio.h>
#include <string.h>
#pragma comment(lib,"cv.lib") //载入库文件
#pragma comment(lib,"cvcam.lib")
#pragma comment(lib,"cxcore.lib")
#pragma comment(lib,"highgui.lib")
bool g_IsDown=false; //全局变量
CvPoint g_Point;
void my_callback(int event, int x, int y, int flags, void* param); //声明Show窗口的鼠标回调函数
void put_text(IplImage *image,CvPoint point); //在图像的相应点上写字
void main()
{
IplImage *orginal_image=cvLoadImage("1.jpg");
assert(orginal_image!=NULL);
IplImage *temp_image=cvCreateImage(cvGetSize(orginal_image),orginal_image->depth,orginal_image->nChannels);
assert(temp_image!=NULL);
cvNamedWindow("Show");
cvSetMouseCallback("Show",my_callback,(void*)(temp_image));
while (1)
{
cvCopyImage(orginal_image,temp_image);
if (true==g_IsDown)
{
cvCopyImage(orginal_image,temp_image);
put_text(temp_image,g_Point);
}
if (false==g_IsDown)
{
cvCopy(orginal_image,temp_image);
put_text(temp_image,g_Point);
}
cvShowImage("Show",temp_image);
cvWaitKey(30);
}
}
void my_callback(int event, int x, int y, int flags, void* param) //定义show窗口的鼠标回调函数
{
IplImage *image=(IplImage*)(param);
switch (event)
{
case CV_EVENT_LBUTTONDOWN:{
g_IsDown=true;
if (x<0) x=0;
if (y<0) y=0;
g_Point=cvPoint(x,y);
}
break;
case CV_EVENT_MOUSEMOVE:{
if (true==g_IsDown)
{
if (x<0) x=0;
if (y<0) y=0;
g_Point=cvPoint(x,y);
}
}
break;
case CV_EVENT_LBUTTONUP:{
if (x<0) x=0;
if (y<0) y=0;
g_IsDown=false;
}
put_text(image,g_Point);
break;
}
}
void put_text(IplImage *image,CvPoint point)
{
char str[200]; //存储临时的字符串
uchar *ptr=(uchar*)(image->imageData+point.y*image->widthStep+point.x*image->nChannels);
int blue=(int)(ptr[0]);
int green=(int)(ptr[1]); //存储获取的颜色信息
int red=(int)(ptr[2]);
char char_red[10];
itoa(red,char_red,10);
char char_green[10]; //存储字符型的RGB值
itoa(blue,char_green,10);
char char_blue[10];
itoa(green,char_blue,10);
char char_point_x[10]; //存贮点位置的字符串变量
itoa(point.x,char_point_x,10);
char char_point_y[10];
itoa(point.y,char_point_y,10);
// printf("R: %d G: %d B: %d",red,blue,green); for debug
strcpy(str,"Postion :");
strcat(str,char_point_x);
strcat(str," ");
strcat(str,char_point_y);
strcat(str," RGB: ");
strcat(str,char_red);
strcat(str," ");
strcat(str,char_green);
strcat(str," ");
strcat(str,char_blue);
CvFont font;
cvInitFont(&font,CV_FONT_HERSHEY_SIMPLEX,0.5,0.5);
cvPutText(image,str,point,&font,CV_RGB(0xff,0xff,0x00));
}