opcv检测直线交叉_opencv霍夫变化检测直线和圆
时间: 2023-11-04 19:05:50 浏览: 222
OpenCV中的霍夫变换可以用来检测直线和圆。下面分别介绍一下如何使用霍夫变换检测直线和圆。
1. 检测直线
首先,需要将图像转换为灰度图像,并进行边缘检测。然后,使用cv2.HoughLines函数进行霍夫变换检测直线,该函数的参数包括输入图像、霍夫变换类型、直线的距离和角度分辨率、阈值等。具体代码如下:
```
import cv2
import numpy as np
# 读取图像并转换为灰度图像
img = cv2.imread('test.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 边缘检测
edges = cv2.Canny(gray, 50, 150, apertureSize=3)
# 霍夫变换检测直线
lines = cv2.HoughLines(edges, 1, np.pi/180, 200)
# 绘制直线
for line in lines:
rho, theta = line[0]
a = np.cos(theta)
b = np.sin(theta)
x0 = a*rho
y0 = b*rho
x1 = int(x0 + 1000*(-b))
y1 = int(y0 + 1000*a)
x2 = int(x0 - 1000*(-b))
y2 = int(y0 - 1000*a)
cv2.line(img, (x1, y1), (x2, y2), (0, 0, 255), 2)
# 显示图像
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
2. 检测圆
同样地,需要将图像转换为灰度图像,并进行边缘检测。然后,使用cv2.HoughCircles函数进行霍夫变换检测圆,该函数的参数包括输入图像、霍夫变换类型、圆心和半径的最小值和最大值等。具体代码如下:
```
import cv2
import numpy as np
# 读取图像并转换为灰度图像
img = cv2.imread('test.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 边缘检测
edges = cv2.Canny(gray, 50, 150, apertureSize=3)
# 霍夫变换检测圆
circles = cv2.HoughCircles(edges, 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('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
以上就是使用霍夫变换检测直线和圆的方法,希望能对你有所帮助。
阅读全文
相关推荐












