首页 > 解决方案 > 如何在边缘重叠文本的图像中找到矩形轮廓

问题描述

我正在尝试在图像中找到矩形。矩形可以包含如下示例图像中所示的文本。

示例图像

使用 findContours 和 cv2.approxPolyDP,我只能检测到矩形的一个子集(以绿色突出显示)并且很难找到文本跨越边界的矩形。

在此处输入图像描述

是否有更好的机制来查找所有矩形。(尝试增加 approxPolyDP 的 epsilon 参数,但它看起来对我来说是 hack)

附件是我的代码片段

img = cv2.imread(fname)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(gray,127,255,0)


image,contours,hierarchy = cv2.findContours(thresh, cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
    approx = cv2.approxPolyDP(cnt,0.01*cv2.arcLength(cnt,True),True)
    if len(approx)==4:
        x,y,w,h = cv2.boundingRect(cnt)
        #print x, y, w, h
        carea = cv2.contourArea(cnt, True)
        # if carea is less than 0, the contour is a duplicate - counting both inner and outer edge of the rect
        if carea<0:
            continue
        if x==0:
            continue
        print x, y, w, h

        cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),5)

cv2.imshow("Original", gray)
cv2.imshow("Contours", img)

标签: pythonopencv

解决方案


推荐阅读