Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How to use OpenCV waitKey in Python

📅 2015-Jan-20 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ opencv, python ⬩ 📚 Archive

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 C++ programs:

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

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):
    QuitProgram()

Tried with: OpenCV 2.4.9, Python 2.7.3 and Ubuntu 14.04


© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 @codeyarns@hachyderm.io📧