Sub topic 10
Releasing resources and handling failures
This chapter assumes you can write the read loop from the earlier chapters (ok, frame = cap.read()), that you know Python's try/finally, and that you have opencv-python installed. It covers what must be released, which failures OpenCV hides from you, and how to structure code so cleanup always runs.
What you are holding
Three kinds of resource need explicit cleanup.
- A
VideoCaptureholds an open file handle or a camera device, plus a decoder with internal buffers. A camera is usually exclusive: while your process holds it, other programs (and your own next run) may fail to open it. - A
VideoWriterholds an open output file and an encoder. Many containers, MP4 in particular, write index data when the file is finalized. If the writer is never released, the file can be truncated or unplayable. - HighGUI windows created by
imshowbelong to the GUI backend. They stay on screen until you destroy them, and on some platforms the window only closes after furtherwaitKeycalls.
Python's garbage collector will eventually release these objects when they go out of scope. You should not depend on it. When it runs is not defined, an exception traceback can keep the objects alive, and a long-running process may never reach the point where they are collected.
How OpenCV reports failure
OpenCV's video API mostly does not raise exceptions. It returns status values you must check.
| Situation | What OpenCV does | What you must check |
|---|---|---|
| Wrong path or missing codec | `VideoCapture(...)` returns an object; no exception | `cap.isOpened()` |
| Camera in use or index wrong | Same: object returned, not opened | `cap.isOpened()` |
| End of file | `read()` returns `(False, None)` | `ok` |
| Camera unplugged or driver error | `read()` returns `(False, None)` | `ok` |
| Output path not writable or codec unavailable | `VideoWriter(...)` returns an object | `out.isOpened()` |
| Frame size differs from writer size | `write()` returns without error, and the frame may be dropped or the file corrupted | Compare sizes yourself |
| No GUI available (headless server) | `imshow` raises `cv2.error` | Catch it, or skip display |
Every row except the last is silent. A script that skips these checks does not crash. It produces an empty output file, or loops forever on None frames.
You can see the first row directly:
import cv2
cap = cv2.VideoCapture("does_not_exist.mp4")
print("opened:", cap.isOpened()) # False, no exception raised
ok, frame = cap.read()
print("read:", ok, frame) # False None
cap.release() # safe to call on a capture that never openedCalling release() on a capture that never opened is harmless, and calling it twice is also harmless. That is why it is safe to put in a finally block unconditionally.
The try/finally pattern
The basic pattern is the one from the first read-loop example:
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
# ... process frame ...
finally:
cap.release()
cv2.destroyAllWindows()Note where the try begins: after the isOpened() check. If the open failed, there is nothing useful to run in the loop, and raising before the try keeps the error message clear. release() on an unopened capture would be harmless, so putting the check inside the try would also work. Pick one and keep it consistent.
finally runs when the loop ends normally, when you break, when your processing code raises, and when the user presses Ctrl+C (which raises KeyboardInterrupt). It does not run if the process is killed with SIGKILL or the interpreter crashes. A hard kill of a process that is writing a file can still leave a damaged output.
Wrapping the pattern in context managers
VideoCapture and VideoWriter do not implement __enter__ and __exit__, so with cv2.VideoCapture(...) as cap: fails. A small helper built with contextlib.contextmanager gives you the same shape and puts the open check and the release in one place.
from contextlib import contextmanager
import cv2
@contextmanager
def open_capture(source):
cap = cv2.VideoCapture(source)
try:
if not cap.isOpened():
raise RuntimeError(f"Could not open {source!r}")
yield cap
finally:
cap.release()
@contextmanager
def open_writer(path, fourcc, fps, size):
out = cv2.VideoWriter(path, fourcc, fps, size)
try:
if not out.isOpened():
raise RuntimeError(f"Could not open writer for {path!r}")
yield out
finally:
out.release()Here is a complete pipeline that uses both helpers. It checks every frame's size before writing, because the writer will not do it for you.
import cv2
from contextlib import contextmanager
@contextmanager
def open_capture(source):
cap = cv2.VideoCapture(source)
try:
if not cap.isOpened():
raise RuntimeError(f"Could not open {source!r}")
yield cap
finally:
cap.release()
@contextmanager
def open_writer(path, fourcc, fps, size):
out = cv2.VideoWriter(path, fourcc, fps, size)
try:
if not out.isOpened():
raise RuntimeError(f"Could not open writer for {path!r}")
yield out
finally:
out.release()
def edge_video(src, dst):
with open_capture(src) as cap:
fps = cap.get(cv2.CAP_PROP_FPS) or 30.0
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
with open_writer(dst, fourcc, fps, (width, height)) as out:
written = 0
while True:
ok, frame = cap.read()
if not ok:
break
if frame.shape[:2] != (height, width):
raise ValueError(
f"Frame {written} is {frame.shape[1]}x{frame.shape[0]}, "
f"expected {width}x{height}"
)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(cv2.GaussianBlur(gray, (5, 5), 0), 100, 200)
out.write(cv2.cvtColor(edges, cv2.COLOR_GRAY2BGR))
written += 1
return written
if __name__ == "__main__":
print("frames written:", edge_video("input.mp4", "edges.mp4"))The nesting order matters. The writer is the inner block, so it is released first and finalizes the file while the capture is still valid. The capture is released last. If open_writer raises, the with open_capture block still releases the capture on the way out.
The size check compares frame.shape[:2], which is (height, width), against the writer's (width, height) order. Mixing up these two orders is the most common cause of a writer that opens fine and produces an unplayable file.
The lifecycle at a glance
Telling end of file from a failed read
read() returns False in both cases, so the loop cannot tell them apart by ok alone. For a file, you can compare the number of frames you actually read to CAP_PROP_FRAME_COUNT. If you read far fewer frames than reported, the file is probably truncated or has a corrupt section.
import cv2
cap = cv2.VideoCapture("input.mp4")
if not cap.isOpened():
raise RuntimeError("Could not open input.mp4")
expected = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
count = 0
try:
while True:
ok, frame = cap.read()
if not ok:
break
count += 1
finally:
cap.release()
print(f"read {count} of about {expected} frames")
if expected > 0 and count < 0.95 * expected:
print("Warning: stopped early, the file may be damaged")Treat the frame count as an estimate. Some containers report it inaccurately, and some streams report zero or a negative number. The 95 percent threshold above is a heuristic, not a rule.
For a camera there is no expected total, so you need a different policy. A single failed read can be transient, for example a dropped USB packet. A policy that works well is to tolerate a few failures in a row and give up after that:
import time
import cv2
MAX_FAILURES = 5
cap = cv2.VideoCapture(0)
if not cap.isOpened():
raise RuntimeError("Could not open camera 0")
failures = 0
try:
while True:
ok, frame = cap.read()
if not ok:
failures += 1
if failures >= MAX_FAILURES:
raise RuntimeError(f"Camera failed {failures} reads in a row")
time.sleep(0.05)
continue
failures = 0 # any success resets the count
cv2.imshow("camera", frame)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
finally:
cap.release()
cv2.destroyAllWindows()Resetting the counter on success is what makes this a count of consecutive failures. Without the reset, a camera that fails once an hour would eventually stop your program.
Common mistakes
- Forgetting
release()on the writer. The script finishes, the file exists, and the player rejects it. Always release the writer, and do it before you try to open the output. - Writing frames of the wrong size or channel count. A grayscale frame passed to a default color writer is silently lost. Convert with
cv2.cvtColor(edges, cv2.COLOR_GRAY2BGR)as in the earlier chapter, or create the writer withisColor=False. - Using the frame after a failed read. When
okisFalse,frameisNone. Callingcv2.cvtColor(None, ...)raises acv2.errorthat points at the conversion rather than at the real cause. - Calling
destroyAllWindows()in a headless environment. On builds without GUI support,imshowanddestroyAllWindowscan raisecv2.error. For servers and containers, installopencv-python-headlessand write frames to a file instead of displaying them. - Catching everything. A bare
except:around the loop hidesKeyboardInterruptand real bugs. Letfinallydo the cleanup and let exceptions propagate. - Leaving the camera held after a crash in a notebook. In Jupyter, an exception inside the loop can leave the capture open until the kernel restarts. The context managers above avoid this because the release runs even when the cell raises.
Checklist
- Check
isOpened()after everyVideoCaptureandVideoWriterconstruction. - Check
okafter everyread(), and never touchframewhen it isFalse. - Release the writer before the capture, inside
finallyor a context manager. - Verify frame size against the writer's
(width, height)before everywrite(). - Decide on a failure policy for cameras: how many consecutive failed reads you tolerate.
- Call
cv2.destroyAllWindows()once, in thefinallyblock, if you usedimshow.
Exercise
A script reads "input.mp4", converts each frame to grayscale with cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY), and writes it to "gray.mp4" using a VideoWriter created with the default isColor setting. The script runs without errors, but gray.mp4 is tiny and will not play. Name two likely causes and the fix for each.
Show answer
First, the writer was created for color frames (default isColor=True) but is given single-channel grayscale frames, which are silently dropped. Fix: convert each frame back with cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR) before out.write(), or create the writer with isColor=False. Second, out.release() may never have been called, so the file was not finalized. Fix: release the writer in a finally block or a context manager. A third possible cause is a size mismatch, so also confirm the writer was created with (width, height), not (height, width), and check out.isOpened() right after creating it.