How to use OpenCV waitKey in Python

The cv::waitKey(n) function in OpenCV is used to introduce a delay of n milliseconds while rendering images to windows. When used as cv::waitKey(0) it returns the key pressed by the user on the active window. This is typically used for keyboard input from user in OpenCV programs.

char c = cv::waitKey(0);
if ('q' == c)

The above function is available in the Python API of OpenCV. However, it seems to return an integer value that cannot be compared to a char like above. In fact, it is an ASCII value only in the last 8 bits. To use it to compare with a char first mask everything but the first 8 bits and then convert it using the chr builtin method of Python:

c = cv2.waitKey(0)
if 'q' == chr(c & 255):

Tried with: OpenCV 2.4.9, Python 2.7.3 and Ubuntu 14.04


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.