OpenCV的轮廓和层次

问题描述:

我试图找到字符轮廓的例子:OpenCV的轮廓和层次

enter image description here

thresh = cv2.adaptiveThreshold(roi,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY,9,2) 
_,contours, hierarchy = cv2.findContours(thresh.copy(),cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) 
contours = sorted(contours, key=cv2.contourArea, reverse = True) 
for cnt in contours: 
    x,y,w,h = cv2.rectBounding(cnt) 
    cv2.rectangle(roi,(x,y),(x+w,y+h),(0,255,0),1) 

但我得到的结果不是预期,以及人物孔返回为 轮廓,我可以用cv2.contourArea()宽度,高度绕过它,但我需要用层次结构来完成。

enter image description here

如果我从cv2.RETR_TREE改变层次模式cv2.RETR_EXTERNAL我得到每整窗的一个轮廓例如:

enter image description here

您对这个问题的方法是错误的。您应该反转二进制图像,然后执行轮廓操作。这是因为轮廓仅在白色区域形成。

这是我做过什么:

ret, thresh = cv2.threshold(img, 100, 255, 1) 

enter image description here

现在我执行的轮廓操作。我用cv2.RETR_EXTERNAL选项忽视轮廓

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

enter image description here

现在,我获得的边框为你想要的字母里面:

for cnt in contours: 
    x,y,w,h = cv2.boundingRect(cnt) 
    cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),1) 

enter image description here

+0

谢谢你,你的解决方案解决问题:) – Streem

+0

@Streem只要记住一件事:'*总是突出你想要轮廓的区域白*' –

+0

谢谢,现在我明白了:) – Streem