霍夫变换之直线检测

霍夫变换

查看图像
import matplotlib.pyplot as plt
import numpy as np
import cv2

# 读取图像
img = cv2.imread('bright-close-up-colorful-2097221.jpg')
# 复制图像
img_copy = np.copy(img)
# 颜色空间转换:BGR——RGB
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# 显示图像
plt.imshow(img_rgb)
plt.show()

结果:

01.png

边缘检测

# 灰度图像
gray = cv2.cvtColor(img_copy, cv2.COLOR_BGR2GRAY)
# 高斯滤波
gray_blur = cv2.GaussianBlur(gray, (5,5), 0)
plt.imshow(gray_blur,cmap="gray")
plt.show()
# 设置canny的参数
low_threshold = 120
high_threshold = 200
edges = cv2.Canny(gray_blur,low_threshold,high_threshold)

plt.figure(figsize=(10,8))
plt.imshow(edges,cmap="gray")
plt.show()

结果:

03.png

霍夫变换检测直线

# 使用霍夫变换寻找直线
# 参数设置
rho = 1
theta = np.pi/180
threshold = 65
min_line_length = 250
max_line_gap = 6

# 寻找直线
lines = cv2.HoughLinesP(edges, rho, theta, threshold, np.array([]), min_line_length, max_line_gap)
line_image = np.copy(img_copy)
# 绘制直线
for line in lines:
    for x1,y1,x2,y2 in line:
        cv2.line(line_image,(x1,y1),(x2,y2),(255,0,0),5)

plt.imshow(line_image)
plt.show()

结果:

04.png

你可能感兴趣的:(霍夫变换之直线检测)