Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenCV Error: Assertion failed when using COLOR_BGR2GRAY function

I'm having a weird issue with opencv. I have no issues when working in a jupyter notebook but do when trying to run this 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

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)
like image 254
megashigger Avatar asked Dec 09 '16 02:12

megashigger


1 Answers

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:

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

That doesn't match the requirements of cv2.cvtColor.

The range of values you initialize your image with appears to fall into 0-255, which would correspond to data type uint8.

So, just do

img = np.array(img, dtype=np.uint8)
like image 122
Dan Mašek Avatar answered Nov 16 '22 03:11

Dan Mašek