Sub topic 9
Writing processed frames to a new file
You can already read frames with cv2.VideoCapture and transform them with NumPy and OpenCV functions. This chapter covers the last step of a pipeline: encoding the processed frames into a new video file with cv2.VideoWriter. It assumes you know the read loop, that a frame is a uint8 array in BGR order, and how to query capture properties such as FPS and frame size.
What VideoWriter does
A VideoWriter takes frames one at a time, compresses them with a codec, and stores them in a container file. You decide four things when you create it:
- The output path. The extension suggests the container, such as
.mp4or.avi. - A FourCC code, which names the codec.
- The frame rate stored in the file header.
- The frame size as
(width, height).
out = cv2.VideoWriter(path, fourcc, fps, (width, height))The writer never inspects your source video. It trusts the numbers you give it, so the usual approach is to read them from the input capture.
A complete example
This script reads input.mp4, detects edges in every frame, and saves the result to edges.mp4.
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))
total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
print(f"{width}x{height} at {fps:.2f} fps, about {total} frames")
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")
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)
out.write(cv2.cvtColor(edges, cv2.COLOR_GRAY2BGR))
finally:
cap.release()
out.release()Four details in this script matter.
cap.get(...)returns floats, so the width and height are converted withint(). The writer needs integers.- The
or 30.0fallback covers sources that report an FPS of 0. Without it, the writer would be created with an invalid rate. Cannyreturns a single-channel image, socv2.cvtColor(edges, cv2.COLOR_GRAY2BGR)makes it a three-channel image before writing.out.release()runs in thefinallyblock. Releasing finalizes the file.
Codecs, FourCC codes and containers
A video file has two layers. The codec compresses and decompresses the frames. The container, such as MP4 or AVI, packages the compressed stream with a header and timing data. A FourCC is a four-character code that identifies the codec. You build it with cv2.VideoWriter_fourcc(*"mp4v"), where the * unpacks the string into four separate characters.
| FourCC | Codec | Typical container | Notes |
|---|---|---|---|
| `mp4v` | MPEG-4 Part 2 | `.mp4` | Widely available in pip builds of OpenCV. Larger files than H.264. |
| `XVID` | Xvid (MPEG-4) | `.avi` | Common and well supported on AVI. |
| `MJPG` | Motion JPEG | `.avi` | Every frame is a JPEG. Large files, but cheap to encode and easy to seek. |
| `avc1` | H.264 | `.mp4` | Smaller files, but often missing from pip builds because of licensing. |
Which codecs work depends on your OpenCV build, your operating system, and the backend that does the encoding, which is usually FFmpeg. A FourCC that works on one machine can fail on another. The writer has no error-reporting channel except isOpened(), so you should always check it.
Frame size and type must match
The frameSize you pass at construction is fixed for the life of the writer. Every frame you write must match it exactly, or the backend may drop the frame without raising an error.
The most common mistake is the order of dimensions. A NumPy array has shape (height, width, channels), but VideoWriter wants (width, height). When you take the size from an array, reverse it:
h, w = frame.shape[:2]
size = (w, h) # VideoWriter wants width firstBy default the writer expects color frames: uint8 arrays with shape (height, width, 3). Three typical errors follow from this.
- A single-channel image such as the output of
CannyorcvtColor(..., COLOR_BGR2GRAY)is not the expected shape. Convert it withCOLOR_GRAY2BGR, as the example does. - A
float32orfloat64image is the wrong dtype. Convert it back withnp.clip(img, 0, 255).astype(np.uint8). - A frame that was resized or cropped during processing has the wrong size. Resize it back with
cv2.resize(frame, (width, height)), which also takes(width, height).
The constructor has an isColor argument. Passing isColor=False tells the writer to expect single-channel frames, but support varies by backend and OpenCV version. Converting to BGR works everywhere, so this tutorial uses that approach. The cost is that grayscale content is stored as three identical channels. Modern codecs compress this redundancy well, so the file is not much larger.
Choosing the frame rate
The FPS you pass is written into the file header. It controls how fast players show the video. It does not change how fast your script runs.
- If you process every frame and write each one, use the source FPS. The output has the same duration as the input.
- If you skip frames, for example by writing every second frame to reduce size, halve the FPS. Otherwise the output plays at double speed.
- If you record from a camera, the reported FPS may be a request and not the real delivery rate. A video written at 30 FPS from a camera that delivers 15 FPS plays at double speed. Measure the real rate first, as discussed in the chapter on timing.
Wrapping the setup in a function
Opening a writer needs the same checks every time. A small helper keeps the main loop readable and ensures the failure is reported at the right place.
import cv2
def open_writer(path, fourcc_code, fps, width, height):
"""Create a VideoWriter and fail loudly if it cannot be used."""
fourcc = cv2.VideoWriter_fourcc(*fourcc_code)
writer = cv2.VideoWriter(path, fourcc, fps, (width, height))
if not writer.isOpened():
writer.release()
raise RuntimeError(
f"Could not open {path} with codec {fourcc_code!r}; "
"try another FourCC or container"
)
return writer
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
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
# Output is half size, so the writer's frame size is half size too.
out_w, out_h = width // 2, height // 2
out = open_writer("small.mp4", "mp4v", fps, out_w, out_h)
try:
while True:
ok, frame = cap.read()
if not ok:
break
small = cv2.resize(frame, (out_w, out_h), interpolation=cv2.INTER_AREA)
out.write(small)
finally:
cap.release()
out.release()Here the output size differs from the input size. The writer is built with the output size, and each frame is resized to exactly that size before writing. INTER_AREA is a good interpolation choice when shrinking an image.
Odd dimensions can also fail with some codecs, because many of them require even width and height. The // 2 here gives an odd result for an odd input. If your encoder rejects odd sizes, round down to an even number with out_w = (width // 2) // 2 * 2.
Releasing the writer finishes the file
The codec buffers frames, and the container writes its index and header details at the end. Calling out.release() flushes the buffers and writes that final data. If your script crashes or you forget the call, the file may be truncated, unplayable, or missing its duration. This is why the examples place release() in a finally block. The next chapters on resource cleanup cover this pattern in detail.
Do not reuse a released writer. To write another file, create a new VideoWriter.
Common problems
| Symptom | Likely cause | Fix |
|---|---|---|
| Output file is 0 bytes or missing | Codec or container not supported, or writer never opened | Check `out.isOpened()`. Try `mp4v` with `.mp4`, or `MJPG` with `.avi`. |
| File exists but is very short or empty of frames | Frame size passed to `write` differs from `frameSize` | Compare `frame.shape[:2]` to `(height, width)` and resize if needed. |
| Output is black or garbled | Wrong dtype, or a single-channel frame written to a color writer | Convert to `uint8` and three channels. |
| Output plays too fast or too slow | Wrong FPS in the header | Use the real source FPS, and halve it if you skip every second frame. |
| File will not play or has no duration | `release()` was never called | Release in a `finally` block. |
| Output is much larger than input | Codec such as `MJPG` or `mp4v` compresses less than H.264 | Use a stronger codec if your build has it, or re-encode afterwards with an external tool. |
Audio is not included
VideoWriter writes video only. Audio tracks in the input are ignored by VideoCapture, so your output has no sound. To keep the original audio, mux (combine) the processed video with the source audio afterwards using an external tool such as FFmpeg.
Exercise
A script reads 1280x720 frames, converts each to grayscale with cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY), and writes it to a VideoWriter created with (720, 1280) as the frame size. The output file is empty. Name two separate mistakes and give the fix for each.
Show answer
First, the frame size is in the wrong order. VideoWriter expects (width, height), which is (1280, 720), not (720, 1280). Second, the grayscale image has one channel, but the writer defaults to isColor=True and expects three-channel frames. Convert with cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR) before writing, or create the writer with isColor=False if your backend supports it. Also check out.isOpened() so a bad setup is reported immediately.
Exercise
You want to write every second frame of a 30 FPS input to save space, and the result should play at the original real-time speed. What FPS do you pass to VideoWriter, and why?
Show answer
Pass 15 FPS. Half of the frames are kept, so the output needs half the frame rate to cover the same duration. At 30 FPS the shortened sequence would play at double speed.