OepnCV Image, Video, Cam Examples

To know how to use OpenCV, it is easier to see examples than to know each function.

Python and C++ are similar. If you know one language, it is easy to learn the other; compare the Python and C++ code that performs the same.

C++

image_show.cpp
#include <opencv2/opencv.hpp>
 
int main( void )
{
    cv::Mat img;
 
    /// Reads image.jpg and assigns it in the img variable.
    img = cv::imread( "image.jpg" );
 
    /// Shows the img on the image window.
    cv::imshow( "image", img );
 
    /// Waits for a key event infinitely.
    cv::waitKey();
    cv::destroyAllWindows();
 
    return 0;
}
$ g++ image_show.cpp -o image_show $(pkg-config opencv4 --libs --cflags)
 
$ ./image_show

Python

image_show.py
import cv2 as cv
 
# Reads image.jpg and assigns it in the img variable.
img = cv.imread("image.jpg")
 
# Shows the img on the image window.
cv.imshow("image", img)
 
# Waits for a key event infinitely.
cv.waitKey()
cv.destroyAllWindows()
$ python3 image_show.py

C++

video_show.cpp
#include <opencv2/opencv.hpp>
 
int main( void )
{
    cv::Mat frame;
 
    /// Opens video.mp4.
    cv::VideoCapture cap;
    cap.open( "video.mp4" );
 
    /// Gets frames per second.
    int fps = cap.get( cv::CAP_PROP_FPS );
 
    if( cap.isOpened() )
    {
        for( ;; )
        {
            /// Reads a frame and assigns it in to the frame variable.
            cap >> frame;
            if( frame.empty() )
            {
                break;
            }
 
            /// Shows the frame on the video window.
            cv::imshow( "video", frame );
 
            /// Waits for a key event for 1000/fps ms.
            /// If the key event occurs, it breaks the loop. 
            if( ( cv::waitKey( 1000 / fps ) & 0xFF ) != 0xFF )
            {
                break;
            }
        }
    }
 
    cap.release();
    cv::destroyAllWindows();
 
    return 0;
}

Python

$ g++ video_show.cpp -o video_show $(pkg-config opencv4 --libs --cflags)
 
$ ./video_show
video_show.py
import cv2 as cv
 
# Opens video.mp4.
cap = cv.VideoCapture("video.mp4")
 
# Gets frames per second.
fps = cap.get(cv.CAP_PROP_FPS)
 
if cap.isOpened():
    while True:
        # Reads a frame and assigns it in to the frame variable.
        is_sucess, frame = cap.read()
        if not is_sucess:
            break
 
        # Shows the frame on the video window.
        cv.imshow("video", frame)
 
 
        if cv.waitKey(int(1000/fps)) & 0xFF != 255:
            '''
            Waits for a key event for 1000/fps ms.
            If the key event occurs, it breaks the loop.
            '''
            break
 
cap.release()
cv.destroyAllWindows()
$ python3 video_show.py

Before you start, check your cam info using the command below.

$ v4l2-ctl --all --list-formats-ext
If you want to know specific cam device file like /dev/video0.
Execute the command v4l2-ctl –all –list-formats-ext -d /dev/video0.

C++

cam_record.cpp
#include <opencv2/opencv.hpp>
 
const int OUTPUT_VIDEO_WIDTH  = 640;
const int OUTPUT_VIDEO_HEIGHT = 480;
 
int main( void )
{
    cv::Mat frame;
 
    /// Opens the cam number 0. (/dev/video0)
    cv::VideoCapture cap;
    cap.open( 0, cv::CAP_V4L2 );
 
    /// Sets the width and height in pixel.
    cap.set( cv::CAP_PROP_FRAME_WIDTH, OUTPUT_VIDEO_WIDTH );
    cap.set( cv::CAP_PROP_FRAME_HEIGHT, OUTPUT_VIDEO_HEIGHT );
 
    /// Sets the format of pixel.
    cap.set( cv::CAP_PROP_FOURCC, cv::VideoWriter::fourcc( 'M', 'J', 'P', 'G' ) );
 
    /// Sets the recording properties.
    cv::VideoWriter out;
    /// Saves as record.avi and uses FFmpeg.
    out.open( "record.avi", cv::VideoWriter::fourcc( 'F', 'M', 'P', '4' ), 25.0,
              cv::Size( OUTPUT_VIDEO_WIDTH, OUTPUT_VIDEO_HEIGHT ) );
 
    if( cap.isOpened() && out.isOpened() )
    {
        for( ;; )
        {
            try
            {
                /// Reads a frame and assigns it in the frame variable.
                cap.read( frame );
            }
            catch( cv::Exception& e )
            {
                continue;
            }
 
            if( frame.empty() )
            {
                break;
            }
 
            /// Writes the frame to record.avi.
            out.write( frame );
 
            /// Shows the frame on the video window.
            cv::imshow( "video", frame );
 
            /// Waits for a key event for 1 ms.
            /// If the key event occurs, it breaks the loop.
            if( ( cv::waitKey( 1 ) & 0xFF ) != 0xFF )
            {
                break;
            }
        }
    }
 
    cap.release();
    out.release();
    cv::destroyAllWindows();
 
    return 0;
}
$ g++ cam_record.cpp -o cam_record $(pkg-config opencv4 --libs --cflags)
 
$ ./cam_record

Python

cam_record.py
import cv2 as cv
 
OUTPUT_VIDEO_WIDTH = 640
OUTPUT_VIDEO_HEIGHT = 480
 
# Opens the cam number 0. (/dev/video0)
cap = cv.VideoCapture(0, cv.CAP_V4L2)
 
# Sets the width and height in pixel.
cap.set(cv.CAP_PROP_FRAME_WIDTH, OUTPUT_VIDEO_WIDTH)
cap.set(cv.CAP_PROP_FRAME_HEIGHT, OUTPUT_VIDEO_HEIGHT)
 
# Sets the format of pixel.
cap.set(cv.CAP_PROP_FOURCC, cv.VideoWriter_fourcc(*'MJPG'))
 
'''
Sets the recording properties.
Saves as record.avi and uses FFmpeg.
'''
fourcc = cv.VideoWriter_fourcc(*'FMP4')
out = cv.VideoWriter('record.avi', fourcc, 25.0,
                      (OUTPUT_VIDEO_WIDTH, OUTPUT_VIDEO_HEIGHT))
 
if cap.isOpened() and out.isOpened():
    while True:
        try:
            # Reads a frame and assigns it in the frame variable.
            is_sucess, frame = cap.read()
        except cv.error as e:
            continue
 
        if not is_sucess:
            break
 
        # Writes the frame to record.avi.
        out.write(frame)
 
        #  Shows the frame on the video window.
        cv.imshow("video", frame)
 
        if cv.waitKey(1) & 0xFF != 255:
            '''
            Waits for a key event for 1 ms.
            If the key event occurs, it breaks the loop.
            '''
            break
 
cap.release()
out.release()
cv.destroyAllWindows()
$ python3 cam_record.py