How to remove contours with opencv?
07:06 13 Jun 2023

I'm using OpenCV's drawCountours function to remove only the boxes and preserve the text. However, I'm facing an issue where some of the boxes share pixels with the text, resulting in the removal of characters as well. The image I'm working with is this image.

Can you help me with any suggestions to remove the boxes?

Thank you!


import cv2

def contour_height(contour):
    (x, y, w, h) = cv2.boundingRect(contour)
    return h

image = cv2.imread("sample.png")

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (9, 9), 0)

# Applying threshold
threshold = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
edges = cv2.Canny(threshold, 50, 200)

# Finding and sorting contours based on the contour area
contours, hierarchy  = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
contours = sorted(contours, key=contour_height, reverse = True)

# Display
cv2_imshow(cv2.drawContours(image, contours[:35], -1, (0, 255, 0), 2))

The result is this image

python opencv