如何在图像中找到重叠文字边缘的矩形轮廓?

2024-09-28 20:54:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我在寻找图像中的矩形。矩形可以有文本,如下面的示例图像所示。在

sample image

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

enter image description here

找到一个更好的矩形机制。(尝试为approxPolyDP增加epsilon参数,但在我看来这是一种黑客行为)

附件是我的代码片段

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)

Tags: 图像文本trueimgifcv2矩形cnt