【问题标题】:OpenCV Error: Assertion failed when using COLOR_BGR2GRAY functionOpenCV 错误:使用 COLOR_BGR2GRAY 函数时断言失败
【发布时间】:2016-12-09 02:07:58
【问题描述】:

我在使用 opencv 时遇到了一个奇怪的问题。在 jupyter notebook 中工作时我没有问题,但在尝试运行这个 Sublime 时会遇到问题。

错误是:OpenCV Error: Assertion failed (depth == CV_8U || depth == CV_16U || depth == CV_32F) in cvtColor, file /Users/jenkins/miniconda/1/x64/conda-bld/work /opencv-3.1.0/modules/imgproc/src/color.cpp,第 7935 行

import numpy as np 
import cv2

img = [[[150,160,170], [150,32, 199], [145, 212, 234], [145, 212, 234]], 
       [[150,190,170], [150,32, 199], [145, 212, 234], [145, 212, 234]],
       [[150,160,170], [150,32, 199], [145, 212, 234], [145, 212, 234]],
       [[150,160,170], [150,32, 199], [145, 212, 234], [145, 212, 234]]]

img = np.array(img)

def grayscale(x):
    # plt.imshow(gray, cmap='gray')to show on screen
    # turns dim from (32,32,3) to (32,32)
    return cv2.cvtColor(x, cv2.COLOR_BGR2GRAY)

img2 = grayscale(img)

【问题讨论】:

  • 具有相同修复的其他可能错误:“cv2.error (-215:Assertion failed) VScn::contains(scn) && VDcn::contains(dcn) && VDepth::contains(depth) in函数'CvtHelper'"

标签: python opencv numpy


【解决方案1】:

创建数组时需要指定数据类型。

当我在这里尝试此代码并检查 imgdtype 时,我看到以下内容:

>>> img.dtype
dtype('int32')

这不符合cv2.cvtColor 的要求。

用于初始化图像的值范围似乎在 0-255 之间,这对应于数据类型 uint8

所以,做吧

img = np.array(img, dtype=np.uint8)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-26
    • 1970-01-01
    • 2020-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-14
    相关资源
    最近更新 更多