从BGR到灰度的OpenCV颜色转换中的错误 [英] Error in OpenCV color conversion from BGR to grayscale

查看:79
本文介绍了从BGR到灰度的OpenCV颜色转换中的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下代码将图像从BGR转换为灰度格式:

I am trying to convert an image from BGR to grayscale format using this code:

img = cv2.imread('path//to//image//file')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

这似乎运行良好:我检查了 img 变量的数据类型,结果为numpy ndarray,形状为(100,80,3).但是,如果我给出一个与 cvtColor 函数的输入尺寸相同的本机numpy ndarray数据类型的图像,则会产生以下错误:

This seems to be working fine: I checked the data type of the img variable which turns out to be numpy ndarray and shape to be (100,80,3). However if I give an image of a native numpy ndarray data type with same dimensions of the input of the cvtColor function, it gives me the following error:

Error: Assertion failed (depth == 0 || depth == 2 || depth == 5) in cv::cvtColor, file D:\Build\OpenCV\opencv-3.4.1\modules\imgproc\src\color.cpp, line 11109
cv2.error: OpenCV(3.4.1) D:\Build\OpenCV\opencv-3.4.1\modules\imgproc\src\color.cpp:11109: error: (-215) depth == 0 || depth == 2 || depth == 5 in function cv::cvtColor

第二种情况的代码是(在此处制作自定义 np.ndarray ):

The code for the second case is (making a custom np.ndarray over here):

img = np.full((100,80,3), 12)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 

任何人都可以澄清此错误的原因以及如何纠正该错误吗?

Can anyone clarify what is the reason for this error and how to rectify it?

推荐答案

这是因为您的numpy数组不是由正确的数据类型组成的.默认情况下,数组类型为 np.int64 (64位),但是, cv2.cvtColor()需要8位( np.uint8 )或16位( np.uint16 ).要更正此问题,请更改您的 np.full()函数以包括数据类型:

This is because your numpy array is not made up of the right data type. By default makes an array of type np.int64 (64 bit), however, cv2.cvtColor() requires 8 bit (np.uint8) or 16 bit (np.uint16). To correct this change your np.full() function to include the data type:

img = np.full((100,80,3),12,np.uint8)

这篇关于从BGR到灰度的OpenCV颜色转换中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