OpenCV轮廓和层次结构

Str*_*eem 0 python opencv

我试图找到字符作为例子中的轮廓:

在此输入图像描述

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)
Run Code Online (Sandbox Code Playgroud)

但是我得到的结果并不是预期的,因为字符孔会像轮廓一样返回,我可以用cv2.contourArea()宽度,高度来绕过它,但我需要用层次结构来完成它.

在此输入图像描述

如果我将层次模式从cv2.RETR_TREE更改为cv2.RETR_EXTERNAL,我会在每个窗口中获得一个轮廓,例如:

在此输入图像描述

Jer*_*uke 6

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

这就是我做的:

ret, thresh = cv2.threshold(img, 100, 255, 1)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

现在我执行了轮廓操作.我用这个cv2.RETR_EXTERNAL选项来忽略字母内部的轮廓

contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

现在我按照你的意愿获得了边界框:

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

在此输入图像描述