You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用OpenCV获取图像中白色边框矩形的坐标

基于OpenCV的白色边框矩形坐标提取实现

现有代码问题点

  • 未加入颜色筛选逻辑:直接对全灰度图做边缘检测,会提取所有物体的边缘轮廓,无法过滤非白色边框的矩形
  • 阈值逻辑冗余:代码中同时生成了Canny边缘和二值化阈值结果,但未使用二值化结果做白色筛选

修正实现步骤

  1. 先对原图做白色区域掩码提取:通过BGR颜色区间筛选,仅保留接近白色的像素区域
  2. 基于白色掩码做轮廓检测,避免非白色区域的轮廓干扰
  3. 轮廓筛选阶段补充面积、凸性校验,过滤无效小轮廓

修正后可运行代码

import cv2
import numpy as np
import random as rng

image = cv2.imread('strawberry.png')
# 第一步:提取白色区域掩码,BGR格式下白色三个通道值均接近255
lower_white = np.array([220, 220, 220], dtype=np.uint8)
upper_white = np.array([255, 255, 255], dtype=np.uint8)
white_mask = cv2.inRange(image, lower_white, upper_white)

# 可选:对掩码做形态学开运算,去除噪点
kernel = np.ones((3,3), np.uint8)
white_mask = cv2.morphologyEx(white_mask, cv2.MORPH_OPEN, kernel)

# 第二步:基于白色掩码做轮廓检测
contours, _ = cv2.findContours(white_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

boundRect = []
for c in contours:
    # 多边形拟合,epsilon系数可根据矩形边框平滑度调整
    epsilon = 0.02 * cv2.arcLength(c, True)
    contours_poly = cv2.approxPolyDP(c, epsilon, True)
    # 筛选凸四边形轮廓
    if len(contours_poly) == 4 and cv2.isContourConvex(contours_poly):
        rect = cv2.boundingRect(contours_poly)
        x, y, w, h = rect
        # 过滤面积过小的矩形,阈值可根据实际需求调整
        if w * h < 100:
            continue
        # 保留你原有的宽高比大于2的过滤条件,不需要可删除
        if w / h > 2:
            boundRect.append(rect)

# 绘制结果输出
drawing = np.zeros_like(image)
for i, rect in enumerate(boundRect):
    x, y, w, h = rect
    color = (rng.randint(0,256), rng.randint(0,256), rng.randint(0,256))
    cv2.rectangle(drawing, (x, y), (x+w, y+h), color, 2)
    print(f'矩形坐标:X={x}, Y={y}, 宽={w}, 高={h}')

参数调整说明

  • 颜色阈值lower_white可以根据实际图像的白色深浅调整,避免漏检或者误检
  • 多边形拟合的epsilon系数、面积阈值、宽高比阈值都可以根据你的实际业务场景调整,适配不同尺寸的矩形

内容的提问来源于stack exchange,提问作者xionxavier

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 18:48:02