将坐标点分成连通的一组和孤立的一组
示例代码
def find(parent, i):
if parent[i] == i:
return i
return find(parent, parent[i])
def union(parent, rank, x, y):
xroot = find(parent, x)
yroot = find(parent, y)
if xroot != yroot:
if rank[xroot] < rank[yroot]:
parent[xroot] = yroot
elif rank[xroot] > rank[yroot]:
parent[yroot] = xroot
else:
parent[yroot] = xroot
rank[xroot] += 1
def classify_pixel_from_coord(points):
if not points:
return [], []
parent = {}
rank = {}
for point in points:
parent[point] = point
rank[point] = 0
directions = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]
for point in points:
for dx, dy in directions:
neighbor = (point[0] + dx, point[1] + dy)
if neighbor in points:
union(parent, rank, point, neighbor)
components = {}
for point in points:
root = find(parent, point)
if root in components:
components[root].append(point)
else:
components[root] = [point]
connected_pixels = list(components.values())
isolated_pixels = [comp[0] for comp in connected_pixels if len(comp) == 1]
connected_pixels = [comp for comp in connected_pixels if len(comp) > 1]
return connected_pixels, isolated_pixels
if __name__ == "__main__":
points = [(0, 0), (0, 2), (1, 0), (2, 2), (3, 3), (10, 10), (11, 11), (12, 12), (100, 100)]
connected, isolated = classify_pixel_from_coord(points)
print("Connected pixels:", connected)
print("Isolated pixels:", isolated)