cv2.drawContours 在程序中报error: (-215:Assertion failed) npoints异常的处理方法

在学习 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类型从而解决问题

运行后程序成功执行

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值