OpenCV读取视频,打开摄像头,写入视频文件

1、打开本地视频文件
OpenCV通过VideoCapture类实现视频文件的读取。实现代码如下:

#include <opencv2\core\core.hpp>
#include <opencv2\highgui\highgui.hpp>
#include <opencv2\imgproc\imgproc.hpp>
#include <iostream>
using namespace std;
using namespace cv;


void processimage(Mat &frame)
{
    circle(frame, Point(cvRound(frame.cols / 2),
        cvRound(frame.rows/2)),150,Scalar(0,0,255),2,8);
}
int main()
{
    string filename = "D:\\pic\\demo.avi";
    VideoCapture capture;
    capture.open(filename);

    double rate = capture.get(CV_CAP_PROP_FPS);//获取视频文件的帧率 

    int delay = cvRound(1000.00 / rate);

    if (!capture.isOpened())
    {
        cout << "open failed" << endl;
        return -1;
    }
    else
    {
        while (true)
        {
            Mat frame;
            capture >> frame;//读出每一帧图像
            if (frame.empty())
                break;
            imshow("处理前视频", frame);
            processimage(frame);
            imshow("处理后视频", frame);
            waitKey(delay);
        }
    }
    system("pause");
    return 0;
}

2、打开摄像头,采集图像信息,保存视频
在这个例子中还要使用的一个类VideoWriter,这个类为保存图像信息到视频。

VideoCapture capture(0);//如果是笔记本,0打开的是自带的摄像头,1 打开外接的相机  
    double rate = 25.0;//视频的帧率  
    Size videoSize(1280, 960);
    VideoWriter writer("VideoTest.avi", CV_FOURCC('M', 'J', 'P', 'G'), rate, videoSize);
    Mat frame;

    while (capture.isOpened())
    {
        capture >> frame;
        writer << frame;
        imshow("video", frame);
        if (waitKey(20) == 27)//27是键盘摁下esc时,计算机接收到的ascii码值  
        {
            break;
        }
    }

猜你喜欢

转载自blog.csdn.net/u014801811/article/details/80038827