Sub topic 3
Processing Video Frames from Files and Cameras with OpenCV: Writing Processed Frames to a New File
This chapter assumes you know the cv2.VideoCapture read loop, NumPy array shapes, Python try/finally, and the opencv-python package.
Writing processed frames to a new file
Create a cv2.VideoWriter with the output path, a FourCC codec code, the frame rate, and the frame size. Take the frame size and rate from the input so the output matches it. Check isOpened() before you write.
import cv2
cap = cv2.VideoCapture("input.mp4")
if not cap.isOpened():
raise RuntimeError("Could not open input.mp4")
fps = cap.get(cv2.CAP_PROP_FPS) or 30.0 # some sources report 0
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
out = cv2.VideoWriter("edges.mp4", fourcc, fps, (width, height))
if not out.isOpened():
cap.release()
raise RuntimeError("Could not open edges.mp4 for writing")VideoWriter expects color frames by default. Convert single-channel results, such as Canny edges, back to BGR with cv2.COLOR_GRAY2BGR before you call out.write().
Releasing resources and handling failures
Both the capture and the writer hold operating system resources. Release them in a finally block so they close even when an error occurs. A camera has no end of file, so a failed read() also ends the loop.
try:
while True:
ok, frame = cap.read()
if not ok:
break
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))
finally:
cap.release()
out.release()> Note: Writing an empty or partial file usually means out.release() never ran. Always release the writer.
Jumping to a frame in a file
Set cv2.CAP_PROP_POS_FRAMES to move the read position. The next read() returns that frame, counting from 0. Seeking accuracy depends on the codec and backend.
cap.set(cv2.CAP_PROP_POS_FRAMES, 100)
ok, frame = cap.read()
if ok:
cv2.imwrite("frame_100.png", frame)Measuring per-frame time and keeping up with live video
Time each iteration with time.perf_counter(). If the average processing time is longer than the frame interval (1000 / fps milliseconds, so about 33 ms at 30 fps), a live camera delivers frames faster than you process them. Frames pile up or get dropped. For a file, the loop simply runs slower.
Putting it together: simple motion detection by frame differencing
This program compares each blurred grayscale frame with the previous one. Pixels that changed by more than 25 gray levels count as motion. The program also reports the time spent on each frame.
import time
import cv2
cap = cv2.VideoCapture("input.mp4")
if not cap.isOpened():
raise RuntimeError("Could not open input.mp4")
ok, prev = cap.read()
if not ok:
cap.release()
raise RuntimeError("No frames in input.mp4")
prev = cv2.GaussianBlur(cv2.cvtColor(prev, cv2.COLOR_BGR2GRAY), (21, 21), 0)
try:
while True:
start = time.perf_counter()
ok, frame = cap.read()
if not ok:
break
gray = cv2.GaussianBlur(cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY), (21, 21), 0)
diff = cv2.absdiff(prev, gray)
_, mask = cv2.threshold(diff, 25, 255, cv2.THRESH_BINARY)
changed = cv2.countNonZero(mask)
prev = gray
ms = (time.perf_counter() - start) * 1000
print(f"changed pixels: {changed}, frame time: {ms:.1f} ms")
finally:
cap.release()Exercise
The writer in the first example uses the input's FPS. Why does the code use or 30.0 after reading CAP_PROP_FPS, and what goes wrong if that fallback is removed for a source that reports 0?
Show answer
Some sources report an FPS of 0. Without the fallback, VideoWriter gets a rate of 0 and the output is invalid or unplayable. The or 30.0 fallback supplies a usable default rate.