“This is the sixth day of my participation in the First Challenge 2022. For details: First Challenge 2022”

Save the video file

We’ve covered how to read video files in OpenCV reading Live Camera Images and Video Files, but we’ll dive into the basic concepts related to video (for example, FPS, codecs, and video file formats) and then learn how to save video files using Cv2.VideoWriter.

Calculate frame rate (FPS)

FPS is an important metric in computer vision projects. It refers to the number of frames (frames) processed per second. The higher the FPS, the better. However, the number of frames per second that the algorithm should process will depend on the specific problem that needs to be solved. For example, if the algorithm needs to track and detect people walking down the street, 15 FPS might be sufficient. However, if you are detecting and tracking fast-moving cars on the highway, you might need 20-25 FPS. Therefore, calculating FPS metrics in computer vision projects is very important. Write read_camera_fps.py to print FPS:

import cv2
import argparse
import time

capture = cv2.VideoCapture(0)

if capture.isOpened() is False:
    print("Error opening the camera")

while capture.isOpened():
    ret, frame = capture.read()
    if ret is True:
        processing_start = time.time()
        cv2.imshow("Input frame from the camera", frame)
        gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        cv2.imshow('Grayscale input camera', gray_frame)
        if cv2.waitKey(20) & 0xFF= =ord('q') :break
        processing_end = time.time()
        processing_time_frame = processing_end - processing_start
        print("FPS: {}".format(1.0 / processing_time_frame))
    else:
        break

capture.release()
cv2.destroyAllWindows()
Copy the code

In the example script above, we first need to get the start time of processing:

processing_start = time.time()
Copy the code

Then, get the time after all processing is complete:

processing_end = time.time()
Copy the code

Next, calculate the time difference:

processing_time_frame = processing_end - processing_start
Copy the code

Finally, calculate and print the FPS:

print("FPS: {}".format(1.0 / processing_time_frame))
Copy the code

The process of writing video files

Video encoding is a program for compressing and decompressing digital video. Specifically, codecs can be used to convert uncompressed video to compressed video, or compressed video to uncompressed video. Compressed video formats usually follow the video compression specification or the standard specification for video encoding formats. OpenCV provides FOURCC (a 4-byte encoding) for specifying video codecs. See the list of available encodings for more encodings. It should be noted that the supported codecs are platform-specific and should be installed on your system if you want to use a specific codec. Typical codecs include DIVX, XVID, X264, and MJPG. Video file format is a file format used to store digital Video data. Typical Video file formats include AVI(*.avi), MP4(*.mp4), QuickTime(*.mov), and Windows Media Video(*.wMV). Finally, consider the need for the right combination between the video file format and FOURCC. When creating a video file in OpenCV, you must consider these factors:

The figure above summarizes the main factors to consider when creating video files using cv2.VideoWriter() in OpenCV. In the video named video_example.avi, FOURCC is XVID, the video file format is avi (*.avi), and finally, the FPS and size of each frame of the video should be set. The write_videofile.py script shows how to create a video file:


# Import required packages
import cv2
import argparse

parser = argparse.ArgumentParser()

parser.add_argument("output_video_path".help="path to the video file to write")
args = parser.parse_args()

capture = cv2.VideoCapture(0)

frame_width = capture.get(cv2.CAP_PROP_FRAME_WIDTH)
frame_height = capture.get(cv2.CAP_PROP_FRAME_HEIGHT)
fps = capture.get(cv2.CAP_PROP_FPS)

fourcc = cv2.VideoWriter_fourcc(*'XVID')

out_gray = cv2.VideoWriter(args.output_video_path, fourcc, int(fps), (int(frame_width), int(frame_height)), False)

while capture.isOpened():
    ret, frame = capture.read()
    if ret:
        gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        out_gray.write(gray_frame)

        cv2.imshow('gray', gray_frame)

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

capture.release()
out_gray.release()
cv2.destroyAllWindows()
Copy the code

In the example above, the required argument is to output the video file name (for example, video_example.avi) :

parser = argparse.ArgumentParser()
parser.add_argument("output_video_path".help="path to the video file to write")
args = parser.parse_args()
Copy the code

Take a video picture from the first camera connected to a computer. So, first create an object:

capture = cv2.VideoCapture(0)
Copy the code

Next, get some key properties (frame width, frame height, and FPS) from the Capture object to use when creating the video file:

frame_width = capture.get(cv2.CAP_PROP_FRAME_WIDTH)
frame_height = capture.get(cv2.CAP_PROP_FRAME_HEIGHT)
fps = capture.get(cv2.CAP_PROP_FPS)
Copy the code

The video codec is then specified using the four-byte encoding FOURCC, where the codec is defined as XVID:

fourcc = cv2.VideoWriter_fourcc('X'.'V'.'I'.'D')
Copy the code

You can also specify the video encoder as follows:

fourcc = cv2.VideoWriter_fourcc(*'XVID')
Copy the code

The cv2.VideoWriter object out_gray is then created using the same properties as the input camera, with the last parameter of cv2.VideoWriter having a value of False to indicate that the video is written in grayscale. If we want to create a color video, the last parameter is True:

out_gray = cv2.VideoWriter(args.output_video_path, fourcc, int(fps), (int(frame_width), int(frame_height)), False)
Copy the code

Use Capture.read() to get camera frames from a catpure object. Each frame is converted to grayscale and written to a video file. If the Q key is pressed, the program ends:

while capture.isOpened():
    ret, frame = capture.read()
    if ret:
        gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        out_gray.write(gray_frame)
        cv2.imshow('gray', gray_frame)

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

Finally, release everything (including the cv2.VideoCapture and cv2.VideWriter objects, and destroy the created window) :

capture.release()
out_gray.release()
cv2.destroyAllWindows()
Copy the code

Run the script by running the following command on the command line:

python write_video_file.py video_example.avi
Copy the code

You can see the saved grayscale video file in the working directory.

A link to the

OpenCV image processing basics

Coordinate system and image channel order in OpenCV

OpenCV reads and modifies image pixel values

OpenCV image read and write

OpenCV reads live camera footage and video files