liveBook · Manning

waitKey

As explained in Build Your Own Robot: Using Python, CRICKIT, and Raspberry Pi

OpenCV waitKey waits for a specified interval, returns a keyboard input code when available, and processes window events.

OpenCV's waitKey controls keyboard interaction and window updates. Called with an interval, it waits briefly for input, returns the pressed key code, and processes GUI events. section 8.3.3

Use the call according to the required interaction:

  • Call waitKey(1) inside a camera loop to wait 1 millisecond and continue; an unpressed key returns -1. section 8.3.3
  • Check the returned code against ord('q'), the Esc key code, or another control such as the space key. section 8.3.3
  • Call waitKey() without an interval when an image window should remain visible until a key is pressed. section 9.3.2

Keyboard-controlled camera loop

A snapshot application uses while (key := cv2.waitKey(1)) not in [ord('q'), ESC_KEY] to keep displaying camera frames, save a frame when the space key is pressed, and exit on Q or Esc. section 8.3.3

messages = []
while (key := cv2.waitKey(1)) not in [ord('q'), ESC_KEY]:

View the compact event-loop expression that captures the returned key code while processing the OpenCV window. section 8.3.3

def main():
    frame = cv2.imread('photo.jpg')
    center = detect_face(frame)
    print('face center:', center)
    cv2.imshow('preview', frame)
    cv2.waitKey()

View the blocking call used to keep a detected-face preview open until keyboard input arrives. section 9.3.2

How Build Your Own Robot: Using Python, CRICKIT, and Raspberry Pi covers it

How deep it goes
Explains timed and indefinite waits, return values, key comparisons, and GUI event handling without descending into OpenCV internals.
Examples
Demonstrates a camera snapshot loop and a face-detection preview controlled by Q, Esc, space, or any key.
What it assumes
Assumes Python and basic OpenCV image or camera display code, while demonstrating keyboard codes and event-loop placement.
What you can do after
Apply it via OpenCV to build responsive previews, trigger actions from keys, and close image windows predictably.
How it connects
Connects keyboard input with OpenCV windows, camera capture, image display, and event loops.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build Your Own Robot: Using Python, CRICKIT, and Raspberry Pi. The section links point to the parts of the book it draws on.