我用了cv.HoughCircles函数,但不会选择合适的参数,效果不好。
原图:
结果:
{
```
```import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
def show(img):
if img.ndim == 2:
plt.imshow(img,cmap='gray')
else:
plt.imshow(cv.cvtColor(img,cv.COLOR_BGR2RGB))
plt.show()
img=cv.imread('C:/Users/1/Desktop/img/test.jpg')
gray=cv.cvtColor(img, cv.COLOR_BGR2GRAY)
dst = cv.equalizeHist(gray)#应用直方图均衡化
gaussian = cv.GaussianBlur(dst,(9,9),0)
#利用Canny进行边缘检测
GrayImage = cv.Canny(gaussian, 20,180, apertureSize=3)
ret, th1 = cv.threshold(GrayImage, 127, 255, cv.THRESH_TOZERO) # 固定阈值二值化
th2 = cv.adaptiveThreshold(th1, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY, 3, 5)
th3 = cv.adaptiveThreshold(th2, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 3, 5)
kernel = np.ones((6, 9), np.uint8)
erosion = cv.erode(th3, kernel, iterations=1) # 腐蚀处理
dilation = cv.dilate(erosion, kernel, iterations=1) # 膨胀处理
imgray = cv.Canny(erosion, 3, 8) # Canny算子边缘检测
circles = cv.HoughCircles(imgray, cv.HOUGH_GRADIENT, 1, 40, param1=100, param2=6, minRadius=8,maxRadius=10)
circles = np.uint16(np.around(circles))
P = circles[0] # 去掉circles数组一层外括号
for i in P:
cv.circle(img, (i[0], i[1]), i[2], (0, 255, 0), 5)
cv.circle(img, (i[0], i[1]), 5, (0, 0, 255), 3)
show(img)
}
我参考了一些博主的文章,链接:https://blog.csdn.net/SouthWooden/article/details/98741985