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

发布于:2024-10-10 ⋅ 阅读:(11) ⋅ 点赞:(0)
  • 操作系统:ubuntu22.04
  • OpenCV版本:OpenCV4.9
  • IDE:Visual Studio Code
  • 编程语言:C++11

算法描述

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

函数原型

bool cv::haveImageWriter
(
	const String & 	filename
)	

参数

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

返回值

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

代码示例


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

运行结果

终端:

Supports writing image: output_image.png
Image has been written successfully.

原始图:

在这里插入图片描述