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 = videoCapture.read()
# Loop until there are no more frames.
while success:
videoWriter.write(frame)
success, frame = videoCapture.read()
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:
- cv2.VideoWriter_fourcc('I','4','2','0'): This option is an uncompressed YUV encoding, 4:2:0 chroma subsampled. This encoding is widely compatible but produces large files. The file extension should be .avi.
- cv2.VideoWriter_fourcc('P','I','M','1'): This option is MPEG-1. The file extension should be .avi.
- cv2.VideoWriter_fourcc('X','V','I','D'): This option is MPEG-4 and a preferred option if you want the resulting video size to be average. The file extension should be .avi.
- cv2.VideoWriter_fourcc('T','H','E','O'): This option is Ogg Vorbis. The file extension should be .ogv.
- cv2.VideoWriter_fourcc('F','L','V','1'):This option is a Flash video. The file extension should be .flv.
Capturing Camera Frames
A stream of camera frames is represented by the VideoCapture class too. However, for a camera, we construct a VideoCapture class by passing the camera’s device index instead of a video’s filename. Let’s consider an example that captures 10 seconds of video from a camera and writes it to an AVI file:
# Import OpenCV library
import cv2
# Create a video caputure instance
cameraCapture = cv2.VideoCapture(0)
# An assumption that our camera have 30fps quality
fps = 30
# Store width and height of video in size set
size = (int(cameraCapture.get( cv2.CAP_PROP_FRAME_WIDTH)) , int(cameraCapture.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 = cameraCapture.read()
# Calculate number of frames required for 10 sec
numFramesRemaining = 10 * fps - 1
# Loop until there are no more frames left.
while success and numFramesRemaining > 0:
videoWriter.write(frame)
success, frame = cameraCapture.read()
numFramesRemaining -= 1
# Erase camera Capture instance
cameraCapture.release()
Displaying Camera Frames
OpenCV allows named windows to be created, redrawn, and destroyed using the namedWindow(), imshow(), and destroyWindow() functions. Also, any window may capture keyboard input via the waitKey() function and mouse input via the setMouseCallback() function. Let’s look at an example where we show the frames of a live camera input:
# Import OpenCV library
import cv2
# Initialise clicked to false
clicked = False
# This function change clicked variable value to true when mouse is clicked
def onMouse(event, x, y, flags, param):
global clicked
if event == cv2.EVENT_LBUTTONUP:
clicked = True
# Create a video caputure instance
cameraCapture = cv2.VideoCapture(0)
# Create window named MyWindow
cv2.namedWindow('MyWindow')
# Set onMouse function to window
cv2.setMouseCallback('MyWindow', onMouse)
print('Showing camera feed. Click window or press any key to stop.')
# Read captured video and store them in success and frame
success, frame = cameraCapture.read()
# Loop until key is not pressed or Mouse is not clicked
while success and cv2.waitKey(1) == -1 and not clicked:
cv2.imshow('MyWindow', frame)
success, frame = cameraCapture.read()
# Close window.
cv2.destroyWindow('MyWindow')
# Clear cameraCapture instance
cameraCapture.release()
The argument for waitKey() is a number of milliseconds to wait for keyboard input. The return value is either -1 (meaning that no key has been pressed) or an ASCII keycode, such as 27 for Esc.
The mouse callback passed to setMouseCallback() should take five arguments, as seen in our code sample. The callback’s param argument is set as an optional third argument to setMouseCallback(). By default, it is 0. The callback’s event argument is one of the following actions:
- cv2.EVENT_MOUSEMOVE: This event refers to mouse movement
- cv2.EVENT_LBUTTONDOWN: This event refers to the left button down
- cv2.EVENT_RBUTTONDOWN: This refers to the right button down
- cv2.EVENT_MBUTTONDOWN: This refers to the middle button down
- cv2.EVENT_LBUTTONUP: This refers to the left button up
- cv2.EVENT_RBUTTONUP: This event refers to the right button up
- cv2.EVENT_MBUTTONUP: This event refers to the middle button up
- cv2.EVENT_LBUTTONDBLCLK: This event refers to the left button being double-clicked
- cv2.EVENT_RBUTTONDBLCLK: This refers to the right button being double-clicked
- cv2.EVENT_MBUTTONDBLCLK: This refers to the middle button being double-clicked
The mouse callback’s flags argument may be some bitwise combination of the following events:
- cv2.EVENT_FLAG_LBUTTON: This event refers to the left button being pressed
- cv2.EVENT_FLAG_RBUTTON: This event refers to the right button being pressed
- cv2.EVENT_FLAG_MBUTTON: This event refers to the middle button being pressed
- cv2.EVENT_FLAG_CTRLKEY: This event refers to the Ctrl key being pressed
- cv2.EVENT_FLAG_SHIFTKEY: This event refers to the Shift key being pressed
- cv2.EVENT_FLAG_ALTKEY: This event refers to the Alt key being pressed