Sub topic 9
Writing Processed Frames to a New File
Prerequisites and the writer model
This chapter assumes you can open a source with cv2.VideoCapture, read frames in a loop, and use basic NumPy arrays. You should also know that OpenCV stores color images in BGR order, not RGB order.
cv2.VideoWriter saves a sequence of images as a video file. Every frame written to the file must have the same width and height. The writer also needs a frame rate and a codec. A codec is the algorithm used to encode video data.
The main relationship is:
| Writer setting | Meaning |
|---|---|
| Output path | Where the encoded video is saved |
| FourCC | Four-character codec code |
| FPS | Number of frames displayed per second |
| Frame size | `(width, height)` of every output frame |
| Color flag | Whether frames have three color channels |
The writer does not automatically discover these values from the frames you pass to it. Read them from the input capture, then use them when creating the writer.
Build a read-process-write loop
The following program reads a video, detects edges in each frame, and writes the result to edges.mp4.
import cv2
input_path = "input.mp4"
output_path = "edges.mp4"
cap = cv2.VideoCapture(input_path)
if not cap.isOpened():
raise RuntimeError(f"Could not open {input_path}")
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)
if width <= 0 or height <= 0:
raise RuntimeError("The input has no usable frame size")
if fps <= 0:
fps = 30.0
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
out = cv2.VideoWriter(
output_path,
fourcc,
fps,
(width, height),
isColor=True,
)
if not out.isOpened():
cap.release()
raise RuntimeError(f"Could not open writer for {output_path}")
try:
while True:
ok, frame = cap.read()
if not ok:
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
edges = cv2.Canny(blurred, 100, 200)
# Convert one-channel edges to three-channel BGR.
output_frame = cv2.cvtColor(edges, cv2.COLOR_GRAY2BGR)
out.write(output_frame)
finally:
cap.release()
out.release()
print(f"Saved processed video to {output_path}")The mp4v FourCC works on many installations, but codec support depends on the OpenCV build and operating system. If the writer cannot open, try another codec and an output extension supported by that codec.
Match frame shape and channel count
A common failure occurs when the processed frame does not match the writer configuration. In the example, Canny returns a single-channel grayscale image with shape (height, width). The writer was created with isColor=True, so the image is converted to BGR and has shape (height, width, 3) before it is written.
You can instead create a grayscale writer:
out = cv2.VideoWriter(
"gray_output.avi",
cv2.VideoWriter_fourcc(*"MJPG"),
fps,
(width, height),
isColor=False,
)The exact behavior of grayscale encoding can vary by backend. Converting grayscale output to BGR is often the more portable choice.
Understand timing and output quality
Using the input FPS preserves the source playback rate, but it does not make processing real time. If processing takes longer than one frame interval, the output file is still written at the chosen FPS. It will contain the processed frames, but creating it may take longer than the original video's duration.
For example, at 30 FPS, each frame represents about 33.3 milliseconds of playback. If processing one frame takes 50 milliseconds, the program cannot process the source at 30 frames per second in real time. For a saved file, this usually affects processing duration rather than playback speed.
Exercise
Why must a single-channel edge image be converted to BGR before writing when the writer was created with isColor=True?
Show answer
The writer expects three-channel color frames with the configured width and height. Converting the edge image to BGR supplies the required three channels without changing its dimensions.