OpenCV视频I/O(18)视频写入类VideoWriter之初始化 VideoWriter 对象的函数open()的使用

  • 操作系统:ubuntu22.04
  • OpenCV版本:OpenCV4.9
  • IDE:Visual Studio Code
  • 编程语言:C++11

算法描述

初始化或重新初始化视频编写器。

该方法打开视频编写器。参数与构造函数 VideoWriter::VideoWriter 中的相同。

cv::VideoWriter::open() 函数用于初始化 VideoWriter 对象,使其能够将视频帧写入文件或视频流。

函数原型1

cpp 复制代码
virtual bool cv::VideoWriter::open
(
	const String & 	filename,
	int 	fourcc,
	double 	fps,	
	Size 	frameSize,	
	bool 	isColor = true 
)		

参数1

  • 参数 filename:输出视频文件的路径或名称。
  • 参数 fourcc:四字符代码(FourCC code),用于指定视频编码器。
  • 参数fps:视频的帧率(每秒帧数)。
  • 参数frameSize:视频帧的大小(宽度和高度)。
  • 参数isColor:布尔值,表示视频是否为彩色,默认值为 true(彩色视频)。

函数原型2

这是一个重载的成员函数,提供方便。它与上述函数的不同仅在于接受的参数。

cpp 复制代码
bool cv::VideoWriter::open
(
	const String & 	filename,
	int 	apiPreference,
	int 	fourcc,
	double 	fps,
	Size 	frameSize,
	bool 	isColor = true 
)		

函数原型3

这是一个重载的成员函数,提供方便。它与上述函数的不同仅在于接受的参数。

cpp 复制代码
bool cv::VideoWriter::open	 
(
	const String & 	filename,
	int 	fourcc,
	double 	fps,
	const Size & 	frameSize,
	const std::vector< int > & 	params 
)	

函数原型4

cpp 复制代码
bool cv::VideoWriter::open	
(
	const String & 	filename,
	int 	apiPreference,
	int 	fourcc,
	double 	fps,
	const Size & 	frameSize,
	const std::vector< int > & 	params 
)		

代码示例

cpp 复制代码
#include <iostream>
#include <opencv2/opencv.hpp>
#include <fstream>


int main()
{
    // 设置视频的宽度和高度
    int frameWidth  = 640;
    int frameHeight = 480;

    // 设置视频编码器的 FourCC 代码
    // 使用 XVID 编码器作为替代方案
    int fourcc = cv::VideoWriter::fourcc( 'X', 'V', 'I', 'D' );

    // 创建 VideoWriter 对象
    cv::VideoWriter writer;

    // 初始化 VideoWriter 对象
    bool isOpened = writer.open( "output.avi", fourcc, 25, cv::Size( frameWidth, frameHeight ), true );

    if ( !isOpened )
    {
        std::cerr << "Failed to initialize the video writer." << std::endl;
        return -1;
    }

    // 创建一个示例帧
    cv::Mat frame = cv::Mat::zeros( frameHeight, frameWidth, CV_8UC3 );

    // 写入一帧到视频文件
    writer.write( frame );

    // 检查视频文件是否存在
    std::ifstream file( "output.avi" );
    if ( file.good() )
    {
        std::cout << "Video file created successfully." << std::endl;
    }
    else
    {
        std::cerr << "Failed to create video file." << std::endl;
    }

    // 关闭文件流
    file.close();

    // 释放资源
    writer.release();

    return 0;
}

运行结果

bash 复制代码
Video file created successfully.
相关推荐
开开心心就好3 小时前
电子报纸离线保存:一键下载多报PDF工具
网络·笔记·macos·pdf·word·音视频·phpstorm
无敌最俊朗@3 小时前
视频容器(如 MP4)的作用:组织与同步
音视频
Black蜡笔小新7 小时前
视频融合平台EasyCVR结合视频智能分析技术构建高空抛物智能监控系统,守护“头顶上的安全”
安全·音视频
EasyCVR7 小时前
如何基于视频融合平台EasyCVR实现全域轨迹跟踪,构建主动式安防新体系?
音视频
筑凡7 小时前
PPT+配音生成带旁白的PPT演示视频
powerpoint·音视频·wps·mp4·ppt
EasyGBS7 小时前
从“被动监控”到“主动预警”:EasyGBS远程视频监控方案助力企业高效安全运营
安全·音视频
有为少年8 小时前
告别乱码:OpenCV 中文路径(Unicode)读写的解决方案
人工智能·opencv·计算机视觉
初学小刘8 小时前
基于 U-Net 的医学图像分割
python·opencv·计算机视觉
huaweichenai9 小时前
如何实现html显示WebRTC视频监控流
音视频·webrtc
Likeadust9 小时前
视频直播点播平台EasyDSS:助力现代农业驶入数字科技“快车道”
人工智能·科技·音视频