Reading and Writing Videos using OpenCV

We offer you a brighter future with placement-ready courses - Start Now!!

In this article, we’ll be learning how to read, display and write videos in OpenCV. OpenCV is a vast library that provides numerous functions for image and video processing. Using the built-in functions of OpenCV, we can read videos in various ways. We can display the videos that we have read using the functions available in OpenCV. We can also save or write a video to a specified location using OpenCV. Let’s start!!!

Reading videos in OpenCV

Reading videos in OpenCV is the first step before we can move to video processing tasks. It is essential to properly read a video file to extract useful information and to perform various operations on it. Reading videos in OpenCV is similar to reading images. Videos consist of a sequence of images. Videos are often read frame by frame, that is, one image of the sequence at a time. To read a video, we need to loop over all the frames and then process them one by one.

The cv2.VideoCapture function in OpenCV is used to perform video file reading operations.

Syntax

cv2.VideoCapture(filename, apiPreference)

Parameters

a. filename: The name of the video file to be read. The filename can be in the following formats:

  • Name of the video file located in the current directory or the complete path of the video file if the file is located outside the current working directory.
  • Name of the image sequence to be iterated through
  • The URL of a video stream

b. apiPreference: The preferred API backend to be used to capture or read the video file. It is an optional parameter.

Reading a video from a file

The cv2.VideoCapture function is used to read a video file from a specified destination. The complete file path is given to the function as an argument if the video is not in the current working directory. If the video file is in the working directory, only specifying the filename along with the file extension is sufficient.

The isOpened() function in OpenCV is used to confirm the successful opening of the video file we have read. If the file has not been opened successfully, an error will be received. The error implies the corruption of the video file or certain frames in the video. If the video file is opened successfully, we can extract the metadata associated with the video using the get function in OpenCV.

There are three ways we can read a video in OpenCV, these methods are:

1. cv2.isOpened()

Syntax

cv2.VideoCapture.isOpened()

Parameters

The function takes no arguments.

a. Return value: Its return value is of Boolean type. It returns TRUE if the video file has been successfully opened, otherwise it returns FALSE.

2. cv2.get()

Syntax

cv2.VideoCapture.get(propId)

Parameters

a. propId: This parameter specifies the property to be identified.

b. Return value: The specified property value is returned. When the property queried by the function is not supported by the backend of the VideoCapture function, 0 is returned.

The video file is read frame by frame after the retrieval of the metadata from the video file. The frames are read by creating a loop and reading the frames using the VideoCapture.read() function.

The VideoCapture.read() function is used for extracting and decoding the frame. This function returns a tuple, containing one Boolean element and one image, the video frame. If no video frame has been grabbed, an empty image is returned and the Boolean value is False.

Implementation

# Importing OpenCV
import cv2
 
# Reading the video from a file
video = cv2.VideoCapture(r"C:\Users\tushi\Downloads\PythonGeeks\clouds.mp4")
 
# Checking whether the video has opened using the isOpened function
if (video.isOpened() == False):
    print("Error opening the video file")
 
# When the video has been opened successfully, we'll read each frame of the video using a loop
while(video.isOpened()):
    ret, frame = video.read()
    if ret == True:
        cv2.imshow('Frame',frame)
        # Using waitKey to display each frame of the video for 1 ms
        key = cv2.waitKey(1)
        if key == ord('q'):
            break
 
cv2.destroyAllWindows()

Reading an image sequence using OpenCV

Videos are formed from a sequence of images. Hence, processing the frames of an image sequence works similarly to reading the frames of a video. We need to specify the image files of the image sequence which are going to be read.

The image sequence can be read by specifying an iterable filename in the VideoCapture function. The image sequence is read by using the naming notation of the filename as an image sequence instead of a video file.

Implementation

# Importing OpenCV
import cv2
 
# Reading the image sequence from a file
video = cv2.VideoCapture(r"C:\Users\tushi\Downloads\PythonGeeks\Image sequence\Fire%d.png")
 
