Sub topic 12
Measuring Per-Frame Time and Keeping Up with Live Video
This chapter assumes you know basic Python loops and try/finally, NumPy array shapes, and how cv2.VideoCapture returns frames. You also need OpenCV installed and a camera or video source available.
A live camera produces frames at a target rate. For example, a camera running at 30 frames per second (FPS) provides one frame every about 33.3 milliseconds. Your processing pipeline must finish reading, processing, displaying, and any other work within that time if it should keep up.
Measuring the processing time
Use time.perf_counter() for elapsed-time measurements. It is a monotonic clock designed for timing code. Record the time immediately before processing and subtract it afterward.
import time
import cv2
cap = cv2.VideoCapture(0)
if not cap.isOpened():
raise RuntimeError("Could not open camera 0")
try:
while True:
start = time.perf_counter()
ok, frame = cap.read()
if not ok:
print("Camera read failed")
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
edges = cv2.Canny(blurred, 100, 200)
cv2.imshow("edges", edges)
elapsed = time.perf_counter() - start
processing_fps = 1.0 / elapsed if elapsed > 0 else float("inf")
print(
f"frame time: {elapsed * 1000:.1f} ms, "
f"processing rate: {processing_fps:.1f} FPS"
)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
finally:
cap.release()
cv2.destroyAllWindows()The measured time includes the capture read, image processing, display call, and key polling. This is often the useful number because all of these operations affect how quickly the loop can handle frames.
A processing rate of 40 FPS does not guarantee that the camera is being handled at 40 FPS. The camera may produce 30 FPS, so the source rate is still 30 FPS. Conversely, a measured rate of 20 FPS is too slow for a 30 FPS camera.
The frame-time budget
The time available for one frame is approximately:
frame period = 1 / source FPS
At 30 FPS, the budget is about 33.3 milliseconds. At 60 FPS, it is about 16.7 milliseconds.
The pipeline falls behind when its average frame time is longer than the camera's frame period. Frames may then wait in a driver or backend buffer. The displayed image becomes increasingly old even though the loop continues running. This delay is called latency.
Ways to keep up
When processing is too slow, choose a strategy based on the application:
- Reduce the camera resolution or requested FPS.
- Resize frames before expensive operations.
- Process a region of interest instead of the entire image.
- Use simpler algorithms or optimized OpenCV operations.
- Skip frames when every frame is not required.
- Drop old buffered frames when low latency matters more than processing every frame.
- Move capture and processing to separate threads or processes, while controlling the queue size.
Skipping frames increases the time between analyzed frames, but it can prevent the application from becoming permanently delayed. For a security display, the newest frame is often more useful than every historical frame. For measurement or recording, dropping frames may be unacceptable.
The waitKey call also affects timing. In a display loop, waitKey(1) gives OpenCV a chance to refresh the window and waits briefly for input. A larger delay directly adds time to each iteration.
Check your result
Compare measured frame time with the source FPS. For a camera that reports 30 FPS, aim for a sustained frame time below 33.3 milliseconds, while leaving room for timing variation. If the camera reports zero FPS, use a known configured rate or measure the arrival rate over a longer interval.
Exercise
A camera runs at 25 FPS, and your loop takes 50 milliseconds per frame. What problem should you expect, and name one way to reduce it.
Show answer
The loop can process only about 20 FPS, so frames will accumulate and latency will grow. Reduce the resolution, simplify processing, or drop old frames.