Getting Started with Videos

OpenCVOpenCVBeginner
Practice Now

Introduction

Welcome to this lab on how to get started with videos using OpenCV-Python! OpenCV (Open Source Computer Vision) is a powerful library designed for image processing, machine learning, and computer vision applications. In this lab, we'll be focusing on how to work with videos in OpenCV-Python.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL opencv(("`OpenCV`")) -.-> opencv/BasicOperationsGroup(["`Basic Operations`"]) opencv/BasicOperationsGroup -.-> opencv/imread("`Image Read`") opencv/BasicOperationsGroup -.-> opencv/video_capture("`VideoCapture`") opencv/BasicOperationsGroup -.-> opencv/fourcc("`VideoWriter Fourcc`") opencv/BasicOperationsGroup -.-> opencv/video_writer("`VideoWriter`") opencv/BasicOperationsGroup -.-> opencv/imwrite("`Image Write`") subgraph Lab Skills opencv/imread -.-> lab-14766{{"`Getting Started with Videos`"}} opencv/video_capture -.-> lab-14766{{"`Getting Started with Videos`"}} opencv/fourcc -.-> lab-14766{{"`Getting Started with Videos`"}} opencv/video_writer -.-> lab-14766{{"`Getting Started with Videos`"}} opencv/imwrite -.-> lab-14766{{"`Getting Started with Videos`"}} end

Reading a Video and Saving a Frame

To capture a video, you need to create a VideoCapture object. Here's an example of reading a video and saving each frame to the frame folder:

Video path is /home/labex/project/video.mp4

File path is /home/labex/project/read_video.py

Open the read_video.py file. Then input the following code.

import cv2
import os

## Check if the 'frame' folder exists. Create it if it doesn't.
folder = os.path.exists('frame')
if not folder:
	os.makedirs('frame')
	print('new folder...')
	print('OK')
else:
	print('There is this folder!')

## Frame number
number = 0

## Create a VideoCapture object
cap = cv2.VideoCapture('video.mp4')

while True:
    ## Read a frame from the video
    ret, frame = cap.read()

    ## Frame number added
    number = number + 1
    if ret:
        ## Save the frame
        cv2.imwrite(f"./frame/save{number}.jpg", frame)

    ## Exit the loop
    else:
        break

print('Each frame has been saved to the frame folder')

print('Video read successfully!')

## Release the VideoCapture object
cap.release()

In this example, we create a VideoCapture object by passing the path to the video file we want to read. We then use a while loop to read each frame of the video using the read() method. If the frame is successfully read, we use the imwrite() method to save the frame. Finally, we release the VideoCapture object.

You can run the following command in the terminal to execute.

python /home/labex/project/read_video.py

Or you can just click the button like this Run Python File in the top right corner to execute.

Afterward, wait for Terminal to output "Video read successfully!" and you will see the pictures of each frame in the frame folder.

Writing and Saving a Video

To write and save a video, you need to create a VideoWriter object. Here's an example of how to write and save a video:

Video path is /home/labex/project/video.mp4

File path is /home/labex/project/write_video.py

Open the write_video.py file. Then input the following code.

import cv2

## Create a VideoCapture object
cap = cv2.VideoCapture('video.mp4')

## Get the video frame size and frame rate
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = int(cap.get(cv2.CAP_PROP_FPS))

## Create a VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi', fourcc, fps, (width, height))

while True:
    ## Read a frame from the video
    ret, frame = cap.read()

    if ret:
        ## Process the frame
        ## ...

        ## Write the processed frame to the output video
        out.write(frame)

    else:
        break

print('Video save successfully!')

## Release the VideoCapture and VideoWriter objects
cap.release()
out.release()

In this example, we create a VideoCapture object by passing the path of the video file to be read. Then, we get the video frame size and frame rate using the get() method. Next, we create a VideoWriter object by passing the output file name, fourcc code, frame rate, and frame size. The fourcc code is a four-byte code used to specify the video codec. In this example, we use the XVID codec.

We then use a while loop to read each frame of the video using the read() method. If the frame is successfully read, we process it (e.g., apply filters) and write it to the output video using the write() method of the VideoWriter object. Finally, we release the VideoCapture and VideoWriter objects.

You can run the following command in the terminal to execute.

python /home/labex/project/write_video.py

Or you can just click the button like this Run Python File in the top right corner to execute.

Afterward, wait for Terminal to output "Video save successfully!" and you will see an output video called output.avi in the project folder.However, the current environment does not support the viewing of video files. You will need to download the file locally, as shown below, and then view it using the video player.

Download Video File
Download Video File

Summary

Congratulations! You have now learned how to read, display, write, and save videos using OpenCV-Python. With these basic skills, you can start exploring more advanced computer vision techniques and applications.

Feel free to expand on this tutorial by trying out different video formats, applying filters to the frames, or experimenting with object tracking and detection. The possibilities are endless!

Other OpenCV Tutorials you may like