OpenCV官方指导:
https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_houghcircles/py_houghcircles.html
注:因为霍夫圆检测对噪声比较敏感,所以首先要对图像做中值滤波。基于效率考虑,OpenCV中实现的霍夫变换圆检测是基于图像梯度实现的,分为两步:1. 检测边缘,发现可能的圆心。2. 基于第一步的基础上从候选圆心开始计算最佳半径大小。
视频源码:
import cv2 as cv
import numpy as np
def detect_circles_demo(image):
dst = cv.pyrMeanShiftFiltering(image, 10, 100) # 先做边缘保留滤波,注意,霍夫圆检测必须先做边缘保留滤波!!
cimage = cv.cvtColor(dst, cv.COLOR_BGR2GRAY)
circles = cv.HoughCircles(cimage, cv.HOUGH_GRADIENT, 1, 20, param1=35, param2=30, minRadius=0, maxRadius=0)
circles = np.uint16(np.around(circles))
for i in circles[0, :]:
cv.circle(image, (i[0], i[1]), i[2], (0, 0, 255), 2)
cv.circle(image, (i[0], i[1]), 2, (255, 0, 0), 2)
cv.imshow("circles", image)
print("-----------Python OpenCV Tutorial--------------")
src = cv.imread("C:/cv-samples/data/smarties.png")
cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
cv.imshow("input image", src)
detect_circles_demo(src)
cv.waitKey(0)
cv.destroyAllWindows()