【问题标题】:Opencv:convexityDefects on largest contour gives errorOpencv:convexityDefects on最大轮廓给出错误
【发布时间】:2018-08-30 14:21:24
【问题描述】:

我收到此错误:

OpenCV Error: Assertion failed (hpoints > 0) in cv::convexityDefects, file C:\projects\opencv-python\opencv\modules\imgproc\src\convhull.cpp, line 284
Traceback (most recent call last):
  File "E:/PycharmProjects/ComputerVisionAgain/Image Segmentation/hand_blk/main.py", line 12, in <module>
    hull_defects=cv2.convexityDefects(sorted_cnts[0],hull)
cv2.error: C:\projects\opencv-python\opencv\modules\imgproc\src\convhull.cpp:284: error: (-215) hpoints > 0 in function cv::convexityDefects

当我尝试获取图像最大轮廓的凸度缺陷时。 这是我正在使用的代码:

import cv2
import numpy as np

img=cv2.imread('blk_hand.jpg')
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

ret,thresh=cv2.threshold(gray,100,255,cv2.THRESH_BINARY)

_,contours,h=cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_NONE)
sorted_cnts=sorted(contours,key=cv2.contourArea,reverse=True)
hull=cv2.convexHull(sorted_cnts[0])
hull_defects=cv2.convexityDefects(sorted_cnts[0],hull)
cv2.drawContours(img,[hull],-1,(0,0,255),3)

cv2.drawContours(img,sorted_cnts[0],-1,(0,255,0),3)

cv2.imshow('img',img)
cv2.imshow('thresh',thresh)
cv2.waitKey(0)

【问题讨论】:

    标签: python opencv convexity-defects


    【解决方案1】:

    cv2.convexHull 默认返回凸包作为一组点(returnPoints 参数负责此,默认为 Truedocs here)。但是cv2.convexityDefects 函数,根据docs,期望第二个参数是构成船体的轮廓点的索引

    所以改变

    hull=cv2.convexHull(sorted_cnts[0])
    

    hull=cv2.convexHull(sorted_cnts[0], returnPoints=False)
    

    所以hull 将包含构成凸包的原始sorted_cnts[0] 轮廓的索引。

    顺便说一句,在这种情况下,您仍然可以通过sorted_cnts[0][hull] 将船体作为一组点来获取。

    【讨论】:

    • 目前,在 OpenCV 3.x 下,BTW 代码应该是:sorted_cnts[0][cnt[[ h[0] for h in hull]]],因为这是 OpenCV 的另一种情况,似乎具有额外的单元素数组。
    猜你喜欢
    • 2019-07-04
    • 2018-02-21
    • 1970-01-01
    • 2011-11-27
    • 1970-01-01
    • 1970-01-01
    • 2013-06-19
    • 2022-01-24
    相关资源
    最近更新 更多