有没有什么方法可以在OpenCV中的轮廓检测中只检测到矩形,而忽略由于文本而导致的其他检测?

问题描述 投票:0回答:2

enter image description here我想使用 OpencV 轮廓检测来直观地检测网页的所有文本框。但在这里,它还检测文本,我需要过滤掉其他结果并仅检测矩形框。

我只想对框和按钮进行矩形检测,并过滤掉所有其他文本检测。

python opencv
2个回答
3
投票

使用以下代码作为起点:

img =  cv2.imread('amazon.png')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

# inverse thresholding
thresh = cv2.threshold(gray, 195, 255, cv2.THRESH_BINARY_INV)[1]

# find contours
contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]

mask = np.ones(img.shape[:2], dtype="uint8") * 255
for c in contours:
    # get the bounding rect
    x, y, w, h = cv2.boundingRect(c)
    if w*h>1000:
        cv2.rectangle(mask, (x, y), (x+w, y+h), (0, 0, 255), -1)

res_final = cv2.bitwise_and(img, img, mask=cv2.bitwise_not(mask))

cv2.imshow("boxes", mask)
cv2.imshow("final image", res_final)
cv2.waitKey(0)
cv2.destroyAllWindows()

输出:

图1:原始图像:

enter image description here

图2:所需轮廓的掩模:

enter image description here

图 3:原始图像中检测到的轮廓(所需):

enter image description here


0
投票

这是获取矩形框的通用方法,如果近似值为 4 则它是矩形

approx = cv2.approxPolyDP(cnt,0.01*cv2.arcLength(cnt,True),True)
© www.soinside.com 2019 - 2024. All rights reserved.