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.
相关推荐
beiju2 分钟前
从 Meta AI Mac 版看 Agent 产品:桌面端真正解决的是交付上下文
人工智能
Scene2163 分钟前
旧 REST 接口封装成 MCP 服务:完整实战指南
人工智能·后端
2301_786756603 分钟前
不做分子仿真、不布局自动化实验室,垂直科研智能平台同样跑通 AI for Science 可持续变现
运维·人工智能·自动化
大数据点灯人4 分钟前
【大模型】深度解答:OOV 与 Tokenizer 词汇表共用问题
人工智能·深度学习·ai·大模型·transformer
TMT星球20 分钟前
快手Q2总收入355亿元:月活近8亿,核心商业收入同比增长7.4%
大数据·人工智能
霸道流氓气质26 分钟前
ima.copilot-AI知识库-完整使用手册与最新动态
人工智能·copilot
牧羊人.33330 分钟前
计算机视觉基础 第 9 章|实战:银行卡号识别
图像处理·人工智能·opencv·计算机视觉·图搜索算法
CRMEB36 分钟前
商城大促活动策划全流程:从定目标到复盘四阶段
java·开发语言·人工智能·ai·开源·php
ClouGence40 分钟前
自动化测试实战:手把手教你用 AI Agent 实现版本打包自动化
人工智能·ai编程·测试
vivo互联网技术41 分钟前
协同文档下的 Agent 协作闭环:可回滚、可对比的透明化编辑实现
人工智能·笔记·agent