Python cv2 VideoCapture: How to Capture Video in Python

0
16725
Python cv2 VideoCapture | How to Load Video in Python

OpenCV (Open Source Computer Vision) is the computer vision library that contains various methods to perform operations on Images or videos.

OpenCV library can be used to perform multiple operations on videos. For example, the python OpenCV library provides a cv2 VideoCapture class.

OpenCV provides the cv2 VideoCapture class used to work with the camera. We can do the following task:

  1. Read the video, display the video, and save the Video.
  2. Then, capture it from the camera and display it.

Python cv2.Video capture

To capture a video in Python, use the cv2.VideoCapture() and create an object of VideoCapture. VideoCapture has the device index or the name of a video file. The device index is just an integer to define a Camera.

If we pass 0, it is for the first or primary camera, 1 for the second camera, etc. Then, we capture the video frame by frame.

How to Capture Video from Camera in Python

OpenCV allows a candid interface to capture live streams with the camera (webcam).

To capture a video, we need to create an object for the VideoCapture class. It accepts either a device index or the name of a video file.

A number that is specified to the camera is called the device index. We can select a Camera bypassing the O or 1 as an argument. After that, we can capture the video frame-by-frame.

See the following code.

# app.py

import cv2

cap = cv2.VideoCapture(0)

while(True):
    ret, frame = cap.read()
    cv2.imshow('frame', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

Now, go to the terminal and run the Python file by the following command.

python3 app.py

It will ask for camera permission, and when you permit them, the webcam will be opened, and in the Python window, you will see yourself.

In this example, first, we have imported the cv2 module.

Then we created an object for VideoCapture class. To obtain Video from the camera, we have to create an object of the class VideoCapture. As input, the constructor of the VideoCapture class receives an index of the device we want to use.

If we have a single camera connected to the computer, we can pass a value of 0.

You can pass one of the following values based on your requirements.

cv2.VideoCapture(0): Means first camera or webcam.
cv2.VideoCapture(1):  Means second camera or webcam.
cv2.VideoCapture("file name.mp4"): Means video file

After this, we can start reading a Video from the camera frame by frame. We do this by calling the read method on the VideoCapture object.

This method takes no arguments and returns a tuple. The first returned value is a Boolean indicating if a frame was read correctly (True) or not (False).

We can use this value for error checking to confirm that no problem occurred while reading the frame. But for this tutorial demo, we assume everything went well, so we will not look into this value.

In the next step, we used a while loop.

We read the video frame by frame and pass it to the cv2.imshow() function inside the while loop.

The cv2.imshow() method displays a video or image in a window. The window automatically fits the Video or image size.

Until we press the q key or 1 key, it will keep opening a web camera and capture the Video.

Load video in Grayscale mode

To load webcam video in Grayscale mode, we can use cv2.cvtColor() function. We have to pass the cv2.COLOR_BGR2GRAY property to turn the Video Gray. See the following code.

import cv2

cap = cv2.VideoCapture(0)

while(True):
    ret, frame = cap.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cv2.imshow('frame', gray)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

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

How to Play Video from a file in Python

To play the video from a file, you must provide the video path in the VideoCapture() method. It is similar to capturing from the camera by changing the camera index with the file name.

The time must be appropriate for the cv2.waitKey() function, and if the time is high, the Video will be slow. On the other hand, if the time is too low, the Video will be high-speed.

import cv2

cap = cv2.VideoCapture('friends.mp4')

while(cap.isOpened()):
    ret, frame = cap.read()
    cv2.imshow('frame', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

In this example, when creating a VideoCapture object, we pass the Video called friends.mp4.

Then we read frame by frame and show it to the Python window.

To show grayscale video, use cv2.cvtColor() method to convert video into Grayscale.

import cv2

cap = cv2.VideoCapture('friends.mp4')

while(cap.isOpened()):
    ret, frame = cap.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cv2.imshow('frame', gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

This code will open the grayscale Video.

How to Save a Video in Python

To save a video using the cv2 library in Python, use cv2.VideoWriter_fourcc() method.

Syntax

cv2.VideoWriter(filename, fourcc, fps, frameSize)

Parameters

  1. filename: Input video file.
  2. fourcc: 4-character code of codec used to compress the frames.
  3. fps: framerate of the video stream.
  4. framesize: Height and width of the frame.

Example

import cv2


# Create an object to read
# from camera
video = cv2.VideoCapture(0)

# We need to check if camera
# is opened previously or not
if (video.isOpened() == False):
    print("Error reading video file")

# We need to set resolutions.
# so, convert them from float to integer.
frame_width = int(video.get(3))
frame_height = int(video.get(4))

size = (frame_width, frame_height)

# Below VideoWriter object will create
# a frame of above defined The output
# is stored in 'output.avi' file.
result = cv2.VideoWriter('output.avi',
                         cv2.VideoWriter_fourcc(*'MJPG'),
                         10, size)

while(True):
    ret, frame = video.read()

    if ret == True:

        # Write the frame into the
        # file 'output.avi'
        result.write(frame)

        # Display the frame
        # saved in the file
        cv2.imshow('Frame', frame)

        # Press S on keyboard
        # to stop the process
        if cv2.waitKey('q') & 0xFF == ord(1):
            break

    # Break the loop
    else:
        break

# When everything done, release
# the video capture and video
# write objects
video.release()
result.release()

# Closes all the frames
cv2.destroyAllWindows()

print("The video was successfully saved")

In this example, first, I created an object for VideoCapture class.

Then we got the resolutions of the video object and converted it into an integer.

Then we call the cv2.VideoWriter() method and pass the name of the output video file, size, and codec.

Then we write one by one frame in the output.avi file.

The waitKey() function returns the pressed key as a number. Again, we will assume that we want to finish the program. So, if we press the q key, it will close the python window, and Video is saved in the filesystem. 

The Video is stored in your current project folder because we have not specified the file path.

That is how you load and save the Video in Python using the OpenCV library.

See also

Python cv2 imread()

Python cv2 imwrite()

Leave A Reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.