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()