OpenCV 轮廓和层次结构
OpenCV contours and hierarchy
我正在尝试查找字符作为示例中的轮廓:
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()
宽度、高度绕着它走,但我需要用层次来完成它。
如果我将层级模式从 cv2.RETR_TREE
更改为 cv2.RETR_EXTERNAL
我将得到每个整体一个轮廓 window 如示例:
你处理问题的方法是错误的。您应该反转二进制图像,然后执行轮廓操作。这是因为轮廓仅在白色区域周围形成。
这是我所做的:
ret, thresh = cv2.threshold(img, 100, 255, 1)
现在我进行了轮廓操作。我使用 cv2.RETR_EXTERNAL
选项忽略字母
内的轮廓
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
现在我得到了你想要的边界框:
for cnt in contours:
x,y,w,h = cv2.boundingRect(cnt)
cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),1)
我正在尝试查找字符作为示例中的轮廓:
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()
宽度、高度绕着它走,但我需要用层次来完成它。
如果我将层级模式从 cv2.RETR_TREE
更改为 cv2.RETR_EXTERNAL
我将得到每个整体一个轮廓 window 如示例:
你处理问题的方法是错误的。您应该反转二进制图像,然后执行轮廓操作。这是因为轮廓仅在白色区域周围形成。
这是我所做的:
ret, thresh = cv2.threshold(img, 100, 255, 1)
现在我进行了轮廓操作。我使用 cv2.RETR_EXTERNAL
选项忽略字母
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
现在我得到了你想要的边界框:
for cnt in contours:
x,y,w,h = cv2.boundingRect(cnt)
cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),1)