OpenCV图像文件读写(2) 检查 OpenCV 是否支持某种图像格式的写入功能函数haveImageWriter()的使用

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

算法描述

haveImageWriter 函数用于检查 OpenCV 是否支持某种图像格式的写入功能。这个函数可以帮助开发者在编写代码时确定是否可以成功地将图像写入特定格式的文件中。

函数原型

cpp 复制代码
bool cv::haveImageWriter
(
	const String & 	filename
)	

参数

  • 参数filename:要检查的图像文件的路径。

返回值

如果支持写入该格式的图像文件,返回 true;否则返回 false。

代码示例

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

int main()
{
    // 读取图像
    cv::Mat img = cv::imread( "/media/dingxin/data/study/OpenCV/sources/images/fruit_small.jpg" );

    if ( img.empty() )
    {
        std::cout << "Could not open or find the image!" << std::endl;
        return -1;
    }

    // 检查是否支持写入特定格式的图像文件
    std::string outputFilename = "output_image.png";

    if ( cv::haveImageWriter( outputFilename ) )
    {
        std::cout << "Supports writing image: " << outputFilename << std::endl;

        // 写入图像
        std::vector< int > params;
        params.push_back( cv::IMWRITE_PNG_COMPRESSION );  // 设置 PNG 压缩级别
        params.push_back( 9 );                            // 压缩级别为 9

        bool success = cv::imwrite( outputFilename, img, params );
        if ( success )
        {
            std::cout << "Image has been written successfully." << std::endl;
        }
        else
        {
            std::cout << "Failed to write the image." << std::endl;
        }
    }
    else
    {
        std::cout << "Does not support writing image: " << outputFilename << std::endl;
    }

    // 显示图像
    cv::imshow( "Original Image", img );
    cv::waitKey( 0 );

    return 0;
}

运行结果

终端:

bash 复制代码
Supports writing image: output_image.png
Image has been written successfully.

原始图:

相关推荐
skywalk81634 分钟前
近期有什么ai的新消息,新动态? 2026.4月
人工智能
庄小焱20 分钟前
【AI模型】——RAG索引构建与优化
人工智能·ai·向量数据库·ai大模型·rag·rag索引·索引构建与优化
STLearner24 分钟前
WSDM 2026 | 时间序列(Time Series)论文总结【预测,表示学习,因果】
大数据·论文阅读·人工智能·深度学习·学习·机器学习·数据挖掘
玩转单片机与嵌入式25 分钟前
不会 Python、不会深度学习,也能在STM32上跑AI模型吗?
人工智能·单片机·嵌入式硬件·嵌入式ai
CareyWYR27 分钟前
我暂停了vibecoding一个月
人工智能
竹之却30 分钟前
【Agent-阿程】一文搞懂大模型Token核心原理与实战避坑指南
人工智能·token
呆呆敲代码的小Y32 分钟前
从LLM到Agent Skill:AI核心技术全拆解与系统化学习路线
人工智能·ai·llm·agent·优化·skill·mcp
昵称小白39 分钟前
从 ( y = wx + b ) 到神经网络:参数、loss、梯度到底怎么连起来(一)
人工智能·神经网络
SmartBrain44 分钟前
基于 Spring AI + Skill 工程 + MCP 技术方案研究
人工智能·spring·架构·aigc
俊哥V1 小时前
每日 AI 研究简报 · 2026-04-18
人工智能·ai