python检测同心圆
原图如下:
python
import cv2
import numpy as np
# 读取图像
image_path = r"E:\pycharm3\pythonProject\image\image.png"
img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE) # 灰度图像
img_color = cv2.imread(image_path, cv2.IMREAD_COLOR) # 彩色图像
# 检查图像加载
if img is None or img_color is None:
print("图像加载失败,请检查文件路径是否正确:", image_path)
exit()
# 第一次检测(较大圆)
circles1 = cv2.HoughCircles(
img,
cv2.HOUGH_GRADIENT,
dp=1,
minDist=60,
param1=50,
param2=60,
minRadius=170,
maxRadius=200
)
# 第二次检测(中等圆1)
circles2 = cv2.HoughCircles(
img,
cv2.HOUGH_GRADIENT,
dp=1,
minDist=170,
param1=100,
param2=60,
minRadius=60,
maxRadius=90
)
# 第三次检测(中等圆2,模糊图像)
blurred = cv2.GaussianBlur(img, (9, 9), 2) # 高斯模糊处理
circles3 = cv2.HoughCircles(
blurred,
cv2.HOUGH_GRADIENT,
dp=1,
minDist=170,
param1=100,
param2=60,
minRadius=60,
maxRadius=150
)
# 第四次检测(较小圆,增强边缘特性)
edges = cv2.Canny(img, 50, 150) # 使用 Canny 边缘检测
circles4 = cv2.HoughCircles(
edges,
cv2.HOUGH_GRADIENT,
dp=1,
minDist=30,
param1=100,
param2=60,
minRadius=90,
maxRadius=190
)
# 绘制检测结果
if circles1 is not None:
circles1 = np.uint16(np.around(circles1))
for i in circles1[0, :]:
# 绘制第一个检测结果的圆
cv2.circle(img_color, (i[0], i[1]), i[2], (255, 0, 0), 2) # 蓝色圆
cv2.circle(img_color, (i[0], i[1]), 2, (0, 255, 0), 3) # 圆心
print(f"检测到大环外圆:中心=({i [0]}, {i[1]}), 半径={i[2]}")
if circles2 is not None:
circles2 = np.uint16(np.around(circles2))
for i in circles2[0, :]:
# 绘制第二个检测结果的圆
cv2.circle(img_color, (i[0], i[1]), i[2], (0, 255, 255), 2) # 黄色圆
cv2.circle(img_color, (i[0], i[1]), 2, (255, 0, 255), 3) # 圆心
print(f"检测到小环内圆:中心=({i [0]}, {i[1]}), 半径={i[2]}")
if circles3 is not None:
circles3 = np.uint16(np.around(circles3))
for i in circles3[0, :]:
# 绘制第三个检测结果的圆
cv2.circle(img_color, (i[0], i[1]), i[2], (0, 0, 255), 2) # 红色圆
cv2.circle(img_color, (i[0], i[1]), 2, (255, 255, 0), 3) # 圆心
print(f"检测到小环外圆:中心=({i [0]}, {i[1]}), 半径={i[2]}")
if circles4 is not None:
circles4 = np.uint16(np.around(circles4))
for i in circles4[0, :]:
# 绘制第四个检测结果的圆
cv2.circle(img_color, (i[0], i[1]), i[2], (0, 255, 0), 2) # 绿色圆
cv2.circle(img_color, (i[0], i[1]), 2, (255, 0, 0), 3) # 圆心
print(f"检测到大环内圆:中心=({i [0]}, {i[1]}), 半径={i[2]}")
# 显示结果
cv2.imshow("Multiple Hough Circle Detection (4 times)", img_color)
cv2.imwrite("detected_circles_result.png",img_color ) # 保存结果到文件
# 等待退出
cv2.waitKey(0)
cv2.destroyAllWindows()