Sub topic 10
Releasing Resources and Handling Failures
This chapter assumes you know basic Python loops, try/finally, NumPy array shapes, and the OpenCV VideoCapture and VideoWriter classes. The examples use a video file, but the same cleanup rules apply to a camera.
OpenCV uses operating-system resources when it opens a file, camera, or display window. A capture object may hold a file handle or a camera device. A writer may hold an output file until its container is finalized. A window also needs to be closed. Releasing these resources makes your program predictable and lets other applications use the camera or files afterward.
Check every resource before using it
Creating an object does not guarantee that it opened successfully. Check isOpened() immediately:
import cv2
cap = cv2.VideoCapture("input.mp4")
if not cap.isOpened():
raise RuntimeError("Could not open input.mp4")The same check applies to a VideoWriter. A wrong codec, unsupported file extension, or invalid frame size can cause the writer to fail:
writer = cv2.VideoWriter(
"output.mp4",
cv2.VideoWriter_fourcc(*"mp4v"),
30.0,
(640, 480),
)
if not writer.isOpened():
cap.release()
raise RuntimeError("Could not open output.mp4 for writing")Failing early is safer than continuing with an object that silently discards frames.
Use `finally` for cleanup
A finally block runs whether the loop ends normally, a key stops it, or an exception occurs. Put cleanup there instead of relying on the program reaching the last line.
import cv2
cap = cv2.VideoCapture("input.mp4")
if not cap.isOpened():
raise RuntimeError("Could not open input.mp4")
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = cap.get(cv2.CAP_PROP_FPS) or 30.0
writer = cv2.VideoWriter(
"gray.mp4",
cv2.VideoWriter_fourcc(*"mp4v"),
fps,
(width, height),
)
if not writer.isOpened():
cap.release()
raise RuntimeError("Could not create gray.mp4")
try:
while True:
ok, frame = cap.read()
if not ok:
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
gray_bgr = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
writer.write(gray_bgr)
cv2.imshow("gray", gray)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
finally:
cap.release()
writer.release()
cv2.destroyAllWindows()cap.release() closes the input source. writer.release() finishes the output file and closes it. cv2.destroyAllWindows() closes windows created by OpenCV's high-level GUI functions.
Handle failed reads deliberately
A failed read does not always mean the same thing:
- For a file,
ok == Falseusually means the end of the stream or a damaged frame. - For a camera, it can mean a temporary device or connection failure.
- A camera has no normal end-of-file condition, so you may want to retry instead of stopping immediately.
Do not process frame when ok is false. It may be empty or invalid.
| Failure | Safe response |
|---|---|
| Capture did not open | Raise an error before entering the loop |
| Writer did not open | Release the capture, then raise an error |
| File read returned false | Stop the loop and preserve completed output |
| Camera read returned false | Log it, retry, or stop after a limit |
| Processing raised an exception | Let `finally` release all resources |
Resource ownership and cleanup order
The code that opens a resource should own its cleanup. If opening a later resource fails, release the earlier resources before raising the error. Once all resources are open, one try/finally block can clean them up together.
A finally block does not hide the original exception. Cleanup runs first, then Python reports the exception. This makes debugging easier than catching every exception and printing a vague message.
Exercise
Exercise
Why should a program check writer.isOpened() and call writer.release() even when no frames were written?
Show answer
The check detects configuration or codec failures before processing begins. Calling release() closes the writer and gives the video container a chance to finalize correctly, even when the loop ends early.