Sub topic 2
Showing frames and quitting with a key press
This chapter assumes you know basic Python, can index NumPy arrays, and have opencv-python installed. You should also know that a video is a sequence of frames shown at a set rate.
Showing frames and quitting with a key press
cv2.imshow draws a frame in a window. cv2.waitKey(ms) pauses for that many milliseconds and returns the code of any key pressed, or -1 if none was pressed. Masking with 0xFF keeps the low byte, which makes the comparison work across platforms.
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)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
finally:
cap.release()
cv2.destroyAllWindows()Processing each frame: grayscale, blur and edges
Each frame is a NumPy array in BGR order (blue, green, red). A common pipeline converts to grayscale, blurs to reduce noise, and then finds edges with the Canny detector.
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
edges = cv2.Canny(blurred, 100, 200)Canny returns a single-channel image. Convert it back to three channels before passing it to a color writer.
Reading and setting capture properties
cap.get(prop) reads a property, and cap.set(prop, value) requests a new value. The driver may ignore a request, so check the result.
| Property | Meaning | Notes |
|---|---|---|
| `CAP_PROP_FRAME_WIDTH` | Frame width in pixels | Returned as a float |
| `CAP_PROP_FPS` | Frames per second | Some sources report 0 |
| `CAP_PROP_FRAME_COUNT` | Total frames in a file | Often unavailable for cameras |
| `CAP_PROP_POS_FRAMES` | Index of the next frame to read | Seeking may be approximate |
fps = cap.get(cv2.CAP_PROP_FPS) or 30.0 # fall back when the source reports 0
cap.set(cv2.CAP_PROP_POS_FRAMES, 100) # next read returns frame 100Working with cameras: indexes, backends and requested settings
cv2.VideoCapture(0) opens the first camera. The index depends on the system and can change when devices are added. On Windows, passing a backend such as cv2.CAP_DSHOW as the second argument can improve startup. Settings are requests: read them back to find the actual values.
cap = cv2.VideoCapture(0)
if not cap.isOpened():
raise RuntimeError("Could not open camera 0")
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)
actual_w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
actual_h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
print(f"Camera delivers {actual_w}x{actual_h}")
cap.release()Exercise
Why does the loop call waitKey(1) instead of waitKey(0), and what does the q check protect against?
Show answer
waitKey(1) waits 1 ms and returns, so the loop keeps reading frames and the window refreshes. waitKey(0) would block the loop until a key is pressed. The q check gives the user a way to stop the loop, and the finally block then releases the capture and closes the window.