Hough Space Transformation识别圆形并提取圆心列举代码
时间: 2024-10-11 14:16:15 浏览: 31
hough.zip_hough 圆形_hough直线_提取圆形MATLAB_直线提取
霍夫变换(Hough Transform)是一种在图像处理中用于检测特定形状,如直线、圆形等特征的方法。对于圆形检测,Hough空间转换会将原始像素坐标转换到参数空间(通常是半径和中心角度),通过查找密集区域来识别圆形。以下是基于OpenCV库的Python代码示例,演示如何在图像上应用霍夫变换来寻找圆形并提取圆心:
```python
import cv2
import numpy as np
# 读取图像
img = cv2.imread('image.jpg', 0) # 图像转为灰度图
# 初始化参数
rho = 1 # 半径增量
theta = np.pi / 180 # 角度增量
threshold = 50 # 密集区域阈值
min_radius = 10 # 最小圆半径
max_radius = img.shape[0] // 2 # 最大圆半径
# 创建投票矩阵
hough_image = np.zeros((img.shape[0], img.shape[1]), dtype=np.uint8)
# 应用霍夫变换
for i in range(img.shape[0]):
for j in range(img.shape[1]):
if img[i,j] != 0: # 非零像素投票
hough_image += np.int([np.sin(theta)*j + rho*np.cos(theta)*i,
np.cos(theta)*j - rho*np.sin(theta)*i])
# 找到圆心
peaks, _ = cv2.HoughCircles(hough_image, cv2.HOUGH_GRADIENT, theta=1, rho=rho,
minRadius=min_radius, maxRadius=max_radius,
threshold=threshold)
# 提取圆心
centers = peaks.reshape(-1, 2)[::-1, :]
# 可视化结果
for center in centers:
cv2.circle(img, (int(center[0]), int(center[1])), int(centers[0][2]), (0, 0, 255), 2)
cv2.imshow("Original with detected circles", img)
cv2.waitKey(0)
阅读全文