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.
相关推荐
清月电子16 分钟前
KT148A语音芯片发码很难播放_将4脚对地一下再发正常,什么原因?
单片机·嵌入式硬件·物联网·音视频
AndrewHZ19 分钟前
【图像处理基石】什么是油画感?
图像处理·人工智能·算法·图像压缩·视频处理·超分辨率·去噪算法
Robot2511 小时前
「华为」人形机器人赛道投资首秀!
大数据·人工智能·科技·microsoft·华为·机器人
J先生x1 小时前
【IP101】图像处理进阶:从直方图均衡化到伽马变换,全面掌握图像增强技术
图像处理·人工智能·学习·算法·计算机视觉
Narutolxy4 小时前
大模型数据分析破局之路20250512
人工智能·chatgpt·数据分析
浊酒南街4 小时前
TensorFlow中数据集的创建
人工智能·tensorflow
2301_787552875 小时前
console-chat-gpt开源程序是用于 AI Chat API 的 Python CLI
人工智能·python·gpt·开源·自动化
layneyao5 小时前
AI与自然语言处理(NLP):从BERT到GPT的演进
人工智能·自然语言处理·bert
jndingxin6 小时前
OpenCV 的 CUDA 模块中用于将多个单通道的 GpuMat 图像合并成一个多通道的图像 函数cv::cuda::merge
人工智能·opencv·计算机视觉
格林威7 小时前
Baumer工业相机堡盟工业相机的工业视觉中为什么偏爱“黑白相机”
开发语言·c++·人工智能·数码相机·计算机视觉