如何在边缘重叠文本的图像中查找矩形轮廓

时间:2019-01-09 04:04:46

标签: python opencv

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

sample image

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

enter image description here

是否有更好的机制来查找所有矩形。 (曾尝试为roxPolyDP增加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)

0 个答案:

没有答案