def grid_to_adjacency_matrix(grid, neighborhood=8):
"""Convert a boolean grid where 0's express holes and 1's connected pixel
into a sparse adjacency matrix representing the grid-graph.
Neighborhood for each pixel is calculated from its 4 or 8 more immediate
surrounding neighbors (defaults to 8)."""
coords = np.argwhere(grid)
coords_x = coords[:, 0]
coords_y = coords[:, 1]
# lil is the most performance format to build a sparse matrix iteratively
matrix = sparse.lil_matrix((0, coords.shape[0]), dtype=np.uint8)
if neighborhood == 4:
for px, py in coords:
row = (((px == coords_x) & (np.abs(py - coords_y) == 1)) |
((np.abs(px - coords_x) == 1) & (py == coords_y)))
matrix = sparse.vstack([matrix, row])
else:
for px, py in coords:
row = (np.abs(px - coords_x) <= 1) & (np.abs(py - coords_y) <= 1)
matrix = sparse.vstack([matrix, row])
matrix.setdiag(1)
# Once built, we convert it to compressed sparse columns or rows
return matrix.tocsc() # or .tocsr()
评论列表
文章目录