import cv2 import numpy as np def detect_circles(image_path): # 读取图像 img = cv2.imread(image_path, cv2.IMREAD_COLOR) # 将图像转换为灰度图 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 使用高斯模糊处理图像 blurred = cv2.GaussianBlur(gray, (9, 9), 2) # 使用霍夫圆检测法检测圆圈 circles = cv2.HoughCircles(blurred, cv2.HOUGH_GRADIENT, dp=1.2, minDist=30, param1=80, param2=38, minRadius=15, maxRadius=60) # 确认至少检测到一个圆圈 if circles is not None: circles = np.round(circles[0, :]).astype("int") print(f"检测到 {len(circles)} 个圆圈") for i, (x, y, r) in enumerate(circles, start=1): # 从1开始计数 # 在图像中绘制圆圈 cv2.circle(img, (x, y), r, (0, 255, 0), 4) # 在图像中绘制圆心 cv2.circle(img, (x, y), 2, (0, 128, 255), 3) # 在图像中绘制圆圈编号 cv2.putText(img, f'{i}', (x - 10, y + 10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2) # 显示结果图像并处理退出事件 while True: cv2.imshow("detected circles", img) key = cv2.waitKey(1) & 0xFF if key == 27: # ESC键的ASCII码是27 break cv2.destroyAllWindows() else: print("没有检测到圆圈") # 调用函数并传递图像路径 detect_circles("image2.jpg")