【问题标题】:Error in OpenCV color conversion from BGR to grayscale从 BGR 到灰度的 OpenCV 颜色转换错误
【发布时间】:2018-05-13 18:56:56
【问题描述】:

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

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

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

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) 

谁能澄清这个错误的原因以及如何纠正它?

【问题讨论】:

    标签: python opencv image-processing


    【解决方案1】:

    用初始图像作为源和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' 为什么?
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      因为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)
      

      【讨论】:

        【解决方案4】:

        假设你有一个名为 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)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-01-12
          • 1970-01-01
          • 1970-01-01
          • 2021-08-05
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多