文章目录

  • 写入图片帧信息
  • C/CPP示例
  • Python示例

在《OpenCV API使用笔记 —— 1. 如何打开摄像头或视频文件》 介绍过使用「VideoCapture」类,可以打开摄像头或视频文件,如果数据经过处理后,我们希望保存这些数据时,又该怎么做呢。

写入图片帧信息

我们这里主要用到一个名为 VideoWriter 的类,它可以帮助我们达成以上目标。现在来看看「VideoWriter」类的原型:

cv::VideoWriter::VideoWriter();cv::VideoWriter::VideoWriter(
const String &  filename,
int     fourcc,
double  fps,
Size    frameSize,
bool    isColor = true
);cv::VideoWriter::VideoWriter(
const String &  filename,
int     apiPreference,
int     fourcc,
double  fps,
Size    frameSize,
bool    isColor = true
);

对于C来说,可以使用上面三个构造函数中的任意一个,而我个人比较偏好使用第二个构造函数。以上参数名分别表示如下含义:

  • filename,保存的视频文件名
  • apiPreference,可以用来指定保存视频时使用的解码器,可以使用「cv::CAP_FFMPEG」、「cv::CAP_GSTREAMER」等;如果使用第一个或第二个构造函数,那么当程序运行在Linux系统时,它会默认使用FFMPEG,Windows时使用FFMPEG或VFW,如果是MacOS时,则使用QTKit。
  • fourcc,视频压缩指令,使用4个字节进行表示。例如「VideoWriter::fourcc(‘P’,‘I’,‘M’,‘1’)」使用 MPEG-1 codec, 「VideoWriter::fourcc(‘M’,‘J’,‘P’,‘G’)」使用 motion-jpeg codec. 关于codec的相关指令,可以在 codecs 里找到详细列表。
  • fps,用于指定视频的帧率
  • frameSize,用于指定视频的帧大小
  • isColor,默认以彩色模式处理数据,如果设置为false时,它将以灰白模式处理数据。

C/CPP示例

#include <iostream> // for standard I/O
#include <string>   // for strings
#include <opencv2/core.hpp>     // Basic OpenCV structures (cv::Mat)
#include <opencv2/videoio.hpp>  // Video write
using namespace std;
using namespace cv;static void help()
{cout<< "------------------------------------------------------------------------------" << endl<< "This program shows how to write video files."                                   << endl<< "You can extract the R or G or B color channel of the input video."              << endl<< "Usage:"                                                                         << endl<< "./video-write <input_video_name> [ R | G | B] [Y | N]"                          << endl<< "------------------------------------------------------------------------------" << endl<< endl;
}int main(int argc, char *argv[])
{help();if (argc != 4){cout << "Not enough parameters" << endl;return -1;}const string source      = argv[1];           // the source file nameconst bool askOutputType = argv[3][0] =='Y';  // If false it will use the inputs codec typeVideoCapture inputVideo(source);              // Open inputif (!inputVideo.isOpened()){cout  << "Could not open the input video: " << source << endl;return -1;}string::size_type pAt = source.find_last_of('.');                  // Find extension pointconst string NAME = source.substr(0, pAt) + argv[2][0] + ".avi";   // Form the new name with containerint ex = static_cast<int>(inputVideo.get(CAP_PROP_FOURCC));     // Get Codec Type- Int form// Transform from int to char via Bitwise operatorschar EXT[] = {(char)(ex & 0XFF) , (char)((ex & 0XFF00) >> 8),(char)((ex & 0XFF0000) >> 16),(char)((ex & 0XFF000000) >> 24), 0};Size S = Size((int) inputVideo.get(CAP_PROP_FRAME_WIDTH),    // Acquire input size(int) inputVideo.get(CAP_PROP_FRAME_HEIGHT));VideoWriter outputVideo;                                        // Open the outputif (askOutputType)outputVideo.open(NAME, ex=-1, inputVideo.get(CAP_PROP_FPS), S, true);elseoutputVideo.open(NAME, ex, inputVideo.get(CAP_PROP_FPS), S, true);if (!outputVideo.isOpened()){cout  << "Could not open the output video for write: " << source << endl;return -1;}cout << "Input frame resolution: Width=" << S.width << "  Height=" << S.height<< " of nr#: " << inputVideo.get(CAP_PROP_FRAME_COUNT) << endl;cout << "Input codec type: " << EXT << endl;int channel = 2; // Select the channel to saveswitch(argv[2][0]){case 'R' : channel = 2; break;case 'G' : channel = 1; break;case 'B' : channel = 0; break;}Mat src, res;vector<Mat> spl;for(;;) //Show the image captured in the window and repeat{inputVideo >> src;              // readif (src.empty()) break;         // check if at endsplit(src, spl);                // process - extract only the correct channelfor (int i =0; i < 3; ++i)if (i != channel)spl[i] = Mat::zeros(S, spl[0].type());merge(spl, res);//outputVideo.write(res); //save oroutputVideo << res;}cout << "Finished writing" << endl;return 0;
}

上面的内容相对比较复杂,不过主要步骤如下:

// 创建output
VideoWriter outputVideo;// 指定参数
if (askOutputType)outputVideo.open(NAME, ex=-1, inputVideo.get(CAP_PROP_FPS), S, true);
elseoutputVideo.open(NAME, ex, inputVideo.get(CAP_PROP_FPS), S, true);// 写入数据
outputVideo << res;

