OpenCV Module 6: Read and Write Videos

Read Video from Source:

import cv2
import matplotlib.pyplot as plt
%matplotlib inline

source = './race_car.mpr' #Soure = 0 for webcam

cap = cv2.VideoCapture(source)
if (cap.isOpened() == False):
	print("Error opening video stream of file")

Read and display one frame:

ret, frame = cap.read()
plt.imshow(frame[...,::-1])

» Displays the first frame


Write Video using OpenCV:

For writing the video, you need to create a videoWriter object with the right parameters.

Function Syntax:

VideoWriter object= cv.VideoWriter( filename, fourcc, fps, frameSize )

where, Parameters:

  • filename: Name of the output file

  • fourcc: 4-character code of codec used to compress the frames. For example, VideoWriter::fourcc(‘P’,’I’,’M’,’1’) is a MPEG-1 codec.

  • fps: Framerate of the created video stream.

  • frameSize: Size of the video frames.

#Default resolutions of the frame are obtained.
#Convert the resolutions from float to integer.
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))

#Define the codec and create VideoWriter object.
out_avi = cv2.VideoWriter('race_car_out.avi', cv2.VideoWriter_fourcc('M','J','P','G'), 10, frame_width, frame_height))

out_mp4 = cv2.VideoWriter('race_car_out.mp4', cv2.VideoWriter_fourcc(*'XVID'), 10, frame_width, frame_height))

Read frames and write to file:

#Read until video is complete
while(cap.isOpened()):
	#Capture frame-by-frame
	ret, frame = cap.read()
	if ret == True:
		#Write the frames to the output files
		out_avi.write(frame)
		out_mp4.write(frame)
	else:
		break

#MAKE SURE TO RELEASE
cap.release()
out_avi.release()
out_mp4.release()