python - 在 Python 中为 findContours 使用层次结构

标签 python opencv hierarchy contour shape-recognition

我实现了一个 Python 脚本来识别手绘中的形状。但是,脚本识别的形状比需要的多。

这是一个示例图片:

enter image description here

这是脚本的输出:

enter image description here

我写的部分代码如下:

def create_graph(vertex, color):
    for g in range(0, len(vertex)-1):
        for y in range(0, len(vertex[0][0])-1):
            cv2.circle(newimg, (vertex[g][0][y], vertex[g][0][y+1]), 3, (255,255,255), -1)
            cv2.line(newimg, (vertex[g][0][y], vertex[g][0][y+1]), (vertex[g+1][0][y], vertex[g+1][0][y+1]), color, 2)
    cv2.line(newimg, (vertex[len(vertex)-1][0][0], vertex[len(vertex)-1][0][1]), (vertex[0][0][0], vertex[0][0][1]), color, 2)


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

#Remove of noise, if any
kernel = np.ones((2, 2),np.uint8)
erosion = cv2.erode(gray, kernel, iterations = 1)

#Create a new image of the same size of the starting image
height, width = gray.shape
newimg = np.zeros((height, width, 3), np.uint8)

#Canny edge detector
thresh = 175
edges = cv2.Canny(erosion, thresh, thresh*2)

contours,hierarchy = cv2.findContours(edges, cv2.cv.CV_RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
for b,cnt in enumerate(contours):
    if hierarchy[0,b,3] == -1: #<-the mistake might be here
       approx = cv2.approxPolyDP(cnt,0.015*cv2.arcLength(cnt,True), True)
       clr = (255, 0, 0)
       create_graph(approx, clr) #function for drawing the found contours in the new img
cv2.imwrite('starg.jpg', newimg)

我没有贴出所有的代码,因为没用。我认为我错误地使用层次结构来查找轮廓。我不是 Python 专家,我不太了解轮廓中层次结构的使用。有人有什么建议吗?

最佳答案

更改 findContours 的标志,以便仅检索外部轮廓。使用 RETR_EXTERNAL 标志,如下例所示:

contours,hierarchy = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

这应该可以解决问题。

关于python - 在 Python 中为 findContours 使用层次结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22862161/

相关文章:

python - 如何从不包括一个变量的字符串列表中创建一个新的字符串列表?

python - linux + virtualenv + pip 使用一些系统包

python - 如何使用鼠标单击通过OpenCV和Python更改变量?

c++ - 如何将 boost::geometry::distance 与 opencv cv::Point 一起使用?

python - 使用 Python 循环抓取多个 URL,但当我遍历网站页码时数据没有改变?

python - 在 Python 中创建 n 个字符串

OpenCV:获取图像数据作为数组

c++ - 简单的编译错误但没有意义

php - 递归获取类别树(Yii)

c# - 从结构化数据构建 JSON 层次结构