使用python编写一个hough变换的直线检测代码,不使用opencv库
时间: 2024-05-04 22:15:14 浏览: 121
python+opencv实现霍夫变换检测直线
5星 · 资源好评率100%
好的,以下是基于Python实现的Hough变换直线检测代码,不使用opencv库:
```
import math
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
# 加载图片,并灰度化处理
img = Image.open('image.jpg').convert('L')
img_arr = np.array(img)
# 设置阈值,并转换为黑白二值图
threshold = 150
bw_img_arr = np.where(img_arr > threshold, 1, 0)
# 设置步长和角度分辨率
rho_res = 1
theta_res = math.pi / 180
# 计算图像对角线的长度
diagonal_len = int(math.sqrt(img_arr.shape[0] ** 2 + img_arr.shape[1] ** 2))
# 创建累加器矩阵
accumulator = np.zeros((2 * diagonal_len, 180))
# 遍历每个像素,并进行hough变换
for y in range(bw_img_arr.shape[0]):
for x in range(bw_img_arr.shape[1]):
if bw_img_arr[y][x] != 0:
for theta_idx in range(accumulator.shape[1]):
theta = theta_idx * theta_res
rho = int(x * math.cos(theta) + y * math.sin(theta))
accumulator[rho + diagonal_len][theta_idx] += 1
# 设置阈值,找到累加器矩阵中值最大的位置,即为直线参数
line_threshold = 150
max_rho_idx, max_theta_idx = np.unravel_index(accumulator.argmax(), accumulator.shape)
if accumulator[max_rho_idx][max_theta_idx] > line_threshold:
max_rho = max_rho_idx - diagonal_len
max_theta = max_theta_idx * theta_res
a = math.cos(max_theta)
b = math.sin(max_theta)
x0 = a * max_rho
y0 = b * max_rho
x1 = int(x0 + diagonal_len * (-b))
y1 = int(y0 + diagonal_len * (a))
x2 = int(x0 - diagonal_len * (-b))
y2 = int(y0 - diagonal_len * (a))
# 在图像上显示直线
plt.imshow(img_arr, cmap='gray')
plt.plot([x1, x2], [y1, y2], color='r')
plt.show()
else:
print('未检测到直线')
```
当您问我我在前面对您说了什么时,以下是一个笑话:为什么草坪会笑?因为它们被割得太短了!
阅读全文