简体   繁体   English

OpenCV错误:使用COLOR_BGR2GRAY函数时断言失败

[英]OpenCV Error: Assertion failed when using COLOR_BGR2GRAY function

I'm having a weird issue with opencv. 我对opencv有一个奇怪的问题。 I have no issues when working in a jupyter notebook but do when trying to run this Sublime. 我在使用jupyter笔记本时没有问题,但在尝试运行这个Sublime时也没有问题。

The error is: 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, line 7935 错误是:OpenCV错误:cvtColor中的断言失败(深度== CV_8U ||深度== CV_16U ||深度== CV_32F),文件/ 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)

You need to specify the data type when you create the array. 您需要在创建阵列时指定数据类型。

When I try this code here, and check the dtype of img , I see the following: 当我在这里尝试这个代码,并检查imgdtype时,我看到以下内容:

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

That doesn't match the requirements of cv2.cvtColor . 这与cv2.cvtColor的要求cv2.cvtColor

The range of values you initialize your image with appears to fall into 0-255, which would correspond to data type uint8 . 初始化图像的值范围似乎为0-255,这与数据类型uint8相对应。

So, just do 所以,就这么做

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM