Last modified: Jan 18, 2025 By Alexander Williams

Python OpenCV cv2.VideoWriter() Guide

OpenCV is a powerful library for computer vision tasks. One of its key features is the ability to process and save videos. The cv2.VideoWriter() function is essential for saving video files in OpenCV.

This guide will walk you through the basics of using cv2.VideoWriter(). You will learn how to set it up, write frames to a video file, and handle common issues.

What is cv2.VideoWriter()?

The cv2.VideoWriter() function is used to create a video file. It allows you to save frames captured from a camera or generated by your program. This is useful for creating video outputs from image processing tasks.

To use cv2.VideoWriter(), you need to specify the output file name, codec, frame rate, and frame size. These parameters ensure the video is saved correctly.

Setting Up cv2.VideoWriter()

Before using cv2.VideoWriter(), ensure OpenCV is installed. You can install it using pip:


    pip install opencv-python
    

Once installed, import OpenCV in your Python script:


    import cv2
    

Next, initialize cv2.VideoWriter() with the required parameters. Here's an example:


    # Define the codec and create a VideoWriter object
    fourcc = cv2.VideoWriter_fourcc(*'XVID')
    out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640, 480))
    

In this example, 'XVID' is the codec, 20.0 is the frame rate, and (640, 480) is the frame size.

Writing Frames to a Video

After setting up cv2.VideoWriter(), you can start writing frames to the video file. Frames can be captured using cv2.VideoCapture() or generated programmatically.

Here’s an example of capturing frames from a webcam and saving them:


    cap = cv2.VideoCapture(0)

    while cap.isOpened():
        ret, frame = cap.read()
        if ret:
            out.write(frame)  # Write the frame to the video file
            cv2.imshow('Frame', frame)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
        else:
            break

    cap.release()
    out.release()
    cv2.destroyAllWindows()
    

In this code, frames are read from the webcam and written to the video file. Press 'q' to stop recording.

Common Issues and Solutions

Using cv2.VideoWriter() can sometimes lead to issues. One common problem is incorrect codec or frame size. Ensure the codec is supported and the frame size matches the input frames.

Another issue is file corruption. Always release the cv2.VideoWriter() object using out.release() to ensure the file is saved correctly.

Conclusion

The cv2.VideoWriter() function is a powerful tool for saving video files in OpenCV. By following this guide, you can easily set it up and use it in your projects.

For more advanced video processing, check out our guides on cv2.VideoCapture() and cv2.addWeighted().