OpenCV图像读取与灰度化

在OpenCV中,图像的读取可以通过imread()函数实现:
Mat imread( const String& filename, int flags = IMREAD_COLOR );
读取后的数据存储格式由第二个形参flags决定。flag的值可以从枚举类型cv::ImreadModes中选取:

enum ImreadModes {
    IMREAD_UNCHANGED = -1, //!< If set, return the loaded image as is (with alpha channel, otherwise it gets cropped).
    IMREAD_GRAYSCALE = 0,  //!< If set, always convert image to the single channel grayscale image.
    IMREAD_COLOR = 1,  //!< If set, always convert image to the 3 channel BGR color image.
    IMREAD_ANYDEPTH = 2,  //!< If set, return 16-bit/32-bit image when the input has the corresponding depth, otherwise convert it to 8-bit.
    IMREAD_ANYCOLOR = 4,  //!< If set, the image is read in any possible color format.
    IMREAD_LOAD_GDAL = 8,  //!< If set, use the gdal driver for loading the image.
    IMREAD_REDUCED_GRAYSCALE_2 = 16, //!< If set, always convert image to the single channel grayscale image and the image size reduced 1/2.
    IMREAD_REDUCED_COLOR_2 = 17, //!< If set, always convert image to the 3 channel BGR color image and the image size reduced 1/2.
    IMREAD_REDUCED_GRAYSCALE_4 = 32, //!< If set, always convert image to the single channel grayscale image and the image size reduced 1/4.
    IMREAD_REDUCED_COLOR_4 = 33, //!< If set, always convert image to the 3 channel BGR color image and the image size reduced 1/4.
    IMREAD_REDUCED_GRAYSCALE_8 = 64, //!< If set, always convert image to the single channel grayscale image and the image size reduced 1/8.
    IMREAD_REDUCED_COLOR_8 = 65  //!< If set, always convert image to the 3 channel BGR color image and the image size reduced 1/8.
};

常用的读取格式有 IMREAD_GRAYSCALE 和 IMREAD_COLOR。按照IMREAD_GRAYSCALE 方式读取,得到的结果为CV_8U类型(8位无符号整型 0~255)的单通道灰度值, IMREAD_COLOR读取的结果是按照B G R 顺序存储的CV_8U类型三通道色彩图。(注意色彩通道的存储顺序!!!)
这里写图片描述

灰度化的过程可以通过cvtColor()函数实现:
void cvtColor( InputArray src, OutputArray dst, int code, int dstCn = 0 );
src, dst 分别表示源图像和灰度化后存储的目的图像(Mat);
dstCn 表示输出图像的通道数,默认值0表示跟输入输入图像的通道数保持一致;
code 表示转换的方式,它可以实现在多种颜色空间的格式直接进行转换。详见ColorConversionCodes.
一般code的值为CV_**BGR**2GRAY,表示从三通道色彩图转化为灰度图。
转换过程按照如下公式进行:
RGB[A] to Gray:Y←0.299⋅R+0.587⋅G+0.114⋅B

注意上文提到色彩图的通道的存储顺序为B G R,所以 这里是BGR2GRAY。而CV_RGB2GRAY也是可取的值,它当然是在图像通道顺序为RGB时使用了。二者之间的区间就在于告诉上面的计算公式每个点像素值是按照什么顺序排列的。

更多关于色彩空间的转换,详见官方文档color conversion.

你可能感兴趣的:(OpenCV)