A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/python-opencv-waitkey-function/ below:

Python OpenCV - waitKey() Function

Python OpenCV - waitKey() Function

Last Updated : 14 Jun, 2025

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:

Python
import cv2
img = cv2.imread("gfg_logo.png")

cv2.imshow('gfg', img)
cv2.waitKey(5000)
cv2.destroyAllWindows()

Output

Explanation:

Syntax

cv2.waitKey([delay])

Parameter: delay (Optional) is the time in milliseconds to wait for a key event. If 0, waits indefinitely.

Returns:

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.

Python
import cv2

img = cv2.imread("gfg_logo.png")
cv2.imshow('gfg', img)
cv2.waitKey(0)

Output

Explanation:

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.

Python
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:



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4