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)
2 Since your code is showing error at the very first cvtColor after reading from a file, it is possible that the imread operation was not successful. Start by ensuring that your image is correctly read:
If the number of channels is equal to 1, then your img is already single channel, which is why cvtColor is giving an error. So no color conversion is necessary in this case and you can just comment out the line for cvtColor and the error should be gone.
cv2.findContours function return 3 values (i.e. image, contours and hierarchy) in OpenCV 3.x but just 2 values (i.e. contours, hierarchy) in openCV 4.x len (pts) != [] doesn't make sense.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With