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
