Reputation: 21622
I'm debugging some C++ code that use OpenCV on Ubuntu 14, which is known to work On Ubuntu 12 and maybe with other OpenCV library build.
What was before
int key_pressed = waitKey(0);
cout << "key_pressed " << int(key_pressed) << endl;
switch( key_pressed )
{
case 27: //esc
{
//close all windows and quit
destroyAllWindows();
}
...
But this code is not working and in output I have key_pressed 1048603
This code work:
char key_pressed = cv::waitKey();
cout << "key_pressed " << int(key_pressed) << endl;
switch( key_pressed )
{
case 27: //esc
{
//close all windows and quit
destroyAllWindows();
}
...
This code is working and in output I have key_pressed 27
What can be reason of such behaviour?
P.S. documentation says that cv::waitKey() return int
, so why we should convert it to char
?
Upvotes: 5
Views: 4635
Reputation: 11420
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
.
In this case: It is implementation-defined.... (That is what the standard says) here is a link to a similar case
Some solutions:
1) put it into a char variable... even though it is implementation-defined it seems that is one of the most common working solutions (in some of the opencv samples they use it)
2) use int key = cv::waitKey(1) & 255
. It will eliminate the extra bits...
To go a little bit further, lets check the values:
You obtained as an int: 1048603
in binary it will be: 00000000 00010000 00000000 00011011
27 in binary is: 00000000 00000000 00000000 00011011
As you can see they differ in that lone bit.... The safetest and most portable way is to remove it with a bitwise logic operation, such as my number 2 solution. Other people use some hex value instead of 255, such as 0xEFFFFF that in binary it will be
00000000 11101111 11111111 11111111
Why this happens?
I searched for this once, it seems that some of the bits changes if you have numslock
or capslock
or ctrl
key active... again, this is platform dependent.
Upvotes: 7