Opencv cvtColor dtype issue (error: (-215))

I came across and understood this dtype problem and hope it will be useful for some.

Usually we will convert the color as follows:

img = cv2.imread("img.jpg"), 0) imgColor=cv2.cvtColor(img , cv2.COLOR_GRAY2BGR) 

However, sometimes you can normalize the image first:

 img = cv2.imread("img.jpg"), 0)/255. imgColor=cv2.cvtColor(img , cv2.COLOR_GRAY2BGR) 

This will result in an error:

error: (-215) depth == CV_8U || depth == CV_16U || depth == CV_32F in function> cv :: cvtColor

The fact is that in the first example, dtype is uint8, and in the second, float64. To fix this, add one line:

 img = cv2.imread("img.jpg"), 0)/255. img=img.astype(numpy.float32) imgColor=cv2.cvtColor(img , cv2.COLOR_GRAY2BGR) 
+5
source share
1 answer

Thus, it will be a similar problem, which will be solved, but associated with another function cv2.drawKeypoints ().

This will work:

 img = cv2.imread("img.jpg"), 1) img_out = numpy.copy(img) image_out = cv2.drawKeypoints(img,keypointList,img_out,(255,0,0),4) 

However, this does not compile:

 img = cv2.imread("img.jpg"), 1)/255.0 img_out = numpy.copy(img) image_out = cv2.drawKeypoints(img,keypointList,img_out,(255,0,0),4) 

Here we have this error:

error: (-5) Invalid input image type.

Again, dividing by 255 or any other processing using "img", which leads to the conversion of floating point numbers, will make "img" not the right type for drawKeypoints. Here adding img = img.astype(numpy.float32) does not help. For the img input image, it turns out that uint8 works, but float32 does not. I could not find such a requirement in the documents. A misconception that differs from the above cvtColor related question complains about the "type".

So that it works:

 img = cv2.imread("img.jpg"), 1)/255.0 img_out = numpy.copy(img) img=img.astype(numpy.uint8) image_out = cv2.drawKeypoints(img,keypointList,img_out,(255,0,0),4) 

On the last line, I thought that cv2.DRAW_RICH_KEYPOINTS would work like a flag (the last argument to the drawKeyPoints function). However, only when I use number 4, which it works. Any explanation would be appreciated.

+4
source

Source: https://habr.com/ru/post/1258564/


All Articles