Sub topic 12
Measuring per-frame time and keeping up with live video
This chapter assumes you can write the cap.read() loop from earlier chapters and apply per-frame operations such as grayscale conversion, blurring and Canny edge detection. It also assumes you know how to open a camera by device index. Here you will measure how long each frame takes and decide what to do when the pipeline is too slow.
The frame budget
A source with a frame rate of F frames per second delivers one frame every 1000 / F milliseconds. That interval is your frame budget. If read, process and display together take less than the budget, you keep up. If they take more, you fall behind.
| Source rate | Budget per frame |
|---|---|
| 15 fps | 66.7 ms |
| 24 fps | 41.7 ms |
| 30 fps | 33.3 ms |
| 60 fps | 16.7 ms |
Files and cameras behave differently when you exceed the budget:
- A file has no deadline. A slow loop takes longer than the video's duration, but every frame is still processed in order. Nothing is lost.
- A camera produces frames in real time whether or not you are ready. A slow loop forces the system to buffer frames or drop them. Either way, what you see lags behind what the camera sees.
Timing with perf_counter
Use time.perf_counter() to time code. It is a monotonic clock with the highest resolution available. time.time() can jump when the system clock is adjusted, so it is a poor choice for short intervals.
Time the read and the processing separately. On a camera, cap.read() blocks until the next frame arrives. A slow read can therefore mean "waiting for the camera", not "slow decoding". If you time the whole loop as one block, you cannot tell the two apart.
import time
from collections import deque
import cv2
cap = cv2.VideoCapture("input.mp4")
if not cap.isOpened():
raise RuntimeError("Could not open input.mp4")
source_fps = cap.get(cv2.CAP_PROP_FPS) or 30.0
budget_ms = 1000.0 / source_fps
read_ms = deque(maxlen=60) # rolling window of the last 60 frames
work_ms = deque(maxlen=60)
frames = 0
over_budget = 0
try:
while True:
t0 = time.perf_counter()
ok, frame = cap.read()
t1 = time.perf_counter()
if not ok:
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
edges = cv2.Canny(blurred, 100, 200)
t2 = time.perf_counter()
read_ms.append((t1 - t0) * 1000)
work_ms.append((t2 - t1) * 1000)
frames += 1
if work_ms[-1] > budget_ms:
over_budget += 1
if frames % 60 == 0:
print(f"frame {frames}: read {sum(read_ms) / len(read_ms):.1f} ms, "
f"work {sum(work_ms) / len(work_ms):.1f} ms, "
f"budget {budget_ms:.1f} ms")
finally:
cap.release()
print(f"{frames} frames, {over_budget} over budget")The rolling window smooths out single-frame spikes, such as a keyframe that decodes slowly. The over_budget counter tells you how often the budget was actually missed. An average under the budget can still hide a frame in every few that blows past it.
Reading the numbers
- Work time below the budget: you have headroom. On a camera, the loop will run at the camera's rate because
read()waits for the next frame. - Work time above the budget: the loop cannot keep up with the source. Your effective FPS is roughly 1000 / (read time + work time).
- Read time large on a file: decoding is the bottleneck. Large resolutions and expensive codecs such as H.265 cost more per frame.
- Read time large on a camera: this is often just waiting for the frame. Compare it with the budget minus your work time.
Do not forget the display
cv2.imshow() and cv2.waitKey() also take time. waitKey(1) waits at least 1 ms, and the real cost depends on the platform and the window system. If you only time the processing and not the display, your estimate will be optimistic. For benchmarks, run the loop without imshow and compare the result with the full loop. The difference is your display cost.
Other measurement habits:
- Ignore the first few frames. Caches are cold, and cameras often adjust exposure at start.
- Measure on realistic input at the real resolution. Timing a 640x480 test clip tells you little about a 1920x1080 camera.
- Print sparingly. Printing a line every frame can itself take noticeable time in some terminals.
What happens when you fall behind a camera
When processing is slower than the budget, frames accumulate in the driver or backend queue. Two things can happen, depending on the backend:
- A buffer builds up. Each
read()returns an older frame than the camera is producing now. The picture is smooth but delayed, and the delay can grow to seconds. - Old frames are overwritten.
read()returns recent frames but skips some. The picture is current but choppy.
You can ask for a smaller buffer with cap.set(cv2.CAP_PROP_BUFFERSIZE, 1). Only some backends honor it, so read the value back with cap.get and test with a real camera. Do not rely on it as your only fix.
| Symptom | Likely cause | Fix |
|---|---|---|
| Live view lags more and more | Work time over budget, buffer growing | Reduce work, skip frames, or read in a thread |
| Live view is choppy but current | Frames overwritten in the buffer | Accept it, or reduce work to reach the full rate |
| File processing slower than the video's duration | Work time over budget | Fine for offline use; optimize only if needed |
| Effective FPS exactly at the camera rate | Under budget | Nothing to fix |
Reducing the work per frame
Try these in order of cost and benefit:
- Shrink the frame before heavy work. Cost scales roughly with the pixel count.
cv2.resize(frame, None, fx=0.5, fy=0.5)leaves a quarter of the pixels. - Convert to grayscale early. Many operations need only one channel.
- Use smaller kernels. A 5x5 Gaussian blur is much cheaper than a 21x21 one.
- Process every Nth frame. Many tasks, such as detecting a person walking, do not need every frame.
- Avoid per-frame allocation in your own code, such as repeatedly building new large arrays in Python loops. Prefer vectorized NumPy and OpenCV calls.
Skipping frames with grab and retrieve
cap.read() is cap.grab() followed by cap.retrieve(). grab() advances to the next frame, and retrieve() decodes it into an array. If you only need every Nth frame, call grab() on the others and skip the retrieve(). On a camera, this keeps you drawing from the latest frames. On a file, the saving is smaller, because most codecs still have to decode each frame internally.
import cv2
STEP = 3 # process every third frame
cap = cv2.VideoCapture(0)
if not cap.isOpened():
raise RuntimeError("Could not open camera 0")
count = 0
try:
while True:
if not cap.grab():
print("Camera grab failed")
break
count += 1
if count % STEP != 0:
continue
ok, frame = cap.retrieve()
if not ok:
break
small = cv2.resize(frame, None, fx=0.5, fy=0.5)
edges = cv2.Canny(cv2.cvtColor(small, cv2.COLOR_BGR2GRAY), 100, 200)
cv2.imshow("edges", edges)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
finally:
cap.release()
cv2.destroyAllWindows()Always processing the newest frame with a reader thread
If the work cannot be made cheap enough, you can still avoid lag. Run cap.read() in a background thread that keeps only the newest frame, and let the main loop take that frame whenever it is ready. The camera is drained at its full rate, so the buffer never builds up. The main loop skips frames it has no time for.
import threading
import time
import cv2
class LatestFrameReader:
"""Reads a source in a thread and keeps only the newest frame."""
def __init__(self, source):
self.cap = cv2.VideoCapture(source)
if not self.cap.isOpened():
raise RuntimeError(f"Could not open {source!r}")
self._lock = threading.Lock()
self._frame = None
self._index = 0
self._stop = threading.Event()
self._thread = threading.Thread(target=self._run, daemon=True)
self._thread.start()
def _run(self):
while not self._stop.is_set():
ok, frame = self.cap.read()
if not ok:
self._stop.set()
break
with self._lock:
self._frame = frame
self._index += 1
@property
def running(self):
return not self._stop.is_set()
def latest(self):
with self._lock:
return self._index, self._frame
def stop(self):
self._stop.set()
self._thread.join(timeout=2.0)
self.cap.release()
reader = LatestFrameReader(0)
last_index = 0
dropped = 0
try:
while reader.running:
index, frame = reader.latest()
if frame is None or index == last_index:
time.sleep(0.001) # no new frame yet
continue
dropped += index - last_index - 1
last_index = index
edges = cv2.Canny(cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY), 100, 200)
cv2.imshow("edges", edges)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
finally:
reader.stop()
cv2.destroyAllWindows()
print(f"Skipped {dropped} frames")The dropped counter turns the problem into a number. A value near zero means the main loop keeps up. A large value means it skips many frames, so reduce the work.
Each frame in the reader is a separate array, because read() allocates a new one on every call. The reader replaces its reference and never modifies the old array, so the main loop can use the frame it received safely. If you do share one array between threads, copy it first.
Common errors
- Timing only
cv2.Canny. Conversion, resizing and display are also in the loop. Time the whole path you will run. - Trusting
CAP_PROP_FPSfor cameras. Many cameras report 0 or a nominal value. Measure the actual rate by counting frames over a few seconds. - Comparing runs with different window states. A visible
imshowwindow, a covered window and no window can differ in cost. - Using the mean alone. Occasional slow frames matter for live video. Track the maximum or the count of over-budget frames, as the first example does.
- Forgetting to stop the thread. A reader thread still holding the camera keeps the device busy after your program ends its loop. Call
stop()infinally.
Exercise
A 30 fps camera loop reports a read time of 28 ms and a work time of 12 ms per frame, and the live window falls further behind the real scene over time. Explain why, and name two changes that would fix the lag.
Show answer
The budget is 33.3 ms. Read plus work is 40 ms, so the loop takes longer than a frame interval and the buffer grows. (If the 28 ms read time were pure waiting for the camera, the loop would be under budget at about 12 ms of work. Here the read time includes real decoding or transfer cost, so it counts.) Fixes: reduce the work, for example by resizing the frame to half size before processing, or skip frames with grab() and retrieve(). Reading in a background thread that keeps only the newest frame also removes the lag, at the cost of skipped frames.
Exercise
Why should you time cap.read() and the processing separately instead of timing the whole loop body once?
Show answer
On a camera, cap.read() blocks until the next frame arrives, so its time can be mostly waiting. Timing the two parts separately shows how much of the budget your processing uses (the headroom) and whether the time goes to reading or to your own code. A single combined timing hides this and makes a loop that is well under budget look the same as one that is close to the limit.
Exercise
Write the formula for the frame budget in milliseconds for a source with a given fps, and give the budget for 25 fps.
Show answer
budget_ms = 1000 / fps. For 25 fps it is 1000 / 25 = 40 ms.