Sub topic 5
Showing Frames and Quitting with a Key Press
This chapter assumes you know basic Python loops and functions, NumPy array shapes, and how cv2.VideoCapture returns (ok, frame) from cap.read(). You also need a desktop environment where OpenCV can create windows. A notebook, server, or container without a display may not support cv2.imshow.
How OpenCV displays a frame
cv2.imshow(window_name, image) schedules an image for display in a named window. The first argument is a string used as the window's identifier. The second argument is a NumPy array containing the image.
Displaying a frame is a two-step operation:
- Call
imshowto provide the latest image. - Call
waitKeyto process window events and give the operating system time to refresh the window.
Without waitKey, the window may remain blank or stop responding. waitKey(delay) waits for approximately delay milliseconds and returns the code for a key pressed during that interval. If no key is pressed, it usually returns -1.
A small delay such as 1 is common for video. It requests a short wait while allowing the window system to handle repainting and keyboard input. A larger delay makes the video appear slower.
A complete display loop
The following program displays a video until it reaches the end or the user presses q or Escape.
import cv2
cap = cv2.VideoCapture("input.mp4")
if not cap.isOpened():
raise RuntimeError("Could not open input.mp4")
try:
while True:
ok, frame = cap.read()
if not ok:
break
cv2.imshow("video", frame)
key = cv2.waitKey(1) & 0xFF
if key == ord("q") or key == 27:
break
finally:
cap.release()
cv2.destroyAllWindows()The expression ord("q") converts the character q into its integer key code. The value 27 is the usual code for Escape. The bitwise operation & 0xFF keeps the part of the return value used by many OpenCV backends. It is a common portability habit, especially when code runs on different operating systems.
The finally block runs whether the loop ends normally or an exception occurs. cap.release() closes the video source. cv2.destroyAllWindows() closes every OpenCV-created window.
Choosing a window and delay
The window name is also useful when displaying several images. For example, you might show an original frame and its grayscale version separately:
cv2.imshow("original", frame)
cv2.imshow("gray", gray)
cv2.waitKey(1)Both calls should happen before the same waitKey call. Calling waitKey once per frame gives all OpenCV windows a chance to update.
A delay of 1 does not guarantee that the program runs at exactly the video's original frame rate. The total time for reading, processing, displaying, and waiting determines the actual speed. For a file, the loop may run faster or slower than real time. For a camera, slow processing can cause delayed or dropped frames.
Common display problems
- If no window appears, check that the program runs with a graphical display and that OpenCV was not installed in a headless-only environment.
- If the window freezes, verify that
waitKeyis called inside the loop. - If the program never exits at the end of a file, check that the loop tests
okbefore usingframe. - If a camera stays busy after the program stops, make sure
cap.release()runs. - If a window remains open after an early exit, call
cv2.destroyAllWindows()during cleanup.
Exercise
Why does a video display loop usually call cv2.waitKey(1) after cv2.imshow, and what should the program do when the returned key code matches Escape?
Show answer
waitKey processes window events, refreshes the display, and checks for keyboard input. When Escape is detected, the program should break from the loop and release the capture before destroying the windows.