opencv读写图像问题!

本文详细介绍OpenCV中图像的读取与保存方法,包括支持的图像格式、读取方式及参数说明,如flags参数的不同用途,以及保存图像时的格式选择与压缩参数调整。特别指出,使用imwrite函数保存图像时,需注意图像格式、深度及通道顺序的匹配。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、OpenCV中支持读取的图像格式:

1.  Windows bitmaps     \*.bmp, \*.dib

2.  JPEG files         \*.jpeg, \*.jpg, \*.jpe

3.  JPEG 2000 files      \*.jp2 

4.   Portable Network Graphics       \*.png 

5.   WebP       \*.webp 

6.   Portable image format      \*.pbm, \*.pgm, \*.ppm \*.pxm, \*.pnm 

7.   Sun rasters       \*.sr, \*.ras 

8.   TIFF files        \*.tiff, \*.tif 

9.   OpenEXR Image files        \*.exr

10.   Radiance HDR        \*.hdr, \*.pic 

11.   Raster and Vector geospatial data supported by GDAL 

二、读取方式

cv2.imread(filename, flags=None)

其中:
flags = -1, 读取原始数据
flags = 0,  读取图像并将其转换为单通道灰度图,并且结果可能与使用cvtColor()函数的结果不同
flags = 1,  读取图像并将其转换为3通道图像,通道顺序为B、G、R
flags = 2,  读取并返回16位或32位图像(前提是图像必须有对应的深度,否则将转化为int8位图像返回

三、保存图像

cv2.imwrite(filename, img, params=None)

Imwrite flags
enum ImwriteFlags {
       IMWRITE_JPEG_QUALITY        = 1,  //!< For JPEG, it can be a quality from 0 to 100 (the higher is the better). Default value is 95.
       IMWRITE_JPEG_PROGRESSIVE    = 2,  //!< Enable JPEG features, 0 or 1, default is False.
       IMWRITE_JPEG_OPTIMIZE       = 3,  //!< Enable JPEG features, 0 or 1, default is False.
       IMWRITE_JPEG_RST_INTERVAL   = 4,  //!< JPEG restart interval, 0 - 65535, default is 0 - no restart.
       IMWRITE_JPEG_LUMA_QUALITY   = 5,  //!< Separate luma quality level, 0 - 100, default is 0 - don't use.
       IMWRITE_JPEG_CHROMA_QUALITY = 6,  //!< Separate chroma quality level, 0 - 100, default is 0 - don't use.
       IMWRITE_PNG_COMPRESSION     = 16, //!< For PNG, it can be the compression level from 0 to 9. A higher value means a smaller size and longer compression time. If specified, strategy is changed to IMWRITE_PNG_STRATEGY_DEFAULT (Z_DEFAULT_STRATEGY). Default value is 1 (best speed setting).
       IMWRITE_PNG_STRATEGY        = 17, //!< One of cv::ImwritePNGFlags, default is IMWRITE_PNG_STRATEGY_RLE.
       IMWRITE_PNG_BILEVEL         = 18, //!< Binary level PNG, 0 or 1, default is 0.
       IMWRITE_PXM_BINARY          = 32, //!< For PPM, PGM, or PBM, it can be a binary format flag, 0 or 1. Default value is 1.
       IMWRITE_WEBP_QUALITY        = 64, //!< For WEBP, it can be a quality from 1 to 100 (the higher is the better). By default (without any parameter) and for quality above 100 the lossless compression is used.
       IMWRITE_PAM_TUPLETYPE       = 128,//!< For PAM, sets the TUPLETYPE field to the corresponding string value that is defined for the format
     };

//! Imwrite PNG specific flags used to tune the compression algorithm.
/** These flags will be modify the way of PNG image compression and will be passed to the underlying zlib processing stage.

-   The effect of IMWRITE_PNG_STRATEGY_FILTERED is to force more Huffman coding and less string matching; it is somewhat intermediate between IMWRITE_PNG_STRATEGY_DEFAULT and IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY.
-   IMWRITE_PNG_STRATEGY_RLE is designed to be almost as fast as IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY, but give better compression for PNG image data.
-   The strategy parameter only affects the compression ratio but not the correctness of the compressed output even if it is not set appropriately.
-   IMWRITE_PNG_STRATEGY_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler decoder for special applications.
*/
enum ImwritePNGFlags {
       IMWRITE_PNG_STRATEGY_DEFAULT      = 0, //!< Use this value for normal data.
       IMWRITE_PNG_STRATEGY_FILTERED     = 1, //!< Use this value for data produced by a filter (or predictor).Filtered data consists mostly of small values with a somewhat random distribution. In this case, the compression algorithm is tuned to compress them better.
       IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY = 2, //!< Use this value to force Huffman encoding only (no string match).
       IMWRITE_PNG_STRATEGY_RLE          = 3, //!< Use this value to limit match distances to one (run-length encoding).
       IMWRITE_PNG_STRATEGY_FIXED        = 4  //!< Using this value prevents the use of dynamic Huffman codes, allowing for a simpler decoder for special applications.
     };

//! Imwrite PAM specific tupletype flags used to define the 'TUPETYPE' field of a PAM file.
enum ImwritePAMFlags {
       IMWRITE_PAM_FORMAT_NULL = 0,
       IMWRITE_PAM_FORMAT_BLACKANDWHITE = 1,
       IMWRITE_PAM_FORMAT_GRAYSCALE = 2,
       IMWRITE_PAM_FORMAT_GRAYSCALE_ALPHA = 3,
       IMWRITE_PAM_FORMAT_RGB = 4,
       IMWRITE_PAM_FORMAT_RGB_ALPHA = 5,
     };

       注意使用imwire函数保存图像时,一般只能保存8位(或16位无符号型<CV_16U>)的单通道或三通道图像(通道顺序位BGR),保存的格式取决于所使用的扩展名。如果图像格式、深度或通道顺序不同,需要先使用ConvertTo或者CvtColor函数进行转换,或者使用通用的FileStorage I/O函数将其保存为XML或者YAML类型的文件。

使用此函数还可以保存带有alpha通道的png图片,需要首先创建一个8位或16位的4通道的图像BGRA,其中alpha通道放在最后,对于全透明的图像,其alpha通道值的应该设置为0,对于完全不透明的图像,其alpha通道的值应该设置为255/65535。C++版本的示例代码如下:

#include <opencv2/opencv.hpp>

using namespace cv;
using namespace std;

void createAlphaMat(Mat &mat)
{
    CV_Assert(mat.channels() == 4);
    for (int i = 0; i < mat.rows; ++i) {
        for (int j = 0; j < mat.cols; ++j) {
            Vec4b& bgra = mat.at<Vec4b>(i, j);
            bgra[0] = UCHAR_MAX; // Blue
            bgra[1] = saturate_cast<uchar>((float (mat.cols - j)) / ((float)mat.cols) * UCHAR_MAX); // Green
            bgra[2] = saturate_cast<uchar>((float (mat.rows - i)) / ((float)mat.rows) * UCHAR_MAX); // Red
            bgra[3] = saturate_cast<uchar>(0.5 * (bgra[1] + bgra[2])); // Alpha
        }
    }
}

int main(int argv, char **argc)
{
    // Create mat with alpha channel
    Mat mat(480, 640, CV_8UC4);
    createAlphaMat(mat);

    vector<int> compression_params;
    compression_params.push_back(IMWRITE_PNG_COMPRESSION);
    compression_params.push_back(9);
    try{
        imwrite("alpha.png", mat, compression_params);
    }
    catch (cv::Exception& ex) {
        fprintf(stderr, "Exception converting image to PNG format: %s\n", ex.what());
        return 1;
    }

    fprintf(stdout, "Saved PNG file with alpha data.\n");
    return 0;
}

如果你想保存其他数据类型的图像,可按照下列方式:

1.CV_16U格式的图像可以保存为:PNG、JPEG 2000、 TIFF 格式

2.CV_32F格式的图像可以保存为:TIFF、 OpenEXR、 Radiance HDR格式。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值