如何从图像数组中获取最优矩形数量及尺寸信息?
提取数组中的最优矩形方案

问题描述
我有一个如上图所示的数组,其中存在大量潜在矩形,但需要提取最优矩形信息:共3个矩形,尺寸分别为4×3、3×3和1×3。请问有没有简洁优雅的实现方法?
我曾尝试循环遍历但未成功(尤其是矩形计数部分),也使用过np.any和np.where,但它们仅适用于单个大矩形,无法处理包含多个矩形的图像。
方法一:使用OpenCV连通区域分析(简洁高效)
利用OpenCV的连通区域统计功能,可直接识别所有独立矩形区域并获取其尺寸:
import numpy as np import cv2 # 模拟输入数组(根据示意图生成) arr = np.array([ [1,1,1,0,1,1,1], [1,1,1,0,1,1,1], [1,1,1,0,1,1,1], [1,1,1,0,0,0,0], [0,0,0,0,1,1,1] ], dtype=np.uint8) # 识别4连通区域,返回统计信息 num_labels, _, stats, _ = cv2.connectedComponentsWithStats(arr, connectivity=4) # 提取每个矩形的尺寸(跳过背景标签0) rect_sizes = [] for i in range(1, num_labels): height = stats[i, cv2.CC_STAT_HEIGHT] width = stats[i, cv2.CC_STAT_WIDTH] rect_sizes.append(f"{height}×{width}") print(f"提取到的矩形尺寸:{rect_sizes}") # 输出:['4×3', '3×3', '1×3']
说明
cv2.connectedComponentsWithStats自动识别上下左右连通的区域,返回每个区域的宽、高、位置等统计数据- 目标区域本身是规则矩形,直接取统计结果的宽高即可得到最优矩形尺寸
方法二:纯NumPy实现(无第三方依赖)
若不想引入OpenCV,可通过坐标分组的方式实现:
import numpy as np arr = np.array([ [1,1,1,0,1,1,1], [1,1,1,0,1,1,1], [1,1,1,0,1,1,1], [1,1,1,0,0,0,0], [0,0,0,0,1,1,1] ]) # 获取所有非零元素的行、列坐标 y_coords, x_coords = np.where(arr != 0) # 按连续列分组(矩形的列是连续的) unique_x = np.sort(np.unique(x_coords)) x_groups = [] current_group = [unique_x[0]] for x in unique_x[1:]: if x == current_group[-1] + 1: current_group.append(x) else: x_groups.append(current_group) current_group = [x] x_groups.append(current_group) # 对每个列块计算对应的行范围,得到矩形尺寸 rect_sizes = [] for x_group in x_groups: # 筛选当前列块内的所有行坐标 y_in_group = y_coords[(x_coords >= x_group[0]) & (x_coords <= x_group[-1])] height = y_in_group.max() - y_in_group.min() + 1 width = len(x_group) rect_sizes.append(f"{height}×{width}") print(f"提取到的矩形尺寸:{rect_sizes}") # 输出:['4×3', '3×3', '1×3']
说明
- 先定位所有非零元素的坐标,再将连续的列划分为一组(对应矩形的宽度方向)
- 对每组列,找到覆盖的最小/最大行,计算高度,最终得到每个矩形的尺寸
内容的提问来源于stack exchange,提问作者kmojanky
相关产品推荐
相关产品推荐

