Reading and Writing a video file

OpenCV provides the VideoCapture and VideoWriter classes that support various video file formats. The supported formats vary by system but should always include an AVI. Via its read() method, a VideoCapture class may be polled for new frames until it reaches the end of its video file. Each frame is an image in a BGR format.

Conversely, an image may be passed to the write() method of the VideoWriter class, which appends the image to a file in VideoWriter. Let’s look at an example that reads frames from one AVI file and writes them to another with a YUV encoding:

# Import OpenCV library
import cv2    

# Loading/Reading Video
videoCapture = cv2.VideoCapture('MyInputVid.avi')
# Capture Frames
fps = videoCapture.get(cv2.CAP_PROP_FPS)
# Store width and height of video in size set
size = (int(videoCapture.get( cv2.CAP_PROP_FRAME_WIDTH)), int(videoCapture.get( cv2.CAP_PROP_FRAME_HEIGHT)))
# Writing Video in ('I','4','2','0') encoding as MyOutputVid.avi
videoWriter = cv2.VideoWriter( 'MyOutputVid.avi', cv2.VideoWriter_fourcc ('I','4','2','0'), fps, size)
# Read captured video and store them in success and frame
success, frame =
# Loop until there are no more frames.
while success:
     success, frame =      

The arguments to the VideoWriter class constructor deserve special attention. A video’s filename must be specified. Any preexisting file with this name is overwritten. A video codec must also be specified. The available codecs may vary from system to system. These are the options that are included: