python 霍夫直线检测
时间: 2023-11-17 14:02:56 浏览: 88
霍夫变换是一种在图像处理中用于检测任何形状的技术,其中最常见的应用是检测直线。下面是Python中使用OpenCV库实现霍夫直线检测的步骤:
1. 导入必要的库和读取图像
```python
import cv2
import numpy as np
img = cv2.imread('image.jpg')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray,50,150,apertureSize = 3)
```
2. 进行霍夫变换
```python
lines = cv2.HoughLines(edges,1,np.pi/180,200)
```
3. 绘制检测到的直线
```python
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)
```
4. 显示结果
```python
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
阅读全文