52 lines
1.7 KiB
Python
52 lines
1.7 KiB
Python
from functools import reduce
|
|
from typing import Iterable
|
|
|
|
import cv2
|
|
import numpy as np
|
|
from funcy import first
|
|
|
|
from cv_analysis.utils.rectangle import Rectangle
|
|
|
|
|
|
def find_contours_and_hierarchies(image):
|
|
contours, hierarchies = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
|
return contours, first(hierarchies) if hierarchies is not None else None
|
|
|
|
|
|
def dilate_page_components(image: np.ndarray) -> np.ndarray:
|
|
# FIXME: Parameterize via factory
|
|
image = cv2.GaussianBlur(image, (7, 7), 0)
|
|
# FIXME: Parameterize via factory
|
|
thresh = cv2.threshold(image, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
|
|
# FIXME: Parameterize via factory
|
|
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
|
|
# FIXME: Parameterize via factory
|
|
dilate = cv2.dilate(thresh, kernel, iterations=4)
|
|
return dilate
|
|
|
|
|
|
def normalize_to_gray_scale(image: np.ndarray) -> np.ndarray:
|
|
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) if len(image.shape) > 2 else image
|
|
return image
|
|
|
|
|
|
def threshold_image(image: np.ndarray) -> np.ndarray:
|
|
# FIXME: Parameterize via factory
|
|
_, image = cv2.threshold(image, 254, 255, cv2.THRESH_BINARY)
|
|
return image
|
|
|
|
|
|
def invert_image(image: np.ndarray):
|
|
return ~image
|
|
|
|
|
|
def fill_rectangles(image: np.ndarray, rectangles: Iterable[Rectangle]) -> np.ndarray:
|
|
image = reduce(fill_in_component_area, rectangles, image)
|
|
return image
|
|
|
|
|
|
def fill_in_component_area(image: np.ndarray, rectangle: Rectangle) -> np.ndarray:
|
|
cv2.rectangle(image, (rectangle.x1, rectangle.y1), (rectangle.x2, rectangle.y2), (0, 0, 0), -1)
|
|
cv2.rectangle(image, (rectangle.x1, rectangle.y1), (rectangle.x2, rectangle.y2), (255, 255, 255), 7)
|
|
return image
|