如果对于Python来说,上述执行步骤就可以变得更简单了

Python示例

import cv2cap = cv2.VideoCapture(0)
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = 15
print(f"width: {width}, height: {height}, fps: {fps}")fourcc = cv2.VideoWriter_fourcc(*"DIVX")
writer = cv2.VideoWriter("output.avi", fourcc, fps, (width, height))while True:ret, frame = cap.read()if not ret:breakcv2.imshow("Frame", frame)writer.write(frame)if cv2.waitKey(1) & 0xFF == ord("q"):breakwriter.release()
cap.release()

OpenCV API使用笔记 —— 4. 如何保存视频文件相关推荐

  1. 保存视频文件到相册视频的时长为0

    问题:保存视频文件到相册视频的时长为0: 代码: String fileName = FileManagerUtil.getFileName(filePath); String mimeType =  ...

  2. 基于VFW实现摄像头录制并保存视频文件

    基于VFW实现摄像头录制并保存视频文件 本文介绍了通过使用Windows提供的VFW(Microsoft Video for Windows)实现摄像头的开启和视频文件的保存. 主要接口函数介绍 1. ...

  3. python读视频文件_python读取和保存视频文件

    如何用python实现视频关键帧提取并保存为图片?也许你会觉得对小编多做一点事你会觉得你很爽,可是在小编看来这是不屑的 import cv2vc = cv2.VideoCapture('Test.av ...

  4. python(opencv + pyaudio + moviepy)实现录制音视频文件并合并

    使用opencv录制视频文件 def record_webcam(filename):"""cv2.VideoCapture(0, cv2.CAP_DSHOW)参数1:打 ...

  5. python读取视频显示视频和保存视频文件

    为了获取视频,应该创建一个 VideoCapture 对象.他的参数可以是设备的索引号,或者是一个视频文件.设备索引号就是在指定要使用的摄像头. 一般的笔记本电脑都有内置摄像头.所以参数就是 0.你可 ...

  6. 【opencv】VideoCapture打不开本地视频文件或者网络IP摄像头

    1.前提:成功打开本地USB摄像头 // 创建VideoCapture对象 VideoCapture vc = new VideoCapture(); // 可以成功打开本地USB摄像头 // 参数可 ...

  7. iOS开发 Tips 保存视频文件到相册

    需要遵守这个代理 UIImagePickerControllerDelegate // path 为视频的绝对路径 /var/mobile/Containers/Data/Application/XX ...

  8. [opencv][原创]关于opencv-python的cv2保存视频不支持H264格式问题探讨

    项目有个不合理要求,能够在chrome浏览器打开播放,但是cv2根本不支持H264,由于版权原因,官方不支持h264格式所以当你使用诸如XVID,MJPG等虽然不影响使用和正常播放,但是就是无法在浏览 ...

  9. OpenCV API使用笔记 —— 3. 如何读取和保存图片

    文章目录 读取图片数据 参数说明 支持格式 保存图片数据 参数说明 用例 在某些时候,我们可能需要在图像数据被处理后保存结果.对于 OpenCV 来说,我们需要保存的主要有两种数据,一种是图片,还有一 ...

最新文章

  1. [算法]华为笔试题——拼音与英文转换
  2. 读书笔记《Hadoop开源云计算平台》
  3. 《大数据原理:复杂信息的准备、共享和分析》一一2.5 在标识符中嵌入信息:不推荐...
  4. python中常见的15中面试题
  5. Android官方开发文档Training系列课程中文版:创建自定义View之View的交互
  6. 寻宝处理器的引人入胜之旅——《大话处理器》新书出炉
  7. java控制台代码_Java控制台常用命令
  8. python opencv_Python open()
  9. asp.net中调用javascript自定义函数的方法(包括引入JavaScript文件)总结
  10. 应该如何理解mobx_MobX入门
  11. Servlet之间的跳转(MVC模式)
  12. centos7 安装 卸载docker
  13. Visual Studio 2012 激活码
  14. matlab 读取shp面文件,在matlab中将处理结果输出为shp文件
  15. C语言stdio头文件常见的输入输出库函数
  16. 光猫修改rms服务器地址大全,华为光猫备份jffs2及HG8321R-RMS切换HG8321版本教程
  17. c语言中的16进制坐标计算器,16进制计算器
  18. 不同时区时间换算_不同时区时间转换
  19. 《从Paxos到Zookeeper分布式一致性原理与实践》读书笔记
  20. uboot分析第一阶段学习笔记

热门文章

  1. handsontable使用及遇到的坑--mergeCell、合并单元格
  2. zip文件类型如何恢复系统默认值--右键->打开方式中 无 “资源管理器”选项
  3. 人工智能门槛太高?用这个框架轻松入门深度学习!
  4. flask html下拉列表,用Flask框架作两个关联式的下拉式选单,抓取资料库资料
  5. Prometheus + Grafana 实现监控功能总结
  6. 爬虫模拟登录和发表评论
  7. python提取时长2s以内的单词音频的韵母基频,以及单词词长信息
  8. 人工智能、深度学习和机器学习有哪些区别?
  9. mysql僵尸进程_僵尸Z进程和D进程
  10. Altium Designer使用介绍和界面介绍