opencv3/C + + video reading and writing

Video reading

Video reading mainly uses the methods under VideoCapture class to open the video and obtain the frames in the video. The specific examples are as follows:

#include<iostream>
#include<opencv2/opencv.hpp>
using namespace cv;

int main()
{
    VideoCapture capture;
    Mat frame;
    frame= capture.open("E:/image/a1.avi");
    if(!capture.isOpened())
    {
        printf("can not open ...\n");
        return -1;
    }
    namedWindow("output", CV_WINDOW_AUTOSIZE);

    while (capture.read(frame))
    {
        imshow("output", frame);
        waitKey(10);
    }
    capture.release();
    return 0;
}

When the parameter of capture.open() is 0, it is to read the camera:

frame= capture.open(0);

Video write

Get the video through the camera, and then get the width and height of the current frame through capture.get (CV cap Pro frame width), and create a VideoWriter class object writer to write the video.
Simple video processing can be performed before writing.

#include<iostream>
#include<opencv2/opencv.hpp>
using namespace cv;

int main()
{
    VideoCapture capture;
    capture.open(0);
    if(!capture.isOpened())
    {
        printf("can not open ...\n");
        return -1;
    }

    Size size = Size(capture.get(CV_CAP_PROP_FRAME_WIDTH), capture.get(CV_CAP_PROP_FRAME_HEIGHT));
    VideoWriter writer;
    writer.open("E:/image/a2.avi", CV_FOURCC('M', 'J', 'P', 'G'), 10, size, true);

    Mat frame, gray;
    namedWindow("output", CV_WINDOW_AUTOSIZE);

    while (capture.read(frame))
    {
        //Convert to black and white image
        cvtColor(frame, gray, COLOR_BGR2GRAY);  
        //Binary treatment 
        threshold(gray, gray, 0, 255, THRESH_BINARY | THRESH_OTSU);
        cvtColor(gray, gray, COLOR_GRAY2BGR);
        imshow("output", gray);
        writer.write(gray);
        waitKey(10);
    }

    waitKey(0);
    capture.release();
    return 0;
}

Keywords: OpenCV

Added by jpowermacg4 on Mon, 04 May 2020 02:01:04 +0300