cv-analysis-service/vidocp/utils/post_processing.py

77 lines
2.2 KiB
Python

from collections import namedtuple
from functools import partial
from itertools import starmap
def remove_overlapping(rectangles):
def overlap(a, b):
return compute_intersection(a, b) > 0
def does_not_overlap(rect, rectangles):
return not any(overlap(rect, r2) for r2 in rectangles if not rect == r2)
rectangles = list(map(xywh_to_vec_rect, rectangles))
rectangles = filter(partial(does_not_overlap, rectangles=rectangles), rectangles)
rectangles = map(vec_rect_to_xywh, rectangles)
return rectangles
def remove_included(rectangles):
def included(a, b):
return b.xmin >= a.xmin and b.ymin >= a.ymin and b.xmax <= a.xmax and b.ymax <= a.ymax
def is_not_included(rect, rectangles):
return not any(included(r2, rect) for r2 in rectangles if not rect == r2)
rectangles = list(map(xywh_to_vec_rect, rectangles))
rectangles = filter(partial(is_not_included, rectangles=rectangles), rectangles)
rectangles = map(vec_rect_to_xywh, rectangles)
return rectangles
# FIXME: For some reason some isolated rects remain.
def remove_isolated(rectangles):
def are_neighbours(a, b):
def adjacent(n, m):
return abs(n - m) <= 1
return any(starmap(adjacent, [(b.xmin, a.xmax), (b.ymin, a.ymax), (b.xmax, a.xmin), (b.ymax, a.ymin)]))
def is_connected(rect, rectangles):
return any(are_neighbours(r2, rect) for r2 in rectangles if not rect == r2)
rectangles = list(map(xywh_to_vec_rect, rectangles))
rectangles = filter(partial(is_connected, rectangles=rectangles), rectangles)
rectangles = map(vec_rect_to_xywh, rectangles)
return rectangles
Rectangle = namedtuple("Rectangle", "xmin ymin xmax ymax")
def compute_intersection(a, b):
dx = min(a.xmax, b.xmax) - max(a.xmin, b.xmin)
dy = min(a.ymax, b.ymax) - max(a.ymin, b.ymin)
return dx * dy if (dx >= 0) and (dy >= 0) else 0
def has_no_parent(hierarchy):
return hierarchy[-1] <= 0
def xywh_to_vec_rect(rect):
x1, y1, w, h = rect
x2 = x1 + w
y2 = y1 + h
return Rectangle(x1, y1, x2, y2)
def vec_rect_to_xywh(rect):
x, y, x2, y2 = rect
w = x2 - x
h = y2 - y
return x, y, w, h