opencv python霍夫变换检测直线段并在图像中显示
时间: 2023-06-14 22:04:50 浏览: 128
要使用OpenCV Python实现霍夫变换检测直线段并在图像中显示,请按照以下步骤进行:
1. 导入必要的库
```python
import cv2
import numpy as np
```
2. 读取图像并将其转换为灰度图像
```python
img = cv2.imread('image.jpg')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
```
3. 对图像进行边缘检测
```python
edges = cv2.Canny(gray,50,150,apertureSize = 3)
```
4. 进行霍夫变换
```python
lines = cv2.HoughLines(edges,1,np.pi/180,200)
```
其中,`1` 和 `np.pi/180` 分别表示距离和角度的精度,`200` 表示阈值,即认为是一条直线的最小投票数。
5. 在图像中绘制直线
```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)
```
6. 显示图像
```python
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
完整代码如下:
```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)
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('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
注意:在实际使用中,可能需要调整Canny边缘检测和霍夫变换的参数以获得更好的结果。
阅读全文