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

时间:2016-10-20 19:25:05

标签: python opencv numpy

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)

1 个答案:

答案 0 :(得分:8)

所以这将是一个类似的问题,已解决,但与另一个函数cv2.drawKeypoints()有关。

这将有效:

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

但是,这不会编译:

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)

我们遇到此错误:

  

错误:( - 5)输入图像类型不正确。

再次,除以255或任何其他处理" img"导致转换为浮动数字将导致" img"不是drawKeypoints的正确类型。在这里添加img = img.astype(numpy.float32)没有帮助。对于输入图像img,事实证明uint8工作,但float32不工作。我在文件中找不到这样的要求。令人困惑的是,与上述与cvtColor相关的问题不同,它抱怨"类型"。

所以要让它发挥作用:

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)

对于最后一行,我认为cv2.DRAW_RICH_KEYPOINTS将作为标志(drawKeyPoints函数中的最后一个参数)。但是只有当我使用数字4时它才有效。任何解释将不胜感激。