OpenCV: 颜色空间转换 cvtColor()出错?注意浮点数精度

问题描述

OpenCV 2.0 中的cvtColor()函数可用于颜色空间的转换,例如RGB转HSV,RGB转YUV等等。这里笔者用它来转灰度图,即RGB2GRAY,出现了错误。

/* various operations of Mat I 
*/
Mat grayI;
cvtColor(I, grayI, COLOR_BGR2GRAY);

OpenCV: 颜色空间转换 cvtColor()出错?注意浮点数精度_第1张图片
控制台

解决方案

根据上图控制台的报错提示

OpenCV Error: Assertion failed (depth==CV_8U || depth==CV_16U|| depth==CV_32F) in cv::cvtColor……

可知该问题与输入矩阵的“深度”(depth)有关
我们先来看官方文档中该函数的关于参数的说明:

Parameters:
src – Source image: 8-bit unsigned, 16-bit unsigned ( CV_16UC… ), or single-precision floating-point.
dst – Destination image of the same size and depth as src .
code – Color space conversion code. See the description below.
dstCn – Number of channels in the destination image. If the parameter is 0, the number of the channels is derived automatically from src and code .

The function converts an input image from one color space to another. In case of a transformation to-from RGB color space, the order of the channels should be specified explicitly
(RGB or BGR). Note that the default color format in OpenCV is often referred to as RGB but it is actually BGR (the bytes are reversed). So the first byte in a standard (24-bit) color image will be an 8-bit Blue component, the second byte will be Green, and the third byte will be Red. The fourth, fifth, and sixth bytes would then be the second pixel (Blue, then Green, then Red), and so on.

The conventional ranges for R, G, and B channel values are:

0 to 255 for CV_8U images
0 to 65535 for CV_16U images
0 to 1 for CV_32F images

果然笔者发现了在前文中定义了Mat I为64位浮点数精度的矩阵,所以先将其转换为32位浮点数,再做颜色转换:

Mat grayI;
I.convertTo(grayI, CV_32FC3);
cvtColor(grayI, grayI, COLOR_BGR2GRAY);

你可能感兴趣的:(OpenCV,C++)