import cv2
import numpy as np
# 读取图像
image_path = r"C:\Users\yh\Pictures\2.png"
img = cv2.imread(image_path)
# 将图像转换为灰度图
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 进行阈值分割
_, thresholded = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
# 形态学操作 - 填充孔洞
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
filled = cv2.morphologyEx(thresholded, cv2.MORPH_CLOSE, kernel)
# 进行边缘检测
edges = cv2.Canny(filled, 100, 200)
# 使用霍夫圆变换检测圆形轮廓
circles = cv2.HoughCircles(edges, cv2.HOUGH_GRADIENT, dp=1, minDist=50,
param1=4, param2=4, minRadius=340, maxRadius=380)
# 在原始图像上标注圆弧位置
if circles is not None:
circles = np.round(circles[0, :]).astype(int)
for (x, y, r) in circles:
if ((x+1)>filled.shape[0]) or ((y+1)>filled.shape[1]):
continue
if filled[y][x]==0:
continue
# 绘制圆心和圆
cv2.circle(img, (x, y), r, (0, 0, 255), 2)
cv2.circle(img, (x, y), 3, (0, 255, 0), -1)
# 显示结果图像
cv2.imshow("Result", img)
cv2.waitKey(0)
cv2.destroyAllWindows()