OpenCV - Read, Write and Edit Videos

wordcloud

Capture video from a webcam

OpenCV provides a VideoCapture class that allows us to open a video file or a capturing device (like a webcam) or an IP video stream for video capturing. The first argument is either an index or a filename. index is the id of the video capturing device. index 0 opens default camera with default backend. In most notebook computers, webcam is the default camera. So we will use 0 as the index. If your webcam is camera 2, then you need to use index 1.

VideoCapture.read() function grabs video frames and returns a tuple. The first value in the tuple is a boolean value - True if a frame is grabbed and False if no frames are grabbed. Let's call it frameFlag. The second value (called frame here) returns an image of a video frame.

We will use an infinite while loop to capture video frames continously from a webcam and display them using imshow(), which we used to display images here. We will break the while loop using a keyboard key 'x'. You can use any key of your choice.

In [1]:
# Importing OpenCV library
import cv2
In [2]:
video=cv2.VideoCapture(0) # specify device id 0 for default camera (webcam)
while True:
    frameFlag,frame=video.read() # capture each video frame
    print(frameFlag, end=" ") # check if each frame is successfully captured
    cv2.imshow("Frames",frame) # dislay each video frame
    if cv2.waitKey(1)&0xFF==ord("x"): # Press 'x' to quit
        break
video.release() # Release VideoCapture object (webcam device)
cv2.destroyAllWindows() # close all display windows
True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True 

The output is a window of continous video frames captured from a webcam until the x key is pressed. The print output shows the boolean values of the first element of the VideoCapture.read() tuple. It appears that all frames were successfully read without failure.

[^top]

Capture video from a webcam in grayscale

We already used COLOR_BGR2RBG to convert BGR image array to RBG to display in PIL here. Now we will use COLOR_BGR2GRAY to convert each video frame to grayscale.

In [3]:
video=cv2.VideoCapture(0) # specify device id 0 for default camera (webcam)
while True:
    frameFlag,frame=video.read() # capture each video frame
    print(frameFlag, end=" ") # check if each frame is successfully captured
    grayframe=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
    cv2.imshow("Gray frames",grayframe) # dislay each video frame
    if cv2.waitKey(1)&0xFF==ord("x"): # Press 'x' to quit
        break
video.release() # Release VideoCapture object (webcam device)
cv2.destroyAllWindows() # close all display windows
True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True 

The output is a display of continous grayscale video frames.

[^top]

Capture video from a file

As mentioned earlier, VideoCapture class also accepts filename as an argument to read video files.

In [4]:
video=cv2.VideoCapture("https://go.allika.eu.org/catslomo") # specify the filename (path or URL)
while True:
    frameFlag,frame=video.read() # capture each video frame
    print(frameFlag, end=" ") # check if each frame is successfully captured
    if frameFlag: # display video frames till end of the video. frameFlag becomes False after the video ends.
        cv2.imshow("Frames",frame) # dislay each video frame
        cv2.waitKey(1)
    else:
        break  
video.release() # Release VideoCapture object (webcam device)
cv2.destroyAllWindows() # close all display windows
True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True False 

Following is the video output of the code above. As the video ends, the frameFlag becomes False and the while loop breaks.

[^top]

Edit a video and write to a file

We will perform the following operations.

  • Read a video file or a webcam
  • Speed up the video playrate by 2x.
  • Convert it in to grayscale
  • Write it to a file.

OpenCV's VideoCapture class provides the following functions that we will use:

  • isOpened(): Returns true if video capturing has been initialized already. This is to check that the video is opened properly before editing.
  • get() to obtain following VideoCapture properties that we will use for editing and writing the video. The values retuned are of data type float, so they are converted to int.
    • Frame width: CAP_PROP_FRAME_WIDTH
    • Frame height: CAP_PROP_FRAME_HEIGHT
    • Frame rate (Frame per second, FPS): CAP_PROP_FPS

VideoWriter class is used for writing a video to a file. It accepts the following arguments:

  • filename: Output file name or path.
  • fourcc: FOURCC video codec. We use X246 codec as it produces comparitively smaller file sizes.
  • fps: Frame rate
  • size: video size (width x height)
  • isColor: Boolean value. If it is not zero, the encoder will expect and encode color frames, otherwise it will work with grayscale frames (the flag is currently supported on Windows only)
In [5]:
# Reading the input file.
input_video=cv2.VideoCapture("https://go.allika.eu.org/catslomo") # specify the filename (path or URL)
# input_video=cv2.VideoCapture(0) # Uncomment this line to capture from a webcam.

if input_video.isOpened(): # Ensure video is opened before editing
    # Get input video properties
    width=int(input_video.get(cv2.CAP_PROP_FRAME_WIDTH))
    height=int(input_video.get(cv2.CAP_PROP_FRAME_HEIGHT))
    fps=int(input_video.get(cv2.CAP_PROP_FPS))
    print("Video size: {}x{} pixels\nFrame rate: {} FPS".format(width,height,fps))
    # Defining output object
    output_video=cv2.VideoWriter("../../files/ml/002/cat_slomo_gray.mp4", # Output file
                                cv2.VideoWriter_fourcc(*'X264'), # FOURCC codec
                                2*fps, # To speed up the video by 2x, we multply FPS by 2
                                (width,height)) # video size
    while True:
        frameFlag,frame=input_video.read() # reading input
        if frameFlag:
            gray_frame=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) # converting to grayscale
            # write frame to output
            output_video.write(gray_frame)
            # display output frame
            cv2.imshow("Frames",gray_frame)
            # Press 'x' to stop capturing
            if cv2.waitKey(1)&0xFF==ord("x"):
                break
        else:
            break
    
input_video.release() # Release VideoCapture object (input file or webcam device)
output_video.release() # Release VideoWriter object (output file)
cv2.destroyAllWindows() # close all display windows
Video size: 480x270
Frame rate: 30FPS

Following is the output video. Its in grayscale and play 2x faster.

[^top]

Last updated 2020-12-16 16:39:09.290219 IST

Comments