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.

原始图:

相关推荐
AKAMAI29 分钟前
跳过复杂环节:Akamai应用平台让Kubernetes生产就绪——现已正式发布
人工智能·云原生·云计算
新智元2 小时前
阿里王牌 Agent 横扫 SOTA,全栈开源力压 OpenAI!博士级难题一键搞定
人工智能·openai
新智元2 小时前
刚刚,OpenAI/Gemini 共斩 ICPC 2025 金牌!OpenAI 满分碾压横扫全场
人工智能·openai
机器之心2 小时前
OneSearch,揭开快手电商搜索「一步到位」的秘技
人工智能·openai
阿里云大数据AI技术2 小时前
2025云栖大会·大数据AI参会攻略请查收!
大数据·人工智能
YourKing3 小时前
yolov11n.onnx格式模型转换与图像推理
人工智能
sans_3 小时前
NCCL的用户缓冲区注册
人工智能
sans_3 小时前
三种视角下的Symmetric Memory,下一代HPC内存模型
人工智能
算家计算3 小时前
模糊高清修复真王炸!ComfyUI-SeedVR2-Kontext(画质修复+P图)本地部署教程
人工智能·开源·aigc
虫无涯4 小时前
LangSmith:大模型应用开发的得力助手
人工智能·langchain·llm