将坐标点分成连通的一组和孤立的一组

将坐标点分成连通的一组和孤立的一组

示例代码

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)
    # Connected pixels: [[(0, 0), (1, 0)], [(2, 2), (3, 3)], [(10, 10), (11, 11), (12, 12)]]
    # Isolated pixels: [(0, 2), (100, 100)]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值