Sub topic 5
Showing frames and quitting with a key press
This chapter covers how OpenCV puts frames on screen and how a loop reads keyboard input. It assumes you can write a Python loop with try/finally, you know that a frame is a NumPy array, and you have opencv-python installed (not the -headless build, which has no window support).
What imshow and waitKey do
cv2.imshow(name, image) draws an image in a window called name. If no window with that name exists, OpenCV creates one. If it exists, the image replaces the previous content.
imshow does not repaint the screen by itself. The window is drawn and updated by the GUI event loop, and OpenCV only runs that loop inside cv2.waitKey(). Without a waitKey call, the window may stay blank, look frozen, or never appear.
cv2.waitKey(delay) does two jobs:
- It lets the GUI process pending events, which includes repainting the window.
- It waits up to
delaymilliseconds for a key press and returns the key code, or-1if no key was pressed in that time.
The minimal display loop
This loop reads a file, converts each frame to grayscale, and shows it. Pressing q quits.
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 # end of file or a failed read
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow("gray", gray)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
finally:
cap.release()
cv2.destroyAllWindows()Each part of the key check has a purpose.
waitKey(1)waits at most 1 ms. The loop is then limited by how fast you read and process frames, not by the wait.& 0xFFkeeps only the lowest 8 bits of the return value. On some platforms and builds,waitKeyreturns a larger integer with extra bits set, for example when a modifier such as Num Lock is active. Masking makes the comparison reliable for ordinary keys.ord("q")turns the character into its integer code (113), so it can be compared with the masked value.-1is0xFFFFFFFFin a 32-bit view, so-1 & 0xFFis255. That never equals the code of a normal letter, so "no key" falls through correctly.
The delay argument
The value you pass to waitKey changes the behavior a lot.
| Call | Behavior |
|---|---|
| `waitKey(1)` | Poll for 1 ms, then continue. Shows frames as fast as the loop can run. |
| `waitKey(30)` | Wait up to 30 ms. Caps the display near 33 frames per second if processing is quick. |
| `waitKey(0)` | Block until a key is pressed. Useful for showing a single image or stepping frame by frame. |
A key press ends the wait early. So waitKey(30) can return sooner than 30 ms, and the loop then runs a little faster for that iteration.
Playing at the file's frame rate
With waitKey(1) a short video plays far faster than real time, because nothing slows the loop. To approximate real-time playback, derive the delay from the file's frame rate and subtract the time already spent on the frame.
import time
import cv2
cap = cv2.VideoCapture("input.mp4")
if not cap.isOpened():
raise RuntimeError("Could not open input.mp4")
fps = cap.get(cv2.CAP_PROP_FPS) or 30.0 # some sources report 0
frame_budget = 1.0 / fps
try:
while True:
start = time.perf_counter()
ok, frame = cap.read()
if not ok:
break
cv2.imshow("playback", frame)
spent = time.perf_counter() - start
delay_ms = max(1, int((frame_budget - spent) * 1000))
if cv2.waitKey(delay_ms) & 0xFF == ord("q"):
break
finally:
cap.release()
cv2.destroyAllWindows()The max(1, ...) matters. A delay of 0 would block forever, and a negative number behaves unpredictably. If a frame took longer than its budget, you still want waitKey to run once so the window repaints and the key check happens.
This is an approximation. waitKey has a granularity that depends on the operating system, so playback may drift a few percent from real time. For accurate pacing against a clock, track absolute target times instead of per-frame delays. Chapter 12 covers timing in more detail.
Reacting to more than one key
You are not limited to a single quit key. Store the return value once, then compare it several times. Calling waitKey twice in one iteration would consume two separate waits and lose key presses.
import cv2
cap = cv2.VideoCapture("input.mp4")
if not cap.isOpened():
raise RuntimeError("Could not open input.mp4")
paused = False
frame = None
try:
while True:
if not paused:
ok, frame = cap.read()
if not ok:
break
cv2.imshow("player", frame)
key = cv2.waitKey(30) & 0xFF
if key == ord("q"):
break
elif key == ord(" "):
paused = not paused
elif key == ord("s") and frame is not None:
cv2.imwrite("snapshot.png", frame)
print("Saved snapshot.png")
finally:
cap.release()
cv2.destroyAllWindows()When paused, the loop keeps calling imshow and waitKey with the same frame. That keeps the window responsive, so you can still move it, close it, or press a key. Skipping the call entirely would freeze the window and make the process look hung.
Key codes and their limits
waitKey is a simple tool, and its limits matter in practice.
- Printable characters work as expected:
ord("a"),ord(" "),ord("1"). Letters are case-sensitive, soord("q")does not match a capitalQ. If you want both, compare against both, or usechr(key).lower()after checking thatkey != 255. - Special keys such as arrows, function keys, and Escape vary by platform and GUI backend. Escape is
27almost everywhere. Arrow keys often return codes above 255, and the masked& 0xFFform can collapse several keys onto the same value. If you need arrows, print the unmasked value on your system and compare against that. - Key release and held keys are not reported. You only learn that a key was pressed during a wait, not when it was released.
- Focus matters. The window must have keyboard focus. If your terminal has focus instead, key presses go there and
waitKeyreturns-1. This is the most common reason "pressing q does nothing".
To find the codes on your machine, run this small probe and press keys in the window.
import cv2
import numpy as np
canvas = np.zeros((120, 400, 3), dtype=np.uint8)
cv2.imshow("probe", canvas)
print("Press keys in the window. Press Escape (27) to stop.")
while True:
raw = cv2.waitKey(0)
print(f"raw={raw} masked={raw & 0xFF}")
if raw & 0xFF == 27:
break
cv2.destroyAllWindows()Window management
You can create a window explicitly before showing anything. This lets you set its behavior.
import cv2
cv2.namedWindow("view", cv2.WINDOW_NORMAL) # resizable window
cv2.resizeWindow("view", 960, 540)
cv2.moveWindow("view", 50, 50)cv2.WINDOW_AUTOSIZE(the default) sizes the window to the image and does not let you resize it by hand.cv2.WINDOW_NORMALallows resizing. The image is scaled to fit, which is useful for large frames on a small screen. Scaling happens at display time, so the frame array you process is unchanged.cv2.destroyWindow("view")closes one window, andcv2.destroyAllWindows()closes all of them.
Even after destroyAllWindows(), some GUI backends, notably on macOS and some Linux setups, only close the window after another waitKey runs. If a window lingers after your script reaches the end of the finally block, add cv2.waitKey(1) after the destroy call.
Detecting that the user closed the window
Clicking the window's close button does not stop your loop. The next imshow simply creates a new window. To stop when the window is closed, check its visibility property.
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("view", frame)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
if cv2.getWindowProperty("view", cv2.WND_PROP_VISIBLE) < 1:
break # user closed the window
finally:
cap.release()
cv2.destroyAllWindows()getWindowProperty returns a value below 1 when the window is no longer visible. Some backends raise an error if the window never existed, so call it only after at least one imshow.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Window is gray or blank, or never appears | No `waitKey` call in the loop | Call `waitKey(1)` after every `imshow` |
| Pressing `q` does nothing | Terminal has focus, not the window | Click the image window first |
| Pressing `q` works only sometimes | `waitKey(1)` is called rarely because processing is slow | Reduce per-frame work, or accept the latency |
| Window freezes while paused | Loop skips `imshow` and `waitKey` | Keep calling both while paused |
| Video plays too fast | `waitKey(1)` with no pacing | Use the frame-rate delay shown above |
| `cv2.error` mentioning "The function is not implemented" | Headless OpenCV build installed | Install `opencv-python`, not `opencv-python-headless` |
| `imshow` fails over SSH or in a container | No display available | Write frames with `VideoWriter` or `imwrite` instead |
Summary of the pattern
A reliable display loop has these parts: a read with an end check, an imshow on every iteration, exactly one waitKey per iteration whose result is stored and masked with 0xFF, and a finally block that releases the capture and closes the windows. The next chapter builds on this loop by adding per-frame processing between the read and the display.
Exercise
A learner's loop calls cv2.imshow("v", frame) for every frame but never calls waitKey. The script runs, yet the window stays blank. Then they add if cv2.waitKey(1) == ord("q"): break and the window shows video, but pressing q still sometimes fails on their machine. Explain why the window was blank, and give two separate changes that make the quit check more robust.
Show answer
The window was blank because imshow only queues the image. The GUI event loop that repaints the window runs only inside waitKey, so without it nothing is drawn. For the quit check, first mask the return value with & 0xFF so extra bits (for example from Num Lock) do not break the comparison with ord("q"). Second, make sure the image window has keyboard focus, because key presses sent to the terminal make waitKey return -1. Comparing against both ord("q") and ord("Q") also helps if Caps Lock is on.
Exercise
You want a player that plays a 25 fps file at roughly real-time speed, pauses on the space bar, and still responds to q while paused. Which calls must run in every loop iteration, even while paused, and why is waitKey(0) a poor choice for the delay?
Show answer
imshow and waitKey must run every iteration, including while paused, so the window stays responsive and keys are still read. Only cap.read() is skipped while paused. waitKey(0) blocks until a key is pressed, so playback would advance only on key presses. Use a delay near 1000 / 25 = 40 ms, reduced by the time the frame already took and never below 1.