用霍夫变换原理检测圆 python
时间: 2023-11-27 22:05:09 浏览: 103
基于霍夫变换的圆检测,MATLAB,python,c语言的实现.zip
霍夫变换是一种常见的图像处理方法,可以用于检测圆。在 Python 中,可以使用 OpenCV 库来实现霍夫变换检测圆。
以下是实现步骤:
1. 导入 OpenCV 库和 numpy 库
```
import cv2
import numpy as np
```
2. 读取图像并转换为灰度图像
```
img = cv2.imread('image.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
```
3. 进行边缘检测
```
edges = cv2.Canny(gray, 50, 150, apertureSize=3)
```
4. 进行霍夫变换检测圆
```
circles = cv2.HoughCircles(edges, cv2.HOUGH_GRADIENT, dp=1, minDist=20, param1=50, param2=30, minRadius=0, maxRadius=0)
```
5. 绘制检测到的圆
```
if circles is not None:
circles = np.uint16(np.around(circles))
for i in circles[0, :]:
# 绘制圆心
cv2.circle(img, (i[0], i[1]), 2, (0, 0, 255), 3)
# 绘制圆
cv2.circle(img, (i[0], i[1]), i[2], (0, 255, 0), 2)
```
完整代码如下:
```
import cv2
import numpy as np
img = cv2.imread('image.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 50, 150, apertureSize=3)
circles = cv2.HoughCircles(edges, cv2.HOUGH_GRADIENT, dp=1, minDist=20, param1=50, param2=30, minRadius=0, maxRadius=0)
if circles is not None:
circles = np.uint16(np.around(circles))
for i in circles[0, :]:
# 绘制圆心
cv2.circle(img, (i[0], i[1]), 2, (0, 0, 255), 3)
# 绘制圆
cv2.circle(img, (i[0], i[1]), i[2], (0, 255, 0), 2)
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
阅读全文