Python OpenCV - waitKey() Function
waitkey() function of Python OpenCV allows users to display a window for given milliseconds or until any key is pressed. It takes time in milliseconds as a parameter and waits for the given time to destroy the window, if 0 is passed in the argument it waits till any key is pressed. Example:
import cv2
img = cv2.imread("gfg_logo.png")
cv2.imshow('gfg', img)
cv2.waitKey(5000)
cv2.destroyAllWindows()
Output

Explanation:
- cv2.imread("gfg_logo.png") loads the image from file into a variable (img) as a NumPy array.
- cv2.imshow('gfg', img) displays the loaded image in a window titled "gfg".
- cv2.waitKey(5000) + cv2.destroyAllWindows() waits for 5 seconds, then closes the image window automatically.
Syntax
cv2.waitKey([delay])
Parameter: delay (Optional) is the time in milliseconds to wait for a key event. If 0, waits indefinitely.
Returns:
- Returns the ASCII code of the pressed key.
- If no key is pressed during the delay, it returns -1.
Use cases of waitkey()
Let's clearly understand the use cases of cv2.waitKey() in OpenCV.
1. Wait indefinitely until key press: cv2.waitKey(0) pauses the program until a key is pressed, commonly used when displaying static images to keep the window open until user input.
cv2.waitKey(0)
2. Wait for a key for limited time: cv2.waitKey(milliseconds) waits for the specified time (in ms) and proceeds if no key is pressed and ideal for video playback, animations or slideshows.
cv2.waitKey(1000)
Examples
Example 1: This example loads and displays an image using OpenCV and waits indefinitely until the user presses any key.
import cv2
img = cv2.imread("gfg_logo.png")
cv2.imshow('gfg', img)
cv2.waitKey(0)
Output

Explanation:
- cv2.imread() loads image into img and cv2.imshow() displays the image in a window.
- cv2.waitKey(0) waits indefinitely for key press and cv2.destroyAllWindows() closes the window.
Example 2: This example plays a video (video.mp4) frame by frame in a loop using OpenCV. It displays each frame in real-time and allows the user to exit the playback by pressing the 'q' key.
import cv2
cap = cv2.VideoCapture('video.mp4')
while True:
ret, frame = cap.read()
if not ret:
break
cv2.imshow('Video Playback', frame)
# wait 25ms and check if 'q' is pressed to quit
if cv2.waitKey(25) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
Output

Explanation:
- cv2.VideoCapture() + cap.read() opens the video and reads frames one by one in a loop.
- cv2.imshow() + cv2.waitKey(25) displays each frame and waits 25ms between frames (for real-time playback).
- Exits if 'q' is pressed, then releases the video and closes all windows.