OpenCV视频I/O(17)视频写入类VideoWriter之检查视频编写器是否已经成功初始化的函数isOpened()的使用

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

算法描述

如果视频编写器已经成功初始化,则返回 true。

isOpened()函数用于检查 VideoWriter 对象是否已经成功初始化并且准备好写入视频帧。这个函数是非成员函数 cv::VideoWriter::open() 的辅助函数,通常用于确认 VideoWriter 是否处于可以工作的状态。

函数原型

cpp 复制代码
virtual bool cv::VideoWriter::isOpened	(		)	const

参数

该函数没有参数。

返回值

返回一个布尔值,指示 VideoWriter 对象是否已经成功初始化。如果返回 true,则表示对象已经准备好写入视频帧;如果返回 false,则表示对象尚未初始化或出现了错误。

代码示例

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

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

    // 使用 isOpened() 函数再次检查状态
    if ( !writer.isOpened() )
    {
        std::cerr << "The video writer is not opened despite successful initialization." << std::endl;
        return -1;
    }
    else
    {
        std::cout<<"The video writer is opened successfully"<<std::endl;
    }

    // 创建一个示例帧
    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 复制代码
The video writer is opened successfully
Video file created successfully.
相关推荐
东离与糖宝1 小时前
Spring AI 大模型容易混淆概念一次性讲透
人工智能
复杂网络与机器学习1 小时前
全双工 160 毫秒一格:李沐让模型不再「一问一答」
人工智能
武子康2 小时前
Qwen-Drive 的 91.4 分,究竟选中了什么?
大数据·人工智能·agent
王中阳Go2 小时前
你把重试加到 2 次那天,200 条里成功还是 181 条,你回看过吗?
人工智能·后端·架构
北杨2 小时前
三键之内的意图:用 AIUI 在 Rokid 眼镜上做一个能玩的 21 点
人工智能
火山引擎开发者社区2 小时前
给企业配一双 AI 的手:火山引擎 OS Agent 替你操作手机和电脑
前端·人工智能
神鹰手哥_起飞版3 小时前
我是怎么管理 Coding Agent 的:把任务交出去,也把结果验回来
人工智能·架构·产品经理
泯泷3 小时前
你的 AI 知识库为什么答非所问?问题出在“切块”这一刀
人工智能
国科安芯3 小时前
算力上天之后的电与静:星上边缘计算载荷带外管理网络的低功耗调度与辐射容错
网络·人工智能·嵌入式硬件·安全·边缘计算·低轨卫星·商业航天
kisdiem3 小时前
让 AI 边玩游戏边编写世界规则:从 XLand 到 ARC-AGI-3 的实验记录
人工智能·agi·玩游戏