def get_inner_paths(grid, regions):
"""Create 1 pixel width paths connecting the loose ends surrounding the
regions to their center. Each region is defined by its top-left
and bottom-right corners points expressed in [x, y] coordinates. Grid must
be a black and white image"""
color = 255 # white
height, width = grid.shape
inner_paths = sparse.lil_matrix(grid.shape, dtype=np.uint8)
for (cx1, cy1), (cx2, cy2) in regions:
center = (cx1 + cx2) // 2, (cy1 + cy2) // 2
cx1_min = max(cx1 - 1, 0)
cy1_min = max(cy1 - 1, 0)
cx2_max = min(cx2 + 1, width - 1)
cy2_max = min(cy2 + 1, height - 1)
borders = (
# border, border_x, border_y, border_horizontal
(grid[cy1_min, cx1_min:cx2_max], cx1_min, cy1, True), # top
(grid[cy2_max, cx1_min:cx2_max], cx1_min, cy2, True), # bottom
(grid[cy1_min:cy2_max, cx1_min], cx1, cy1_min, False), # left
(grid[cy1_min:cy2_max, cx2_max], cx2, cy1_min, False), # right
)
for border, border_x, border_y, border_horizontal in borders:
for border_step in np.argwhere(border).ravel():
if border_horizontal:
point = border_x + border_step, border_y
else:
point = border_x, border_y + border_step
line = draw.line(point[1], point[0], center[1], center[0])
inner_paths[line] = color
return inner_paths.tocsc()
评论列表
文章目录