示例代码:
void demo::key_demo(Mat& image)
{
Mat dsc = Mat::zeros(image.size(), image.type());
while (true)
{
int c = waitKey(100);
if (c == 27)
break;
if (c == 49)
{
cout << c << endl;
cvtColor(image, dsc, COLOR_BGR2GRAY);
}
if (c == 50)
{
cout << c << endl;
cvtColor(image, dsc, COLOR_BGR2HSV);
}
if (c == 51)
{
cout << c << endl;
dsc = Scalar(50, 50, 50);
add(image, dsc, dsc);
}
imshow("键盘输入", dsc);
}
}
这里主要是注意waitKey()函数,声明在highgui.hpp
CV_EXPORTS_W int waitKey(int delay = 0);
delay默认为0,waitKey(0)表示窗口一直停留在当前界面,waitKey(50)表示延时50ms,窗口停留50ms后自动关闭。
同时waitKey有返回值,返回值是键盘输入对应字符的ASCII码,比如上面代码c==27,27对应的ASCII码就是“ESC”,即退出当前界面,同理,49对应字符“1”,50对应字符“2”,51对应字符“3”.
waitKey的返回值必须在延时时间内,所以延时时间不能太短。
效果:
over!!!