# Checking whether the video has opened using the isOpened function
if (video.isOpened() == False):
    print("Error opening the video file")
 
# When the video has been opened successfully, we'll read each frame of the video using a loop
while(video.isOpened()):
    ret, frame = video.read()
    if ret == True:
        # Using waitKey to display each frame of the video for 1 ms
        cv2.imshow('Frame',frame)
        key = cv2.waitKey(1)
        if key == ord('q'):
            break
 
cv2.destroyAllWindows()

Reading video using the device’s camera

To read a video using our device’s camera, we can use the VideoCapture function. Instead of specifying the name of the video file present in the working directory or the name of the image sequence, we need to specify the device index for video capture.

For a built-in webcam in our system, the device index will be 0. If we have multiple cameras attached to our system, the device index for each camera is incremented. We need to specify the appropriate device index in the VideoCapture function depending on the camera we’ll be using.

Implementation

# Importing OpenCV
import cv2

# Reading the video from the webcam
video = cv2.VideoCapture(0)

# Checking whether the camera has been accessed using the isOpened function
if (video.isOpened() == False):
    print("Error opening the video file")
    

# When the video from the camera has been opened successfully, we'll read each frame of the video using a loop
while(video.isOpened()):
    ret, frame = video.read()
    if ret == True:
        cv2.imshow('Frame',frame)
        # Using waitKey to display each frame of the video for 1 ms
        key = cv2.waitKey(1)
        if key == ord('q'):
            break

cv2.destroyAllWindows()

Reading video from a URL

The cv2.VideoCapture function is used to read a video file from a URL. The complete link of the video must be provided as an argument to the function.

The isOpened() function in OpenCV is used to confirm the successful opening of the video file we have read. If the file has not been opened successfully, an error will be received. The error implies the corruption of the video file or certain frames in the video. If the video file is opened successfully, we can extract the metadata associated with the video using the get function in OpenCV.

Implementation

# Importing OpenCV
import cv2

# Reading the video from URL
video = cv2.VideoCapture(r"pexels-mart-production-8447658.mp4")

# Checking whether the video has opened using the isOpened function
if (video.isOpened() == False):
    print("Error opening the video file")

# When the video has been opened successfully, we'll read each frame of the video using a loop
while(video.isOpened()):
    ret, frame = video.read()
    
    # Resizing the video 
    frame = cv2.resize(frame, None, None, fx=0.1, fy=0.1)
    
    # Checking if each frame is being read
    if ret == True:
        cv2.imshow('Frame',frame)
    
        # Using waitKey to display each frame of the video for 1 ms
        key = cv2.waitKey(1)
        if key == ord('q'):
            break

video.release()
cv2.destroyAllWindows()

Displaying videos in OpenCV

To display a video file, we have read using one of three methods mentioned above, we can use the cv2.imshow function. The cv2.imshow() function in OpenCV displays the video frame by frame.

The waitKey() function is used along with imshow() and allows the users to display the frames of the video for a specified time given in milliseconds or until any key (or the key specified in the code) is pressed. We need to give a value greater than 0 to the waitKey() function, otherwise, the video will be stuck infinitely on one frame.

Each frame in the video has to be shown for a finite interval and hence the number passed to the waitKey() function should correspond to the time each frame will be displayed in milliseconds. Giving a greater value to the waitKey() will play the video slower as each frame will be delayed by a greater value.

While reading video from the camera of our system or a stream, the waitKey() function can be given the value as 1 millisecond. The display rate of each frame will be limited by the frame rate of the camera we are using.

Implementation

# Importing OpenCV
import cv2
 
# Reading the video from the webcam
video = cv2.VideoCapture(0)
 
# Checking whether the camera has been accessed using the isOpened function
if (video.isOpened() == False):
    print("Error opening the video file")
 
