User input OpenCV HighGui
To get string input from a user in OpenCV HighGui:
//==================================================================================
//User input from consol or window. User can edit the command line or esc to cancel
//
//INPUT:
//prompt is the question to the user
//init is the default answer value coming in
//std1_win0 means read from stdin if 1, or from pop-up window if 0
//clr clear the window after done
//windowname The name of the pop up window
//
//RETURN:
// string with user respponse
//
std::string getString(std::string prompt, std::string init,int std1_win0, bool clr, string windowname ="I/O window" )
{
namedWindow(windowname,0);
std::string str=init;
Point orgprompt(10,30);
Point org(10,60);
Mat io_mat(400,600,CV_8UC3);
if(std1_win0)
{
printf("%s\n%s",prompt.c_str(),str.c_str());
fflush(stdout);
}
else
{
io_mat.setTo(Scalar(0,0,0));
putText(io_mat, prompt, orgprompt, CV_FONT_HERSHEY_SIMPLEX,1.0, Scalar(0,100,255),2); //Write string
putText(io_mat, str, org, CV_FONT_HERSHEY_SIMPLEX, 1.0, Scalar(255,255,255),2); //Write string
imshow(windowname,io_mat);
}
int c = 0, slen;
//COLLECT USER INPUT, IGNORE WHITESPACE, ESC OUT
while (1)
{
c = waitKey(0) & 0xFF;
if(c == 27) {str.erase(); break;}
if((c == 0)||(c > 128)) continue;
if((c == 13)||(c == 10)) break; //Carriage return and/or line feed => accept this label
if((c == ' ')||(c == '\t')) continue; //Ignore white space
slen = str.length();
if(!std1_win0)
putText(io_mat, str, org, CV_FONT_HERSHEY_SIMPLEX, 1.0, Scalar(0,0,0),2); //Write string
else
{
printf("\r");
for(int u=0; u<slen; ++u)
printf(" ");
printf("\r");
}
if(c == 8) //backspace
{
//OVERLAY MASK ONTO IMAGE
if(std1_win0)
{
printf("\r");
for(int u=0; u<slen; ++u)
printf(" ");
printf("\r");
}
if(slen)
str.erase(slen - 1);
}
else
{
str.append(1, (char)c);
}
if(std1_win0)
{
printf("%s\r",str.c_str());
fflush(stdout);
}else
{
putText(io_mat, str, org, CV_FONT_HERSHEY_SIMPLEX, 1.0, Scalar(255,255,255),2); //Write string
imshow(windowname,io_mat);
}
} //End while
//CLEAN UP AND OUT
if(std1_win0)
{
printf("string %s\n",str.c_str());
printf("\n");
}
else
{
io_mat.setTo(Scalar(0,0,0));
putText(io_mat, prompt, orgprompt, CV_FONT_HERSHEY_SIMPLEX,1.0, Scalar(0,100,255),2); //Write string
putText(io_mat, str, org, CV_FONT_HERSHEY_SIMPLEX, 1.0, Scalar(255,255,255),2); //Write string
if(clr) io_mat.setTo(Scalar(0,0,0));
imshow(windowname,io_mat);
}
return str;
}