2022-03-23 13:46:57 +01:00

59 lines
1.6 KiB
Python

import cv2
def remove_primary_text_regions(image):
"""Removes regions of primary text, meaning no figure descriptions for example, but main text body paragraphs.
Args:
image: Image to remove primary text from.
Returns:
Image with primary text removed.
"""
image = image.copy()
cnts = find_primary_text_regions(image)
for cnt in cnts:
x, y, w, h = cv2.boundingRect(cnt)
cv2.rectangle(image, (x, y), (x + w, y + h), (255, 255, 255), -1)
return image
def find_primary_text_regions(image):
"""Finds regions of primary text, meaning no figure descriptions for example, but main text body paragraphs.
Args:
image: Image to remove primary text from.
Returns:
Image with primary text removed.
References:
https://stackoverflow.com/questions/58349726/opencv-how-to-remove-text-from-background
"""
def is_likely_primary_text_segments(cnt):
return 800 < cv2.contourArea(cnt) < 15000
image = image.copy()
if len(image.shape) > 2:
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
image = cv2.threshold(image, 253, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
close_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (20, 3))
close = cv2.morphologyEx(image, cv2.MORPH_CLOSE, close_kernel, iterations=1)
dilate_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 3))
dilate = cv2.dilate(close, dilate_kernel, iterations=1)
cnts, _ = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
cnts = filter(is_likely_primary_text_segments, cnts)
return cnts