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

7 篇文章 2 订阅

问题描述

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

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

出错
控制台

解决方案

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

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);
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值