霍夫圆检测python代码 不调用opencv
时间: 2023-06-17 18:06:45 浏览: 48
霍夫圆检测是一种经典的圆形检测算法,OpenCV中提供了对应的函数,但如果不想使用OpenCV,也可以自己实现。以下是一个简单的Python实现:
```python
import numpy as np
import math
def hough_circle(image, radius):
# 霍夫空间的r维大小
rows, cols = image.shape
hough = np.zeros((rows, cols))
# 预先计算好sin和cos
sin_table = np.sin(np.arange(360) * math.pi / 180)
cos_table = np.cos(np.arange(360) * math.pi / 180)
# 遍历图像每个像素
for r in range(rows):
for c in range(cols):
# 如果当前像素是边缘点
if image[r, c] > 0:
# 在以当前像素为圆心,半径为r的圆上进行遍历
for i in range(360):
a = int(r - radius * sin_table[i])
b = int(c - radius * cos_table[i])
if a >= 0 and a < rows and b >= 0 and b < cols:
hough[a, b] += 1
# 取出霍夫空间中的极大值点
max_points = []
for r in range(rows):
for c in range(cols):
if hough[r, c] > 0:
flag = True
for i in range(-1, 2):
for j in range(-1, 2):
if r+i >= 0 and r+i < rows and c+j >= 0 and c+j < cols:
if hough[r+i, c+j] > hough[r, c]:
flag = False
break
if not flag:
break
if flag:
max_points.append((r, c))
return max_points
```
该函数接受一个二值化图像(边缘检测后的图像),以及要检测的圆的半径。函数首先创建一个与图像大小相同的霍夫空间,并预先计算好sin和cos值。然后遍历图像每个像素,如果当前像素是边缘点,就在以当前像素为圆心、半径为r的圆上进行遍历,并在霍夫空间中对应的位置加1。最后取出霍夫空间中的极大值点作为圆心坐标,并返回。