Python求解图像白色区域内边平行于图像边缘的最大内接矩形
求解图像白色区域内最大轴对齐矩形的Python实现

我们需要提取边与图像边缘平行、整个区域完全落在白色范围内的最大矩形,不需要四个顶点必须落在白色区域边缘,符合要求的输出效果如下:
实现思路
采用二值掩码+动态规划方案实现,无需轮廓检测,适配任意形状的白色区域:
- 先将图像转换为二值掩码,白色区域标记为1,非白色区域标记为0
- 逐行扫描图像,维护高度数组记录每一列向上连续的白色像素高度
- 对每一行的高度数组,用单调栈计算当前行可形成的最大矩形面积,全程记录全局最大矩形的坐标和尺寸
依赖安装
执行以下命令安装所需工具库:
pip install opencv-python numpy
完整实现代码
import cv2 import numpy as np def get_largest_white_rect(image_path, white_threshold=240): # 读入原始图像 img = cv2.imread(image_path) # 转灰度图后生成二值掩码:符合白色阈值的区域标记为1,其余为0 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) binary_mask = (gray >= white_threshold).astype(np.uint8) h, w = binary_mask.shape max_area = 0 # 最佳矩形存储格式:(左上角x坐标, 左上角y坐标, 宽度, 高度) best_rect = (0, 0, 0, 0) height_arr = [0] * w for row in range(h): # 更新当前行对应高度数组 for col in range(w): height_arr[col] = height_arr[col] + 1 if binary_mask[row][col] == 1 else 0 # 单调栈计算当前行可构造的最大矩形 stack = [] for col in range(w + 1): current_h = height_arr[col] if col < w else 0 while stack and current_h < height_arr[stack[-1]]: h_idx = stack.pop() rect_h = height_arr[h_idx] rect_w = col if not stack else col - stack[-1] - 1 area = rect_h * rect_w # 更新全局最大矩形 if area > max_area: max_area = area x = stack[-1] + 1 if stack else 0 y = row - rect_h + 1 best_rect = (x, y, rect_w, rect_h) stack.append(col) # 在原图上绘制识别到的最大矩形(绿色边框,线宽2) x, y, rect_w, rect_h = best_rect cv2.rectangle(img, (x, y), (x + rect_w, y + rect_h), (0, 255, 0), 2) return best_rect, img # 调用示例 if __name__ == "__main__": # 替换为你的本地图像路径 rect, result_img = get_largest_white_rect("test.png") print(f"最大矩形参数:左上角({rect[0]}, {rect[1]}),宽{rect[2]},高{rect[3]},面积{rect[2]*rect[3]}") cv2.imwrite("result.png", result_img) cv2.imshow("识别结果", result_img) cv2.waitKey(0) cv2.destroyAllWindows()
参数说明
white_threshold:白色像素的判断阈值,取值范围0-255,默认240,可根据图像实际亮度调整,数值越大对白色的判断标准越严格- 返回值
best_rect依次存储矩形左上角x坐标、左上角y坐标、宽度、高度,可直接对接后续业务逻辑使用
内容的提问来源于stack exchange,提问作者a_parida
相关产品推荐
相关产品推荐

