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


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

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


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

函数原型3

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


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

函数原型4

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

代码示例


#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;
}

运行结果

Video file created successfully.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值