如何从numpy.argwhere返回的矩阵索引中查找相邻元素组成的最大模式
矩阵最大连通同色模式查找指导
现有实现合理性验证
你当前使用np.argwhere(matrix==color)提取目标颜色所有坐标的实现方向是正确的,这是后续查找相邻连通模式的必要基础。
推荐实现方案
根据依赖情况可以选择以下两种方案,默认适配4连通(仅上下左右算相邻),需要8连通(含斜向相邻)可按照注释调整参数。
方案1:基于scipy连通分量分析(最简实现)
直接调用scipy的成熟连通分量标记能力,代码量少、运算效率高:
import numpy as np from scipy import ndimage color = 10 # 生成目标颜色的二值掩码 mask = (matrix == color).astype(int) # 标记所有连通区域,默认4连通,返回标签矩阵和区域总数 labeled_matrix, num_features = ndimage.label(mask) # 若需使用8连通,替换上一行代码为: # structure = [[1,1,1],[1,1,1],[1,1,1]] # labeled_matrix, num_features = ndimage.label(mask, structure=structure) # 统计每个连通区域的像素数量 region_sizes = ndimage.sum(mask, labeled_matrix, range(num_features + 1)) # 筛选出最大的非背景区域标签(背景标签为0) max_region_label = region_sizes[1:].argmax() + 1 # 提取最大模式对应的所有坐标 max_region_coords = np.argwhere(labeled_matrix == max_region_label)
方案2:基于BFS手动实现(无第三方依赖)
如果不能引入scipy依赖,可以基于你已经得到的solutions坐标列表手动做广度优先搜索遍历:
import numpy as np from collections import deque color = 10 solutions = np.argwhere(matrix == color) # 转换为元组集合,实现O(1)复杂度的坐标存在性判断 coord_set = set(tuple(coord) for coord in solutions) visited = set() max_region = [] # 4连通的坐标偏移量,需8连通可补充(1,1),(1,-1),(-1,1),(-1,-1) offsets = [(-1,0),(1,0),(0,-1),(0,1)] for coord in solutions: coord_tuple = tuple(coord) if coord_tuple not in visited: q = deque([coord_tuple]) visited.add(coord_tuple) current_region = [coord_tuple] while q: x,y = q.popleft() for dx, dy in offsets: neighbor = (x+dx, y+dy) if neighbor in coord_set and neighbor not in visited: visited.add(neighbor) q.append(neighbor) current_region.append(neighbor) # 更新最大区域记录 if len(current_region) > len(max_region): max_region = current_region
补充说明
如果需求中的「模式」不是指最大连通同色区域,而是指定规则的特殊形状匹配,需要明确模式的具体定义后再调整判断逻辑。
内容的提问来源于stack exchange,提问作者Syed Muhammad Ibrahim
相关产品推荐
相关产品推荐

