用python的opencv写一个自动找圆的代码
时间: 2024-11-20 15:33:47 浏览: 3
在Python中使用OpenCV(cv2库)来检测圆形物体,通常我们会利用Hough Circle Transform算法。这是一个示例代码片段,它可以帮助你理解如何实现这个功能:
```python
import cv2
import numpy as np
def find_circles(image_path):
# 读取图像
image = cv2.imread(image_path, 0) # 将彩色图片转为灰度图像
if image is None:
print("无法打开图片")
return
# 使用Canny边缘检测
edges = cv2.Canny(image, low_threshold=50, high_threshold=150)
# 初始化参数
min_radius = 10
max_radius = int(np.sqrt(image.shape[0] * image.shape[1])) // 2 # 圆的直径不能超过图像边长的一半
circles = []
# Hough Circle Transform
method = cv2.HOUGH_GRADIENT
dp = 1 # 边缘像素连接的距离间隔
min_dist = 10 # 最小距离避免检测到太近的圆
param1 = 50 # 第一阶差分阈值
param2 = 30 # 第二阶差分阈值
min_radius, max_radius, _ = cv2.HoughCircles(edges, method, dp, min_dist, param1, param2, minRadius=min_radius, maxRadius=max_radius)
# 如果找到圆
if circles is not None:
circles = np.round(circles[0, :]).astype("int") # 取出最有可能的结果
for (x, y, r) in circles:
# 绘制圆
cv2.circle(image, (x, y), r, (0, 255, 0), 2)
cv2.putText(image, "Circle", (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
return image
# 使用函数并显示结果
result = find_circles('input_image.jpg')
cv2.imshow("Detected Circles", result)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
阅读全文