霍夫变换之直线检测

霍夫变换

查看图像

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()

结果:

 
                            14657665-077694a762f9a49b.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()

结果:

 
                                         14657665-38e63ad116ac7d7d.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()

结果:

 
                             14657665-5591b1e57c0fe2fc.png
 
发布了82 篇原创文章 · 获赞 39 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/qq_28368377/article/details/104985248