您当然可以使用VideoWriter
类,但是您需要使用代表H264标准的正确FourCC代码 。 FourCC代表“四字符代码”,它是媒体文件中使用的视频编解码器,压缩格式,颜色或像素格式的标识符。
具体来说,当创建VideoWriter
对象时,在构造它时要指定FourCC代码。有关更多详细信息,请查阅OpenCV文档: http : //docs.opencv.org/trunk/modules/highgui/doc/reading_and_writing_images_and_video.html#videowriter-videowriter
我假设您使用的是C ++,因此VideoWriter
构造函数的定义为:
VideoWriter::VideoWriter(const String& filename, int fourcc,
double fps, Size frameSize, bool isColor=true)
filename
是视频文件的输出, fourcc
是您要使用的代码的FourCC代码, fps
是所需的帧速率, frameSize
是所需的视频尺寸, isColor
指定是否要使用视频颜色。即使FourCC使用四个字符,OpenCV仍具有用于解析FourCC并输出单个整数ID的实用程序,该ID用作查找以便能够将正确的视频格式写入文件。您使用CV_FOURCC
函数,并指定四个单个字符-每个对应于所需编解码器的FourCC代码中的单个字符。
具体来说,您可以这样称呼它:
int fourcc = CV_FOURCC('X', 'X', 'X', 'X');
用属于FourCC的每个字符替换X
(按顺序)。因为您需要H264标准,所以可以这样创建一个VideoWriter
对象:
#include <iostream> // for standard I/O
#include <string> // for strings
#include <opencv2/core/core.hpp> // Basic OpenCV structures (cv::Mat)
#include <opencv2/highgui/highgui.hpp> // Video write
using namespace std;
using namespace cv;
int main()
{
VideoWriter outputVideo; // For writing the video
int width = ...; // Declare width here
int height = ...; // Declare height here
Size S = Size(width, height); // Declare Size structure
// Open up the video for writing
const string filename = ...; // Declare name of file here
// Declare FourCC code
int fourcc = CV_FOURCC('H','2','6','4');
// Declare FPS here
int fps = ...;
outputVideo.open(filename, fourcc, fps, S);
// Put your processing code here
// ...
// Logic to write frames here... see below for more details
// ...
return 0;
}
另外,您可以在声明VideoWriter
对象时执行以下VideoWriter
:
VideoWriter outputVideo(filename, fourcc, fps, S);
如果使用上述方法,则不需要调用open
因为这将自动打开写入器以将框架写入文件。
如果不确定计算机是否支持H.264,请指定-1
作为FourCC代码,并且在运行该代码时应弹出一个窗口,该窗口显示计算机上所有可用的视频编解码器。我想提一下,这仅适用于Windows。当您指定-1
时,Linux或Mac OS不会弹出此窗口。换一种说法:
VideoWriter outputVideo(filename, -1, fps, S);
如果计算机上不存在H.264,则可以选择最合适的一种。完成此操作后,OpenCV将创建正确的FourCC代码,以输入到VideoWriter
构造函数中,这样您将获得一个VideoWriter实例,该实例代表一个VideoWriter
并将该类型的视频写入文件。
准备好框架并将其存储在frm
以写入文件后,您可以执行以下任一操作:
outputVideo << frm;
要么
outputVideo.write(frm);
另外,这是一个有关如何在OpenCV中读取/编写视频的教程: http : //docs.opencv.org/3.0-beta/doc/py_tutorials/py_gui/py_video_display/py_video_display.html-但是,它是为Python编写的,但是最好知道的是该链接的底部附近,有一个已知的适用于每个操作系统的FourCC代码列表。顺便说一句,他们为H264标准指定的FourCC代码实际上是'X','2','6','4'
,因此,如果'H','2','6','4'
不起作用,将H
替换为X
另一个小注意事项。如果您使用的是Mac OS,则需要使用'A','V','C','1'
或'M','P','4','V'
。根据经验,尝试指定FourCC代码时, 'H','2','6','4'
或'X','2','6','4'
似乎不起作用。
0
如何在OpenCV中使用VideoWriter类使用H.264压缩来编写视频?我基本上想从网络摄像头中获取视频,并在按下角色后将其保存。使用MPEG4 Part 2压缩时,输出视频文件很大。