I am trying to learn OPENCV for an image processing project using online tutorials.
The opencv documentation says that waitKey() returns an int. This is supposed to be the ASCII value of the key pressed. But most tutorials online use the following code which compiles and runs fine.
if ( (char)27==waitKey(1) ) break;
This suggests that waitKey returns a char and not an int. Can someone please explain?
cv::waitKey() returns an int. The reason char key = cv::waitKey(1) works is due to implicit conversions in C++. In this case the return value of type int for cv::waitKey() is implicitely converted to char and then assigned to key. See this link for reference. The following statements are equivalent:
char key = (char) cv::waitKey(30); // explicit cast
char key = cv::waitKey(30); // implicit cast
In the case of if ((char)27 == waitKey(1)) break;, the output of waitKey(1) is probably implicitly converted to char and then compared to esc character (ASCII code 27). I would re-write it with explicit conversion to avoid ambiguity.
if ( (char)27 == (char) waitKey(1) ) break;
The way I see how it's often done in OpenCV sample cpp files:
char key = (char) cv::waitKey(30); // explicit cast
if (key == 27) break; // break if `esc' key was pressed.
if (key == ' ') do_something(); // do_something() when space key is pressed
The following is also possible but the first approach is much cleaner:
int key = cv::waitKey(30) & 255; // key is an integer here
if (key == 27) break; // break when `esc' key is pressed
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With