opencv 从摄像头中读取视频并保存(c++版)

本文介绍如何使用OpenCV进行视频文件的读写操作,包括VideoCapture和VideoWriter类的基本使用方法,如打开摄像头、读取视频帧、保存视频等。

opencv中的视频操作函数如下表所列:

VideoCapture
VideoCapture::VideoCapture
VideoCapture::open
VideoCapture::isOpened
VideoCapture::release
VideoCapture::grab
VideoCapture::retrieve
VideoCapture::read
VideoCapture::get
VideoCapture::set
VideoWriter
VideoWriter::VideoWriter
ReleaseVideoWriter
VideoWriter::open
VideoWriter::isOpened
VideoWriter::write

感兴趣的可以自己查看官方文档。
这里主要介绍几个本文中使用到的函数。

C++: VideoWriter::VideoWriter()
C++: VideoWriter::VideoWriter(const string& filename, int fourcc, double fps, Size frameSize, bool isColor=true)

Parameters:
filename – Name of the output video file.
fourcc – 4-character code of codec used to compress the frames. For example, CV_FOURCC(‘P’,’I’,’M’,’1’) is a MPEG-1 codec, CV_FOURCC(‘M’,’J’,’P’,’G’) is a motion-jpeg codec etc. List of codes can be obtained at Video Codecs by FOURCC page. (如果,这里输入-1.在windows下会弹出一个对话框让你选择视频解压格式。)
fps – Framerate of the created video stream.
frameSize – Size of the video frames.
isColor – 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).

    //视频保存位置
    string outputVideoPath = "..\\images\\test.avi";  

    //打开摄像头
    VideoCapture capture0(0);  

    VideoWriter outputVideo;
    //获取当前摄像头的视频信息
    cv::Size S = cv::Size((int)capture0.get(CV_CAP_PROP_FRAME_WIDTH),
                          (int)capture0.get(CV_CAP_PROP_FRAME_HEIGHT));
    //打开视频路劲,设置基本信息 open函数中你参数跟上面给出的VideoWriter函数是一样的
    outputVideo.open(outputVideoPath, -1, 30.0, S, true);
    //CV_FOURCC('P','I','M','1')

    if (!outputVideo.isOpened()) {
        cout << "fail to open!" << endl;
        return -1;
    }


    cv::Mat frameImage;
    int count = 0;

    while(true) {
        //读取当前帧
        capture0 >> frameImage;

        if (frameImage.empty()) break;

        ++count;
        //输出当前帧
        cv::imshow("output", frameImage);
        //保存当前帧
        outputVideo << frameImage;

        if (char(waitKey(1)) == 'q') break;
    }

    std::cout << "TotalFrame: " << count << std::endl;
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值