cvWaitKey() is a function in the OpenCV library, primarily used to pause program execution while displaying images and wait for user keyboard input. Specifically, this function serves the following purposes:
-
Delay: The parameter specifies a time in milliseconds indicating how long the window waits for keyboard input. If the parameter is 0, it waits indefinitely for user input.
-
Keyboard Input Response: This function captures user keyboard input. If a key is pressed within the specified time, it returns the ASCII code of the key; otherwise, it returns -1. This enables developers to implement specific program logic based on user input.
-
Image Display: When processing images with OpenCV, the
imshow()function is typically used to display images. To keep the window visible instead of disappearing immediately,cvWaitKey()is commonly used afterimshow().
Example
Assume we are writing a program that displays an image and allows the user to save it by pressing the "s" key or exit by pressing the ESC key. Here is an example implementation:
pythonimport cv2 # Read an image image = cv2.imread('path_to_image.jpg') # Display the image cv2.imshow('Image Window', image) while True: # Wait for keyboard input key = cv2.waitKey(0) & 0xFF # Check if the key is ESC (27 is the ASCII code for ESC) if key == 27: break # Check if the key is 's' or 'S' elif key == ord('s') or key == ord('S'): # Save the image cv2.imwrite('path_to_save.jpg', image) print("Image saved!") break # Destroy all windows cv2.destroyAllWindows()
In this example, cvWaitKey(0) causes the program to wait indefinitely for user keyboard input when no keys are pressed. When a key is pressed, it checks if it is "s" or ESC and executes the corresponding action (saving the image or exiting).