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

基于Python-OpenCV识别绘图图像中线条内的小圆圈问题

解决线条内部小圆圈检测问题

输入图像描述

我需要识别图像中线条内部的小圆圈,但使用以下代码无法得到正确结果:

import cv2
import numpy as np

# Load image
image = cv2.imread("image_33(1).png",0)  # Load in grayscale
# Apply thresholding to convert to binary image
_, binary_image = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY)

# Apply edge detection
contours, _ = cv2.findContours(binary_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

circle_params = dict(
    dp=1,      # Resolution of inverse accumulator 1
    minDist=180,  # Minimum distance between centers of circles 
    param1=150,  # Specific parameter of circle detection method 
    param2=15, # Specific parameter of circle detection method 
    minRadius=4,  # Minimum radius of circles to detect 
    maxRadius= 10 # Maximum radius of circles to detect 7
)


# Appliquer la détection de cercles
circles = cv2.HoughCircles(image, cv2.HOUGH_GRADIENT, **circle_params)

# Dessiner les contours et les cercles détectés sur l'image
image_with_contours = cv2.drawContours(cv2.cvtColor(image, cv2.COLOR_GRAY2BGR), contours, -1, (0, 255, 0), 2)
image_with_circles = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)
if circles is not None:
    circles = np.round(circles[0, :]).astype(int)
    for (x, y, r) in circles:
        cv2.circle(image_with_circles, (x, y), r, (0, 0, 255), 2)
# Afficher les résultats
cv2.imwrite("detect_Circles(5).jpg", image_with_circles)

我使用了HoughCircle的代码,但无法检测到小圆圈
I used the hough circle code but it was not able to detect the small circles
(注:上述句子为谷歌翻译版本,核心意思可能存在偏差)


问题分析

原代码检测失败的核心原因是参数设置不合理,且缺少必要的预处理:

  1. minDist设置过大:180的最小圆心距离远大于小圆圈之间的实际间距,导致大部分候选圆被直接过滤。
  2. param1阈值过高:150的Canny边缘检测阈值会过滤掉小圆圈的弱边缘,霍夫圆检测无法捕捉到有效轮廓。
  3. param2阈值过高:15的累加器阈值要求候选圆的投票数达标,小圆圈的投票数很难达到这个标准。
  4. 未做降噪处理:原图的噪声和线条细节会干扰霍夫圆的检测精度。

修改后的代码

import cv2
import numpy as np

# 加载灰度图
image = cv2.imread("image_33(1).png", 0)
# 高斯模糊降噪,减少噪声干扰
blurred = cv2.GaussianBlur(image, (5, 5), 0)

# 调整霍夫圆检测参数
circle_params = dict(
    dp=1,
    minDist=20,  # 缩小最小圆心距离,适配小圆圈间距
    param1=50,   # 降低Canny阈值,保留小圆圈边缘
    param2=8,    # 降低累加器阈值,更容易检测到小圆圈
    minRadius=3,
    maxRadius=12
)

# 对模糊后的图像进行霍夫圆检测
circles = cv2.HoughCircles(blurred, cv2.HOUGH_GRADIENT, **circle_params)

# 绘制检测结果
image_with_circles = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)
if circles is not None:
    circles = np.round(circles[0, :]).astype(int)
    for (x, y, r) in circles:
        cv2.circle(image_with_circles, (x, y), r, (0, 0, 255), 2)

cv2.imwrite("detect_Circles_fixed.jpg", image_with_circles)

关键调整说明

  • 高斯模糊:cv2.GaussianBlur 平滑图像,减少无关噪声对检测的干扰。
  • minDist=20:根据图像中小圆圈的实际间距调整,确保不会过滤掉相邻的圆。
  • param1=50:降低Canny边缘检测的高阈值,保留小圆圈的边缘信息。
  • param2=8:降低累加器的投票阈值,让小圆圈更容易被检测到。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 10:32:46