在Linux下使用waitKey函数使程序跳出while循环时遇到了一个问题,就是在按下esc
键的时候,程序不能够按照预想的退出循环。
while(true)
{
/* your code here */
int keyCode = cv::waitKey(10);
if(keyCode == 27)
{
break;
}
}
这个时候没有办法只能够看看waitKey函数的输出值是什么了,当我按下ESC
键的时候,输出的keycode竟然变成了 1048603 ,很明显在Linux下,OpenCV返回的并不是一个char的类型值。
在stackoverflow上搜索之后发现问题:
This function is highly dependent on the operating system :/ some of them add a bit to the integer....it should return the ascii code of the key press, for example, 27 is the ascii code for the ESC key...Now, the problem would be to know what happens when you cast an int to a char.
也就是说,keyCode值必须显式的指定为char
类型的变量,例如:
while(true)
{
/* your code here */
char keyCode = cv::waitKey(10);
if(keyCode == 27)
{
break;
}
}
或者是进一步观察:
用int变量获得的keycode:1048603
二进制形式为:00000000 00010000 00000000 00011011
而27的二进制形式为: 00000000 00000000 00000000 00011011
因此可以使用按位操作的方式来只取最后八位的结果
while(true)
{
/* your code here */
char keyCode = cv::waitKey(10) & 255;
/* 00000000 00010000 00000000 00011011 -> 1048603
* 00000000 00000000 00000000 11111111 ->255
*位与 00000000 00000000 00000000 00011011 -> 27
*/
if(keyCode == 27)
{
break;
}
}
留言