#include "stdafx.h"
#include "highgui.h"
#include "cv.h"
#define IMG_WIDTH 512
#define IMG_HEIGHT 512
CvFont font;
char *display_text = "|";
// 是否在编辑标签
bool isEditLabel = false;
// 当前标签的起始点
CvPoint point;
IplImage* image;
int EnterKey;//新添加变量,用于判断是否可以编辑文本
void my_mouse_callback(int event, int x, int y, int flags, void* param)
{
switch (event)
{
case CV_EVENT_LBUTTONDOWN://如果左键按下了
isEditLabel = true; //切入编辑状态
point = cvPoint(x, y); //得到点击点的坐标
cvPutText(param, display_text, point, &font, cvScalarAll(255));//以该点为起点打印一排文字
break;
case CV_EVENT_RBUTTONDOWN://如果右键按下了
isEditLabel = false; //切出编辑状态,此时不可以更改
cvPutText(image, display_text, point, &font, cvScalarAll(255));
display_text = "|";
EnterKey = 0;
break;
}
}
int main()
{
image = cvCreateImage(cvSize(IMG_WIDTH, IMG_HEIGHT), IPL_DEPTH_8U, 3);
cvZero(image);
IplImage* temp = cvCloneImage(image);
cvInitFont(&font, CV_FONT_HERSHEY_PLAIN, 1.5f, 1.5f, 0, 1, 8);
cvNamedWindow("image");
cvSetMouseCallback("image", my_mouse_callback, (void*)temp);
while (1)
{
cvCopyImage(image, temp);
if (isEditLabel == true)
{
//puts(display_text);
cvPutText(temp, display_text, point, &font, cvScalarAll(255)); //总是将文字显示在temp上面
}
cvShowImage("image", temp);
char c = cvWaitKey(15);
// 32 -- 126 可显示字符
if (isEditLabel == true && c < 126 && c > 32)//如果处于可编辑状态且字符合法
{
char tempstr[2] = { c };//获取一个字符存入字符传输组
if (display_text == "|")
{
display_text = (char*)malloc(sizeof(char) * 2);
strcpy(display_text, tempstr);
}
else
{
strcat(display_text, tempstr);
}
}
// 13 -- Enter键
else if (c == 13)
{
EnterKey = 1;
}
// 8 -- 退格键
else if (c == 8 && EnterKey == 1)
{
int len = strlen(display_text);
printf("<--\t%d\n", len);
display_text[len - 1] = '\0';
}
else if (c == 27) break;
}
cvReleaseImage(&image);
cvReleaseImage(&temp);
cvDestroyAllWindows();
return 0;
}
注意这里用右键代替enter确定输入
运行结果:
参考于网络。