当前位置: 首页 > article >正文

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

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

算法描述

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

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

函数原型

virtual bool cv::VideoWriter::isOpened	(		)	const

参数

该函数没有参数。

返回值

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

代码示例


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

运行结果

The video writer is opened successfully
Video file created successfully.

http://www.kler.cn/news/336982.html

相关文章:

  • 【QT Quick】C++交互:与QML类型转换
  • macOS开发环境配置与应用开发问题的延伸探讨
  • 什么是安全运营中心 SOC?
  • ARM base instruction -- movk
  • 将自己写好的项目部署在自己的云服务器上
  • Raft 常见问题解答
  • 开源2+1链动S2B2C商城小程序下社区团长的社群温度营造与商业价值实现
  • STM32 通用同步/异步通信
  • 基于SpringBoot图书馆预约与占座小程序【附源码】
  • JS测试框架——Jest
  • selenium元素定位
  • 仿小米的Disucz模板
  • TypeScript 算法手册【快速排序】
  • CSP-S复习:图论题选讲
  • 【网络安全】基础知识详解(非常详细)零基础入门到精通
  • Ubuntu24 Firefox和Window Firefox同步问题
  • 大厂程序员用AI能完成几个人的工作量?
  • 如何使用 Ansible 管理多阶段环境
  • 考研笔记之操作系统(四) - 文件管理
  • ESP8266模块的GPIO0引脚在不同工作模式下