霍夫圆检测几种方法代码
时间: 2023-11-12 18:48:24 浏览: 71
用霍夫变换地方法来检测圆的代码
4星 · 用户满意度95%
霍夫圆检测是一种常见的圆形检测方法,主要用于在图像中检测出圆形的位置和半径。以下是几种常见的霍夫圆检测方法的示例代码:
1. HoughCircles函数(OpenCV)
```python
import cv2
import numpy as np
img = cv2.imread('circles.png', cv2.IMREAD_GRAYSCALE)
# 霍夫圆检测
circles = cv2.HoughCircles(img, cv2.HOUGH_GRADIENT, 1, 20, param1=50, param2=30, minRadius=0, maxRadius=0)
# 绘制检测出的圆
if circles is not None:
circles = np.round(circles[0, :]).astype("int")
for (x, y, r) in circles:
cv2.circle(img, (x, y), r, (0, 255, 0), 2)
cv2.imshow("Detected Circles", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
2. 梯度法霍夫圆检测
```python
import cv2
import numpy as np
img = cv2.imread('circles.png', cv2.IMREAD_GRAYSCALE)
# Canny边缘检测
edges = cv2.Canny(img, 50, 150)
# 霍夫梯度法圆检测
circles = cv2.HoughCircles(edges, cv2.HOUGH_GRADIENT, 1, 20, param1=50, param2=30, minRadius=0, maxRadius=0)
# 绘制检测出的圆
if circles is not None:
circles = np.round(circles[0, :]).astype("int")
for (x, y, r) in circles:
cv2.circle(img, (x, y), r, (0, 255, 0), 2)
cv2.imshow("Detected Circles", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
3. 累加器法霍夫圆检测
```python
import cv2
import numpy as np
img = cv2.imread('circles.png', cv2.IMREAD_GRAYSCALE)
# 高斯模糊
img = cv2.GaussianBlur(img, (9, 9), 2, 2)
# 累加器法霍夫圆检测
circles = cv2.HoughCircles(img, cv2.HOUGH_GRADIENT, 1, 20, param1=50, param2=30, minRadius=0, maxRadius=0)
# 绘制检测出的圆
if circles is not None:
circles = np.round(circles[0, :]).astype("int")
for (x, y, r) in circles:
cv2.circle(img, (x, y), r, (0, 255, 0), 2)
cv2.imshow("Detected Circles", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
以上代码使用的是Python和OpenCV库,可以根据自己的需求进行修改和优化。
阅读全文