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

如何使用OpenCV计算圆形中心与边缘最远端的距离

你要计算的圆形中心点到边缘最远端的距离即下图中绿色线段长度,规则圆形下等于圆的半径,可通过以下OpenCV方案实现:
示例图

实现方案

根据目标圆形的形态可以选择两种不同的实现思路:

方案1:霍夫圆变换(适合标准完整圆形)

运算速度快,直接返回检测到的圆心和半径,代码如下:

import cv2
import numpy as np

# 读取输入图像
img = cv2.imread("your_image_path.jpg")
# 转灰度+去噪预处理
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
# 边缘检测
edges = cv2.Canny(blurred, threshold1=50, threshold2=150)

# 霍夫圆变换检测圆
circles = cv2.HoughCircles(
    edges,
    method=cv2.HOUGH_GRADIENT,
    dp=1.2,
    minDist=100,
    param1=50,
    param2=30,
    minRadius=0,
    maxRadius=0
)

if circles is not None:
    circles = np.uint16(np.around(circles))
    # 取第一个检测到的目标圆
    center_x, center_y, radius = circles[0][0]
    # radius即为所求的中心到边缘最远端距离,单位为像素
    print(f"目标距离(像素):{radius}")

方案2:轮廓遍历法(适合不规则/有缺失的类圆形)

如果目标不是标准圆形,需要遍历轮廓点计算最大距离,代码如下:

import cv2
import numpy as np

# 读取输入图像+预处理
img = cv2.imread("your_image_path.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
edges = cv2.Canny(blurred, 50, 150)

# 提取轮廓,默认取面积最大的轮廓为目标圆形
contours, _ = cv2.findContours(edges.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
target_contour = max(contours, key=cv2.contourArea)

# 计算轮廓中心坐标
moment = cv2.moments(target_contour)
center_x = int(moment["m10"] / moment["m00"])
center_y = int(moment["m01"] / moment["m00"])

# 遍历所有轮廓点,计算到中心的最大欧氏距离
max_distance = 0
for point in target_contour:
    px, py = point[0]
    current_dist = np.sqrt((px - center_x)**2 + (py - center_y)**2)
    if current_dist > max_distance:
        max_distance = current_dist

print(f"目标最大距离(像素):{max_distance}")
补充说明
  • 以上两种方案返回的都是像素单位的距离,如果需要转换为物理长度,可以在同拍摄场景下放置已知长度的参照物,计算像素与实际长度的换算比例后再做转换即可。
  • 可以根据自己的图像调整预处理的阈值、霍夫圆变换的参数,适配不同的拍摄环境。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 11:15:03