欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

OpenCV写文件MP4 flv avi

程序员文章站 2022-07-02 08:39:53
...

除了ffmpeg写视频外,很多时候我们也采用Opencv写视频文件,官方案例:入口

其它一些参考文件:
ffmpeg movflags 参数说明
opencv写文件
这里说明一点就是writerAlias->setFourcc(cv::VideoWriter::fourcc(‘X’, ‘2’, ‘6’, ‘4’));编码出来是x264

不过opencv写的视频文件都比较大,暂时没有看到能控制码流的参数,特别avi达到了20Mb/s

下面是一个参考类:

#ifndef FILEWRITER_H
#define FILEWRITER_H

#include "writer.h"

#include <opencv.hpp>

namespace flow {


class FileWriter {
public:
  using FileWriterPtr=std::make_shared<FileWriter>;
  
  explicit FileWriter(const std::string &file) {
  m_address=file;
  }
  
  FileWriter() = delete;
  FileWriter(FileWriter &&) = delete;
  FileWriter(const FileWriter &) = delete;
  FileWriter &operator=(FileWriter &&) = delete;
  FileWriter &operator=(const FileWriter &) = delete;
  ~FileWriter()  = default;

  bool write(const cv::Mat &frame) ;
  void setFourcc(int fourcc) { m_fourcc = fourcc; }
  static FileWriterPtr create() { return FileWriterPtr(new FileWriter("./test.avi")); }
  
  bool open() ;
  bool close() ;

protected:
  // use 'int64_t' for memory padding
  int64_t m_fourcc = cv::VideoWriter::fourcc('D', 'I', 'V', 'X');
  cv::Ptr<cv::VideoWriter> m_videoFileWriter;
  std::string m_address{};
};

} // namespace flow
#endif // FILEWRITER_H

#include "filewriter.h"

#include "xlog/xlog.h"

namespace flow {

bool FileWriter::open() {
  LOG_INFO("Open file to write: {} ...", m_param.address);
  m_videoFileWriter.reset(new cv::VideoWriter());
  return m_videoFileWriter->open(m_address, static_cast<int>(m_fourcc),
                                 double(25),
                                 cv::Size(2560, 1440));
}

bool FileWriter::close() {
  m_videoFileWriter.release();
  return true;
}

bool FileWriter::write(const cv::Mat &frame) {
  assert(!m_videoFileWriter.empty());

  cv::Mat dst;
  cv::Size size = cv::Size(2560, 1440);
  if (size != frame.mat.size()) {
    dst = cv::Mat(size, frame.type());
    cv::resize(frame, dst, size);
  } else {
    dst = frame;
  }

  *m_videoFileWriter << dst;
  return true;
}
using FileWriterPtr=std::make_shared<FileWriter>;
} // namespace flow

/main函数/
//example

void createMat(cv::Mat &mat){
//somewhere cteate mat
}
int main(){
FileWriterPtr writerPtr=FileWriter::create("./test.avi");
writerPtr->setFourcc(cv::VideoWriter::fourcc('X', '2', '6', '4'));//h264 fourcc('D', 'I', 'V', 'X') mpeg

writerPtr.open();
while(n < 1000){
cv::Mat mat;
createMat(mat);//somewhere get some mat
writerPtr.write(mat);
}
writerPtr.close();
}