opencv 读写视频
OpenCV 2 中提供了两个类来实现视频的读写。读视频的类是 VideoCapture, 写视频的类是 VideoWriter。
一、读视频
VideoCapture 既可以从视频文件读取信息,也可以从计算机外接摄像头读取图像信息。如果 VideoCapture 对象已经创建,也可以使用 VideoCapture::open() 打开,VideoCapture::open() 函数会自动调用 VideoCapture::release()函数,先释放已经打开的视频,然后再打开新视频。
如果要读一帧,可以使用 VideoCapture::read()函数。VideoCapture 类重载了>> 操作符,实现了读视频帧的功能。
二、写视频
与读视频不同的是,你需要在创建视频时设置一系列参数,包括:文件名,编解码器,帧率,宽度和高度等。编解码器 使用四个字符表示,可以是 CV_FOURCC ‘M’,’J’,’P’,’G’)、CV_FOURCC(‘X’,’V’,’I’,’D’) 及 CV_FOURCC(‘D’,’I’,’V’,’X’)等。如果使用某种编解码器无法创建视频文件,请尝试其他的编解码器。
将图像写入视频可以使用 VideoWriter::write() 函数,VideoWriter 类中也重载 了<< 操作符。
注:写入的图像尺寸必须与创建视频时指定的尺寸一致。
C++代码如下:
#include <iostream>
#include "opencv2/opencv.hpp"
//using namespace cv;
int main(int argc, char** argv){
const int cam_width = 1280;//设置摄像头尺寸,根据自己的摄像头选择
const int cam_height = 720;
cv::VideoCapture capture(0);
capture.set(CV_CAP_PROP_FRAME_WIDTH, cam_width);
capture.set(CV_CAP_PROP_FRAME_HEIGHT, cam_height);
cv::VideoWriter writer("video.avi", CV_FOURCC('M','J','P','G'), 25.0, cv::Size(1280, 720),1);
//cv::VideoCapture cap("video.avi");
if(!capture.isOpened()) {
std::cerr << "Can not open a camera or file." << std::endl;
return -1;
}
if(!writer.isOpened()) {
std::cerr << "Can not create video file.\n" << std::endl;
return -1;
}
cv::Mat frame;
while(true){
capture>>frame;
cv::imshow("video",frame);
cv::waitKey(10);
writer<<frame;
if (cv::waitKey(10) == 27){
break;
}
}
return 0;
}
//g++ 2-video.cpp -o video `pkg-config --cflags --libs opencv` 编译