获取两个点之间连通的所有像素坐标和路径长度

获取两个点之间连通的所有像素坐标和路径长度

下面代码可以在掩码图像经过细化后任意连通的两个点之间获取:

  1. 两个点之间连通的所有像素坐标
  2. 两个个点之间连通的路径长度
  3. 两个点之间的掩码
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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值