Home » OpenCV Video Capture

OpenCV Video Capture

by Online Tutorials Library

OpenCV VideoCapture

OpenCV provides the VideoCature() function which is used to work with the Camera. We can do the following task:

  • Read video, display video, and save video.
  • Capture from the camera and display it.

Capture Video from Camera

OpenCV allows a straightforward interface to capture live stream with the camera (webcam). It converts video into grayscale and display it.

We need to create a VideoCapture object to capture a video. It accepts either the device index or the name of a video file. A number which is specifying to the camera is called device index. We can select the camera by passing the O or 1 as an argument. After that we can capture the video frame-by-frame.

The cap.read() returns a boolean value(True/False).It will return True, if the frame is read correctly.

Playing Video from file

We can play the video from the file. It is similar to capturing from the camera by changing the camera index with the file name. The time must be appropriate for cv2.waitKey() function, if time is high, video will be slow. If time is too less, then the video will be very fast.

Saving a Video

The cv2.imwrite() function is used to save the video into the file. First, we need to create a VideoWriter object. Then we should specify the FourCC code and the number of frames per second (fps). The frame size should be passed within the function.

FourCC is a 4-byte code used to identify the video codec. The example is given below for saving the video.

It will save the video at the desired location. Run the above code and see the output.


You may also like