2022-05-17 09:17:24 +02:00

64 lines
1.8 KiB
Python

import cv2
import numpy as np
from cv_analysis.utils.display import show_mpl
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)
#show_mpl(image)
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):
x,y,w,h = cv2.boundingRect(cnt)
return 800 < cv2.contourArea(cnt) < 16000 or w/h > 3
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, (17, 7)) #20,3
close = cv2.morphologyEx(image, cv2.MORPH_CLOSE, close_kernel, iterations=1)
#show_mpl(close)
dilate_kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(7, 3)) #5,3
dilate = cv2.dilate(close, dilate_kernel, iterations=1)
#show_mpl(dilate)
cnts, _ = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
cnts = filter(is_likely_primary_text_segments, cnts)
return cnts