def erode(img, kern_size=3):
    retval, img = cv2.threshold(img, 254.0, 255.0, cv2.THRESH_BINARY)
kern = np.ones((kern_size, kern_size), np.uint8)
eroded = cv2.erode(img, kern, 1)
y, x = eroded.shape
return cv2.rectangle(eroded, (0, 0), (x, y), (255, 255, 255), 1)

def prep(img, kern_size=3):
    img = erode(img, kern_size)
retval, img = cv2.threshold(img, 200.0, 255.0, cv2.THRESH_BINARY_INV)
return cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

def blobbify(img, num_of_labels, kern_size=3, dilation_rate=10):
    prep_img, contours, hierarchy = prep(img.copy(), kern_size)
while len(contours) > num_of_labels:
    kern_size += dilation_rate
previous = prep_img, contours, hierarchy
processed_img, contours, hierarchy = prep(img.copy(), kern_size)
if len(contours) < num_of_labels:
    return processed_img, contours, hierarchy
else:
    return previous

def bounding_box(contours):
    bBox = []
for curve in contours:
    box = cv2.boundingRect(curve)
bBox.append(box)
return bBox
Detect text area in an image using python and opencv