Successful test is completed Opencv opens the camera and saves the video to the local path Ubuntu (similar under win)

Not much to say, send the code, change the file save path of the code below to use it! ! !

#include <opencv2/core.hpp>
#include <opencv2/videoio.hpp>
#include <opencv2/highgui.hpp>
#include <iostream>
#include <stdio.h>
using namespace cv;
using namespace std;

int main(int, char**)
{
    
    
    Mat src;
    //打开摄像头资源
    VideoCapture cap(0);
    //检查是否成功打开
    if (!cap.isOpened()) {
    
    
        cerr << "ERROR! Unable to open camera\n";
        return -1;
    }
    // 将摄像头传到Mat格式里面
    cap >> src;
    // 检查是否传入成功
    if (src.empty()) {
    
    
        cerr << "ERROR! blank frame grabbed\n";
        return -1;
    }
    bool isColor = (src.type() == CV_8UC3);
    //初始化摄像头写入的对象
    VideoWriter writer;
    int codec = VideoWriter::fourcc('M', 'J', 'P', 'G');  // 选择视频的格式
    double fps = 25.0;                          // 视频的帧数
    string filename = "/home/sms/tu/live.avi";             // 视频保存的路径
    writer.open(filename, codec, fps, src.size(), isColor);
    // 检查视频是否读取出来
    if (!writer.isOpened()) {
    
    
        cerr << "Could not open the output video file for write\n";
        return -1;
    }

    cout << "Writing videofile: " << filename << endl
         << "Press any key to terminate" << endl;
    for (;;)
    {
    
    

        if (!cap.read(src)) {
    
    
            cerr << "ERROR! blank frame grabbed\n";
            break;
        }
        // 开始写入视频
        writer.write(src);
        // 显示图像
        imshow("Live", src);
        if (waitKey(5) >= 0)
            break;
    }
    // 视频已经可以保存到之前写的文件路径下,记得文件的后缀名称不要忘记写格式xxx.avi
    return 0;
}

If it is not available, please comment below.

Guess you like

Origin blog.csdn.net/Msyusheng/article/details/111106427