59 lines
2.0 KiB
Python

from functools import reduce
from itertools import combinations
from typing import List, Tuple, Set
from cv_analysis.utils import until, make_merger_sentinel
from cv_analysis.utils.rectangle import Rectangle
from cv_analysis.utils.spacial import related
def merge_related_rectangles(rectangles: List[Rectangle]) -> List[Rectangle]:
"""Merges rectangles that are related to each other, iterating on partial merge results until no more mergers are
possible."""
assert isinstance(rectangles, list)
no_new_merges = make_merger_sentinel()
return until(no_new_merges, merge_rectangles_once, rectangles)
def merge_rectangles_once(rectangles: List[Rectangle]) -> List[Rectangle]:
"""Merges rectangles that are related to each other, but does not iterate on the results."""
def merge_if_related(
acc: Tuple[Set[Rectangle], Set[Rectangle]],
pair: Tuple[Rectangle, Rectangle],
) -> Tuple[Set[Rectangle], Set[Rectangle]]:
"""Merges two rectangles if they are related, otherwise returns the accumulator unchanged."""
alpha, beta = pair
merged, used = acc
def unused(*args) -> bool:
return not used & {*args}
if unused(alpha) and unused(beta) and related(alpha, beta):
return merged | {bounding_rect(alpha, beta)}, used | {alpha, beta}
else:
return merged, used
rectangles = set(rectangles)
merged, used = reduce(merge_if_related, combinations(rectangles, 2), (set(), set()))
return list(merged | rectangles - used)
# for alpha, beta in combinations(rectangles, 2):
# if related(alpha, beta):
# rectangles.remove(alpha)
# rectangles.remove(beta)
# rectangles.append(bounding_rect(alpha, beta))
# return rectangles
# return rectangles
def bounding_rect(alpha: Rectangle, beta: Rectangle) -> Rectangle:
return Rectangle(
min(alpha.x1, beta.x1),
min(alpha.y1, beta.y1),
max(alpha.x2, beta.x2),
max(alpha.y2, beta.y2),
)