OpenCV颜色转换从BGR到灰度的错误

14
我正在尝试使用以下代码将图像从BGR转换为灰度格式:
img = cv2.imread('path//to//image//file')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

这似乎工作正常:我检查了img变量的数据类型,结果是numpy ndarray,形状为(100,80,3)。但是,如果我提供一个本机numpy ndarray数据类型的图像,并具有与cvtColor函数输入相同的尺寸,则会出现以下错误:

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)如下:
img = np.full((100,80,3), 12)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 

能有人澄清一下这个错误的原因以及如何纠正它吗?

4个回答

22

这是因为你的numpy数组未使用正确的数据类型。默认情况下,它会创建一个np.int64(64位)类型的数组,然而,cv2.cvtColor()需要8位(np.uint8)或16位(np.uint16)的数组。要纠正这个问题,请在np.full()函数中包含数据类型:

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


7

使用初始图像作为源,使用dtype=np.uint8初始化新的numpy数组可能更容易:

import numpy as np    
img = cv2.imread('path//to//image//file')    
img = np.array(img, dtype=np.uint8)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

我尝试使用 cv2.COLOR_GRAY2RGB 将一个1通道的.tif文件转换为RGB格式,但是出现了以下错误:frame = np.array(frame, dtype=np.uint8) TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType' 为什么会这样? - just_learning

4

出现错误是因为cv2.imread返回的numpy数组的数据类型是uint8,与np.full()返回的numpy数组的数据类型不同。要将数据类型设置为uint8,请添加dtype参数-

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

-1
假设你有一个名为preprocessing()的函数,它使用cv2对图像进行预处理, 如果你尝试这样应用它:
data = np.array(list(map(preprocessing,data)))

它不会工作,因为np.array创建int64,而你正在尝试将np.uint8分配给它,你应该做的是添加dtype参数,如下所示:

data = np.array(list(map(preprocessing,data)), dtype = np.uint8)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接