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

使用OpenCV识别矩形结构坐标并绘制轮廓

基于OpenCV绘制目标矩形轮廓并获取坐标操作步骤

你已经完成了图像的阈值分割,得到二值化图像,接下来可通过以下步骤实现目标矩形的轮廓绘制与坐标提取:

图像参考

  • 原始图像:
    Original Image
  • 阈值分割后图像:
    Image after thresholding
  • 期望输出效果:
    Desired output

具体操作步骤

1. 提取图像轮廓

使用cv2.findContours从二值化图像中提取轮廓,推荐用RETR_EXTERNAL只检测最外层轮廓,减少不必要的计算:

contours, hierarchy = cv2.findContours(th1, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

2. 筛选目标矩形轮廓

遍历所有轮廓,筛选符合矩形特征的目标轮廓:

  • 用cv2.approxPolyDP对轮廓做多边形近似,判断近似后顶点数量是否为4(矩形的核心特征)
  • 结合cv2.contourArea过滤面积过小的干扰轮廓
target_contours = []
for cnt in contours:
    # 计算轮廓近似多边形的精度参数
    epsilon = 0.02 * cv2.arcLength(cnt, True)
    approx = cv2.approxPolyDP(cnt, epsilon, True)
    # 筛选出矩形轮廓(4个顶点)且面积达标
    if len(approx) == 4 and cv2.contourArea(cnt) > 1000:
        target_contours.append(approx)

3. 绘制矩形并获取坐标

对筛选出的目标轮廓,用cv2.rectangle绘制外接矩形,同时通过cv2.boundingRect获取矩形的坐标参数(x, y, w, h):

# 创建原始图像的副本用于绘制结果
result_img = img.copy()
for cnt in target_contours:
    # 获取外接矩形的左上角坐标及宽高
    x, y, w, h = cv2.boundingRect(cnt)
    # 绘制红色矩形轮廓,线宽为2
    cv2.rectangle(result_img, (x, y), (x + w, y + h), (0, 0, 255), 2)
    # 打印输出矩形坐标
    print(f"目标矩形坐标:x={x}, y={y}, 宽度={w}, 高度={h}")

# 显示结果图像
cv2.imshow("Result", result_img)
cv2.waitKey(0)
cv2.destroyAllWindows()

完整代码整合

将上述步骤与你已有的阈值分割代码整合,完整示例如下:

import cv2

# 读取原始图像
img = cv2.imread("your_image_path.jpg")
# 转为灰度图(若原始图像非灰度图则需要此步骤)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 执行阈值分割
th1 = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]

# 提取图像轮廓
contours, hierarchy = cv2.findContours(th1, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# 筛选目标矩形轮廓
target_contours = []
for cnt in contours:
    epsilon = 0.02 * cv2.arcLength(cnt, True)
    approx = cv2.approxPolyDP(cnt, epsilon, True)
    if len(approx) == 4 and cv2.contourArea(cnt) > 1000:
        target_contours.append(approx)

# 绘制矩形并输出坐标
result_img = img.copy()
for cnt in target_contours:
    x, y, w, h = cv2.boundingRect(cnt)
    cv2.rectangle(result_img, (x, y), (x + w, y + h), (0, 0, 255), 2)
    print(f"目标矩形坐标:x={x}, y={y}, 宽={w}, 高={h}")

cv2.imshow("Result", result_img)
cv2.waitKey(0)
cv2.destroyAllWindows()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 12:00:21