无法使用 cv2.HoughCircles 找到正确的圆圈

问题描述

当我运行下面的代码时,我无法在图像中找到一致的圆圈。我用作输入的图像是:

enter image description here

import numpy as np
import matplotlib.pyplot as plt
import cv2
img = cv2.imread("pipe.jpg")


# convert the image to RGB
img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
# copy the RGB image
cimg = img.copy()
# convert the RGB image to grayscale
img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# detect circles using hough transformation
circles = cv2.HoughCircles(image=img,method=cv2.HOUGH_GRADIENT,dp=3,mindist=60,param1=100,param2=39,maxRadius=200)

for co,i in enumerate(circles[0,:],start=1):
    i = [round(num) for num in i]
    cv2.circle(cimg,(i[0],i[1]),i[2],(0,255,0),2)
    cv2.circle(cimg,2,255),3)
print("Number of circles detected:",co)
plt.imshow(cimg)
plt.show()

我得到的结果是:

enter image description here

解决方法

作为预处理步骤,您通常会在检测之前平滑图像。不平滑会提示很多误检测。有时您在某些教程中看不到预平滑,因为处理的图像具有非常干净的边缘和很少的噪点。在执行检测之前尝试使用中值模糊或高斯模糊。

因此,请尝试以下操作:

import cv2

img = cv2.imread("pipe.jpg")

# convert the image to RGB
img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
# copy the RGB image
cimg = img.copy()
# convert the RGB image to grayscale
img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

### NEW - Smooth the image first
blur = cv2.GaussianBlur(img,(5,5),0)
# or try
# blur = cv2.medianBlur(img,5)

# detect circles using hough transformation
circles = cv2.HoughCircles(image=blur,method=cv2.HOUGH_GRADIENT,dp=3,minDist=60,param1=100,param2=39,maxRadius=200)

除此之外,要让检测找到图像中的所有圆,需要使用圆形霍夫变换的超参数并通过反复试验。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...