错误:函数'pointSetBoundingRect'中的(-215:声明失败)npoints> = 0 &&(深度== CV_32F ||深度== CV_32S)

时间:2020-03-20 09:17:13

标签: python opencv

import numpy as np
import cv2

img = cv2.imread("/home/user/Pictures/shapes_and_colors.png")
_,threshold = cv2.threshold(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY),60,255,cv2.THRESH_BINARY)
_,contours = cv2.findContours(threshold,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
    [x,y,w,h] = cv2.boundingRect(contour)

enter image description here

我收到此错误

错误:OpenCV(4.2.0)/io/opencv/modules/imgproc/src/shapedescr.cpp:784:错误:(-215:断言失败)npoints> = 0 &&(depth == CV_32F || depth) == CV_32S)在函数“ pointSetBoundingRect”中

如何清除此错误。

1 个答案:

答案 0 :(得分:0)

您混合了cv2.findContours输出参数的顺序。

使用:

contours, _ = cv2.findContours(threshold,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

代替:

_, contours = cv2.findContours(threshold,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

在OpenCV 4中,第一个输出参数是contours,第二个输出参数是hierarchy
为了与OpenCV 3向后兼容,您还可以使用:

contours = cv2.findContours(threshold,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)[-2]