使用HoughCircles函数提取如下图像中的圆,并将圆显示出来
时间: 2024-04-21 07:28:49 浏览: 159
用Hough变换检测二值图像中的圆.docx
很高兴回答你的问题。首先,我们需要导入必要的库和加载图像:
```python
import cv2
import numpy as np
img = cv2.imread('circle.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
```
接下来,我们可以使用`HoughCircles`函数来检测圆。这个函数需要一些参数,包括输入图像、检测方法、圆心之间的最小距离、Canny边缘检测器的阈值等等。在这里,我们将使用默认参数:
```python
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 20,
param1=50, param2=30, minRadius=0, maxRadius=0)
```
最后,我们可以将圆绘制在原始图像上并显示它:
```python
if circles is not None:
circles = np.round(circles[0, :]).astype("int")
for (x, y, r) in circles:
cv2.circle(img, (x, y), r, (0, 255, 0), 2)
cv2.imshow("Circle Detection", img)
cv2.waitKey(0)
```
完整代码如下:
```python
import cv2
import numpy as np
img = cv2.imread('circle.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 20,
param1=50, param2=30, minRadius=0, maxRadius=0)
if circles is not None:
circles = np.round(circles[0, :]).astype("int")
for (x, y, r) in circles:
cv2.circle(img, (x, y), r, (0, 255, 0), 2)
cv2.imshow("Circle Detection", img)
cv2.waitKey(0)
```
输出的结果应该如下图所示:
![Circle Detection](https://i.imgur.com/7J0XtIo.jpg)
阅读全文