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

如何用Python(OpenCV)识别网格图中矩形的高度与宽度?

基于OpenCV识别网格中矩形的实际尺寸

核心思路

  1. 利用已知的网格相邻圆心间距(11.5毫米),建立图像像素与实际物理尺寸的映射比例
  2. 检测图中矩形的轮廓,获取其像素维度后,通过比例转换为实际毫米数

实现步骤与代码

import cv2
import numpy as np

# 读取图像
img = cv2.imread('yShnX.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# 预处理:降噪+二值化,提升轮廓检测精度
blurred = cv2.GaussianBlur(gray, (5,5), 0)
_, thresh = cv2.threshold(blurred, 127, 255, cv2.THRESH_BINARY_INV)

# 步骤1:检测网格圆心,计算像素-毫米比例
# 霍夫圆变换检测圆心(参数需根据实际图像调整)
circles = cv2.HoughCircles(
    gray, cv2.HOUGH_GRADIENT, dp=1.2, minDist=20,
    param1=50, param2=30, minRadius=5, maxRadius=15
)
if circles is not None:
    circles = np.uint16(np.around(circles))
    # 取前两个相邻圆心计算像素间距
    circle1 = circles[0][0]
    circle2 = circles[0][1]
    pixel_distance = np.sqrt((circle1[0]-circle2[0])**2 + (circle1[1]-circle2[1])**2)
    # 计算比例:每像素对应多少毫米
    mm_per_pixel = 11.5 / pixel_distance
else:
    raise ValueError("未检测到网格圆心,请调整霍夫圆参数")

# 步骤2:检测矩形轮廓
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 筛选矩形轮廓(通过近似多边形+面积过滤)
for cnt in contours:
    area = cv2.contourArea(cnt)
    if area < 1000:  # 过滤小轮廓
        continue
    # 多边形近似,判断是否为矩形
    epsilon = 0.02 * cv2.arcLength(cnt, True)
    approx = cv2.approxPolyDP(cnt, epsilon, True)
    if len(approx) == 4:
        # 获取矩形的外接矩形
        x, y, w, h = cv2.boundingRect(approx)
        # 转换为实际毫米尺寸
        actual_width = w * mm_per_pixel
        actual_height = h * mm_per_pixel
        print(f"矩形实际宽度:{actual_width:.2f} 毫米,实际高度:{actual_height:.2f} 毫米")
        # 可选:在图像上标注结果
        cv2.rectangle(img, (x,y), (x+w,y+h), (0,255,0), 2)
        cv2.putText(img, f"W:{actual_width:.1f}mm H:{actual_height:.1f}mm", 
                    (x,y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0), 2)

# 显示结果(可选)
cv2.imshow('Result', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

注意事项

  • 霍夫圆变换的参数(minDist、param1、param2等)需要根据图像的清晰度、网格大小微调,确保准确检测到圆心
  • 轮廓过滤的面积阈值(1000)需根据图像中矩形的实际像素大小调整,避免误检小噪点
  • 如果矩形存在倾斜,可使用cv2.minAreaRect()获取旋转矩形的真实宽高,再进行尺寸转换

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 21:06:24