获取两个点之间连通的所有像素坐标和路径长度
下面代码可以在掩码图像经过细化后任意连通的两个点之间获取:
- 两个点之间连通的所有像素坐标
- 两个个点之间连通的路径长度
- 两个点之间的掩码
def get_connected_points_and_path_length(mask, point_1, point_2):
mask = cv2.ximgproc.thinning(
mask,
# thinningType=cv2.ximgproc.THINNING_ZHANGSUEN
thinningType=cv2.ximgproc.THINNING_GUOHALL
)
rows, cols = mask.shape
visited = np.zeros_like(mask, dtype=np.uint8)
queue = []
# 优先队列,优先级是距离
# 堆是一种数据结构,它总是保持最小元素在顶部。
# 将元组(距离, 点)放入堆中,距离较小的点会优先出队
heappush(queue, (0, point_1))
visited[point_1[1], point_1[0]] = 1
# 记录每个点的父节点,用于回溯路径
parents = {}
connected_pixels = []
while queue:
# 从对中取出距离最小对应的元组
current_distance, current_point = heappop(queue)
if current_point == point_2:
# 回溯路径并计算长度
path_length = 0
while current_point in parents:
path_length += 1
current_point = parents[current_point]
connected_pixels.append(current_point)
return path_length, connected_pixels
for direction in directions:
next_point = (
current_point[0] + direction[0],
current_point[1] + direction[1]
)
if 0 <= next_point[0] < cols and 0 <= next_point[1] < rows:
if (
visited[next_point[1], next_point[0]] == 0 and
mask[next_point[1], next_point[0]] > 0
):
visited[next_point[1], next_point[0]] = 1
# 优先队列,优先级是距离
heappush(queue, (current_distance + 1, next_point))
parents[next_point] = current_point
return -1, []
if __name__ == '__main__':
mask_path = "./test.png"
mask = cv2.imread(mask_path, 0)
# TODO 定义掩码中连通的两个点的坐标
# p1, p2 = ...
# 调用函数并打印结果
path_length, connected_points = get_connected_points_and_path_length(
mask,
p_1,
p_2
)
mask_visual = np.zeros_like(mask)
for point in connected_points:
mask_visual[point[1], point[0]] = 255
print(f"==>> path_length: {path_length}")
print(len(connected_points))
mask_visual_path = "./test_visual_point_mask.png"
cv2.imwrite(mask_visual_path, mask_visual)