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.

原始图:

相关推荐
Csvn3 小时前
同一个问题问 100 遍,钱就扣 100 次?精确缓存让它只扣一次(C02)
人工智能·aigc·agent
罗西的思考4 小时前
【轻量化复刻大模型 / KIMI K3】Multi-Token Prediction(MTP / EAGLE-3)(2)
人工智能·算法·机器学习
罗西的思考4 小时前
【轻量化复刻大模型 / KIMI K3】Multi-Token Prediction(MTP / EAGLE-3)(1)
人工智能·算法·机器学习
汤姆宝库5 小时前
BPE分词器的完整实现:字节对合并与词表构建
开发语言·人工智能·c#
岁月宁静5 小时前
从零拆解 AI 语音模拟面试系统
人工智能·python·agent
武子康5 小时前
H3-World 接入 Game Agent:谁来判断门真的打开了?
人工智能·算法·机器学习
可乐ea6 小时前
MCP 和 CLI 差 42 倍:一次 GitHub 任务的上下文成本实测
人工智能·github·工具调用·ai智能体·openrouter·mcp协议·上下文优化
kyriewen6 小时前
编辑弹窗点了取消,列表里的数据怎么还是变了?
前端·javascript·人工智能
泯泷7 小时前
Multica 真正打动我的,不是更多 Agent,而是一种新的团队协作方式
人工智能·llm·agent
电科_银尘7 小时前
【深度学习项目实战·22】灰度图像着色:用小型U-Net学习从灰度到RGB
人工智能·深度学习·学习