获取两个连通的点之间所有的坐标点
代码示例
import cv2
import numpy as np
from heapq import (
heappop,
heappush,
)
directions = [(0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0), (-1, 1)]
def get_connected_coord_list(mask, point_1, point_2):
if len(mask.shape) == 3:
mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
rows, cols = mask.shape[:2]
visited = np.zeros_like(mask, dtype=np.uint8)
queue = []
heappush(queue, (0, point_1))
visited[point_1[0], point_1[1]] = 1
parents = {}
connected_pixels = []
while queue:
current_distance, current_point = heappop(queue)
if current_point == point_2:
while current_point in parents:
current_point = parents[current_point]
connected_pixels.append(current_point)
connected_pixels.append(point_2)
return connected_pixels
for direction in directions:
next_point = (
current_point[0] + direction[0],
current_point[1] + direction[1],
)
if 0 <= next_point[0] < rows and 0 <= next_point[1] < cols:
if (
visited[next_point[0], next_point[1]] == 0
and mask[next_point[0], next_point[1]] > 0
):
visited[next_point[0], next_point[1]] = 1
heappush(queue, (current_distance + 1, next_point))
parents[next_point] = current_point
return []
if __name__ == "__main__":
mask_path = "./test.png"
mask = cv2.imread(mask_path, 0)
end_point_crop_list = [(1, 0), (8, 30), (16, 42), (46, 43)]
intersection_point_crop_list = [(10, 32), (11, 15), (18, 36), (44, 45)]
connected_coord_list = get_connected_coord_list(
mask, (1, 0), (10, 32)
)
print(f"==>> connected_coord_list: {connected_coord_list}")
mask_visual = np.zeros_like(mask)
for coord in connected_coord_list:
mask_visual[coord[0], coord[1]] = 255
print(len(connected_coord_list))
mask_visual_path = "./test_visual_point_mask.png"
cv2.imwrite(mask_visual_path, mask_visual)