在学习 opencv 过程中 遇到一个 cv2.drawContours 报error: (-215:Assertion failed) npoints异常的问题
检查程序之后没有发现异常。问了 度娘后也没有找到原因,最后找到了一个解决方法:
def ContoursDemo2():
"""边界框,最小矩形区域和最小闭圆的轮廓"""
img=cv2.pyrDown(cv2.imread("test.bmp",cv2.IMREAD_GRAYSCALE))
ret,thresh=cv2.threshold(img,127,255,cv2.THRESH_BINARY)
img1=img.copy()
contours,hier=cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
#find bounding box coordinates
x,y,w,h=cv2.boundingRect(c)
cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
#fined minimun area
rect=cv2.minAreaRect(c)
# calculate coordinates of the minimun area recatangle
box =cv2.boxPoints(rect)
# draw contours
cv2.drawContours(img1,[box],0,(0,0,255),3)
# calculate center and radius of minimum enclosing circle
(x,y),radius=cv2.minEnclosingCircle(c)
# cast to integers
center = (int(x),int(y))
radius= int (radius)
#draw the circle
# img =cv2.circle(img,center,radius,(0,255,0),2)
cv2.drawContours(img,contours,-1,(255,0,0),1)
cv2.imshow("contours",img1)
cv2.waitKey()
cv2.destroyAllWindows()
ContoursDemo2()
运行后报异常
最后应该是应为数据类型不匹配导致异常吧。
修改后代码
def ContoursDemo2():
"""边界框,最小矩形区域和最小闭圆的轮廓"""
img=cv2.pyrDown(cv2.imread("test.bmp",cv2.IMREAD_GRAYSCALE))
ret,thresh=cv2.threshold(img,127,255,cv2.THRESH_BINARY)
img1=img.copy()
contours,hier=cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
#find bounding box coordinates
x,y,w,h=cv2.boundingRect(c)
cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
#fined minimun area
rect=cv2.minAreaRect(c)
# calculate coordinates of the minimun area recatangle
box =cv2.boxPoints(rect)
# draw contours
cv2.drawContours(img1,[box.astype(int)],0,(0,0,255),3)
# calculate center and radius of minimum enclosing circle
(x,y),radius=cv2.minEnclosingCircle(c)
# cast to integers
center = (int(x),int(y))
radius= int (radius)
#draw the circle
# img =cv2.circle(img,center,radius,(0,255,0),2)
cv2.drawContours(img,contours,-1,(255,0,0),1)
cv2.imshow("contours",img1)
cv2.waitKey()
cv2.destroyAllWindows()
ContoursDemo2()
将cv2.drawContours(img1,[box],0,(0,0,255),3) 中 [box]修改成box.astype(int) 把box列表全部转换成int类型从而解决问题
运行后程序成功执行