OpenCV中cvtColor转灰度图的通道数


    OpenCV在转灰度图的时候常用到cvtcolor,但是有的时候发现如此转灰度图的方法会导致生成三通道的灰度图?

测试如下:

Mat firstpic = imread("IMG.JPG");
cout << "channnels : " << firstpic.channels() << endl;    //结果  channels:3
Mat pic2(firstpic.rows, firstpic.cols, CV_8UC1);//建立单通道图片
cvtColor(firstpic, pic2, CV_BGR2GRAY);//灰度图存储到单通道pic2中
cvtColor(firstpic, firstpic, CV_BGR2GRAY);//将fistpic变成灰度图存回原图
cout << "channnels : " << dep1.channels()<<endl;          //结果  channels:1
cout << "channnels : " << firstpic.channels() << endl;    //结果  channels:1

由此可见:cvtcolor转成灰度图的时候就已经将通道数变成1;但是为何再后续操作过程中再次读取的时候会变成三通道?

测试如下:

Mat depthpic = imread("pic2.bmp");    //读取上例子中保存的灰度图 Mat pic2
cout << "channnels : " << depthpic.channels() << endl;    //结果  channels:3

其实问题在于imread,OpenCV中imread原型:

Mat imread( const String& filename, int flags = IMREAD_COLOR );

其中我们往往忽略了flags,其定义如下:

//! Imread flags
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_IGNORE_ORIENTATION   = 128 //!< If set, do not rotate the image according to EXIF's orientation flag.
     };

flags默认值为1,所以我们在读取图片的时候默认读入三通道BGB格式,因此可以通过指定读取图片格式的方法来控制通道数:

Mat depthpic = imread("pic2.bmp", -1);    //flags=-1 表示保持原图格式不变,flags=0表示读入单通道灰度图。在此均可
cout << "channnels : " << depthpic.channels() << endl;    //结果  channels:1



猜你喜欢

转载自blog.csdn.net/weixin_39750861/article/details/80877282
今日推荐