# When the video has been opened successfully, we'll read each frame of the video using a loop
while(video.isOpened()):
    ret, frame = video.read()
    if ret == True:
        # Displaying the video frame by frame using the imshow function
        cv2.imshow('Frame',frame)
        # Using waitKey to display each frame of the video for 1 ms
        key = cv2.waitKey(1)
        if key == ord('q'):
            break
 
cv2.destroyAllWindows()

Writing videos in OpenCV

To write a video file in OpenCV, the cv2.VideoWriter function is used. The video has to be read using any of the methods mentioned in the earlier sections. After reading the video, we need to extract the height and width of each frame of the video using the get() function. The object of the video writer has to be created. Using the object of the VideoWriter function, the video will be saved to the specified location.

Syntax

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

Parameters

a. Filename: It is the name of the output file

b. Fourcc: It is a code consisting of four characters. It is used to compress the frames of the video.

c. Fps: Frame per second or the frame rate of the video

d. frameSize: The frame size of the frames of the video extracted using the get() function.

e. isColor: If this parameter is 0, then the function will work with grayscale frames, otherwise it will work with color frames.

Implementation

# Importing OpenCV
import cv2
 
# Reading the video from the webcam
video = cv2.VideoCapture(0)
 
# Checking whether the camera has been accessed using the isOpened function
if (video.isOpened() == False):
    print("Error opening the video file")
    
# Getting the frame width and frame height
frame_width = int(video.get(3))
frame_height = int(video.get(4)) 
    
# Writing the video using the cv2.VideoWriter function
video_out = cv2.VideoWriter(r'C:\Users\tushi\Downloads\PythonGeeks\output.avi',cv2.VideoWriter_fourcc('M','J','P','G'), 10, (frame_width,frame_height))
 
# When the video has been opened successfully, we'll read each frame of the video using a loop
while(video.isOpened()):
    ret, frame = video.read()
    if ret == True:
        cv2.imshow('Frame',frame)
        
        # Writing each frame of the video
        video_out.write(frame)
 
        # Using waitKey to display each frame of the video for 1 ms
        key = cv2.waitKey(1)
        if key == ord('q'):
            break
 
video.release()
video_out.release()
cv2.destroyAllWindows()

The output shows that the video we have recorded using our webcam has been saved to the specified location. These videos can be written in OpenCV.

Errors while Reading or Writing Videos

Reading from a video

If the path is incorrect, the file is corrupted, or a frame is missing, it will throw an error. That is why within the while loop we use an if statement If ret == True, to check whether each frame of the video is being read properly. It will only process the video if the frames are present.

Wrong path

When we specify an incorrect path to a video, the VideoCapture() class will not display any errors or warnings. When we try to perform any operation on the video frames, the operation will not be executed as the video has not been read. We should check whether the file has been properly read or not before performing any operations on it.

Video writing

Various errors can arise during this process. Frame size and api preference errors are the most common. Even if we get a video file in the output directory, if the frame size is not identical to the video, it will be blank. We need to invert the output when using the NumPy shape function to get frame size, as OpenCV will provide height x width x channels. If an api preference error occurs, the CAP_ANY flag in the VideoCapture() argument may be required.

Conclusion

In this article, we understood the process of reading videos in OpenCV. We learned about the different ways we can read videos, which include, reading videos from a file, reading videos from an image sequence, reading videos using the camera connected to our system and reading videos from a URL. Furthermore, we understood how we can display the videos that we have read. We learned to write a video to a specified location using the functions provided by OpenCV. We also learned about the errors that may occur while reading or writing a video file in OpenCV.

Did you like our efforts? If Yes, please give PythonGeeks 5 Stars on Google | Facebook

PythonGeeks Team

At PythonGeeks, our team provides comprehensive guides on Python programming, AI, Data Science, and machine learning. We are passionate about simplifying Python for coders of all levels, offering career-focused resources.

Leave a Reply

Your email address will not be published. Required fields are marked *