run run chicken
run run chicken

Reputation: 503

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

I came across and figured out this dtype problem and hope it will be helpful for some.

Normally we would convert color like this, which works:

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

However sometimes you may normalize the image first:

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

It will result in this error:

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

The point is, in the former example, dtype is uint8, while in the latter it is float64. To correct this, add one line:

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

Upvotes: 13

Views: 17214

Answers (1)

run run chicken
run run chicken

Reputation: 503

So this would be a similar issue that is solved but is related to 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 will 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) Incorrect type of input image.

Again, division by 255 or any other processing with "img" that results in conversion to float numbers will make "img" not the correct type for drawKeypoints. Here adding img = img.astype(numpy.float32) is not helping. For input image img, it turns out that uint8 works, but float32 does not. I could not find such requirement in documentations. It is confusing that different from the issue above related to cvtColor, it complains about "type".

So to make it work:

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)

For the last line, I thought cv2.DRAW_RICH_KEYPOINTS would work as the flag(the last argument in the drawKeyPoints function). However only when I use the number 4 that it works. Any explanation will be appreciated.

Upvotes: 9

Related Questions