如何统计仅含0和1的对称numpy矩阵中1的连通簇数量?
统计对称0-1 NumPy矩阵中1的连通簇数量的方法
当然有,下面两种常用方法可以快速实现需求:
方法一:用图像处理领域的连通区域标记(scipy.ndimage.label)
这种方法适合按邻域规则(比如4邻域:上下左右;8邻域:包含对角线)判断1的连通性,步骤清晰直观:
- 导入所需库
- 定义目标对称矩阵
- 使用
scipy.ndimage.label标记连通区域,直接得到簇的数量
示例代码:
import numpy as np from scipy.ndimage import label # 你的示例对称矩阵 mat = np.array([[0, 0, 0, 0, 1, 1, 0], [0, 0, 0, 0, 1, 1, 0], [0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0]]) # 定义连通规则:这里用4邻域(若要8邻域,替换为[[1,1,1],[1,1,1],[1,1,1]]) structure = np.array([[0,1,0], [1,1,1], [0,1,0]]) # 标记连通区域,返回标签矩阵和簇的数量 labeled_mat, num_clusters = label(mat, structure=structure) print(f"1的连通簇数量:{num_clusters}") # 输出:2
方法二:用图论的连通组件分析(scipy.sparse.csgraph.connected_components)
对称0-1矩阵本质是无向图的邻接矩阵,可以把每个矩阵元素的位置看作节点,1表示节点间有连接边,直接用图论方法统计连通组件数:
示例代码:
import numpy as np from scipy.sparse.csgraph import connected_components mat = np.array([[0, 0, 0, 0, 1, 1, 0], [0, 0, 0, 0, 1, 1, 0], [0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0]]) # 过滤全0的行/列(无连接的孤立节点),避免干扰统计 non_zero_nodes = np.where(np.any(mat == 1, axis=1))[0] if len(non_zero_nodes) == 0: print("1的连通簇数量:0") else: # 提取仅包含有连接节点的子邻接矩阵 sub_mat = mat[np.ix_(non_zero_nodes, non_zero_nodes)] # 计算无向图的连通组件数 num_clusters, labels = connected_components(sub_mat, directed=False) print(f"1的连通簇数量:{num_clusters}") # 输出:2
注意事项
- 两种方法的核心区别是连通规则:方法一的邻域规则更贴近“图像块”的空间连通;方法二的图论规则只要节点间有直接边(矩阵对应位置为1)就算连通,无需位置相邻。可根据实际需求选择。
- 你的示例矩阵用两种方法都会得到2个连通簇,与预期一致。
内容的提问来源于stack exchange,提问作者Joost Dübken
相关产品推荐
相关产品推荐

