网络编程
位置:首页>> 网络编程>> Python编程>> python hough变换检测直线的实现方法

python hough变换检测直线的实现方法

作者:Jackilina_Stone  发布时间:2022-06-11 10:08:37 

标签:python,hough,检测直线

1 原理

python hough变换检测直线的实现方法

 2 检测步骤

将参数空间(ρ,θ) 量化成m*n(m为ρ的等份数,n为θ的等份数)个单元,并设置累加器矩阵,初始值为0;

对图像边界上的每一个点(x,y)带入ρ=xcosθ+ysinθ,求得每个θ对应的ρ值,并在ρ和θ所对应的单元,将累加器加1,即:Q(i,j)=Q(i,j)+1;

检验参数空间中每个累加器的值,累加器最大的单元所对应的ρ和θ即为直角坐标系中直线方程的参数。

 3 接口

python hough变换检测直线的实现方法

image:二值图像,canny边缘检测输出。这里是result。
rho: 以像素为单位的距离精度,这里为1像素。如果想要检测的线段更多,可以设为0.1。
theta: 以弧度为单位的角度精度,这里为numpy.pi/180。如果想要检测的线段更多,可以设为0.01 * numpy.pi/180。
threshod: 阈值参数,int类型,超过设定阈值才被检测出线段,这里为10。
minLineLength:线段以像素为单位的最小长度。
maxLineGap:同一方向上两条线段判定为一条线段的最大允许间隔。

4 代码及结果


import os
import numpy as np
import cv2
from PIL import Image, ImageEnhance
import math

def img_processing(img):
 # 灰度化
 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
 ret, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU)
 # canny边缘检测
 edges = cv2.Canny(binary, 50, 150, apertureSize=3)
 return edges

def line_detect(img):
 img = Image.open(img)
 img = ImageEnhance.Contrast(img).enhance(3)
 # img.show()
 img = np.array(img)
 result = img_processing(img)
 # 霍夫线检测
 lines = cv2.HoughLinesP(result, 1, 1 * np.pi/180, 10, minLineLength=10, maxLineGap=5)
 # print(lines)
 print("Line Num : ", len(lines))

# 画出检测的线段
 for line in lines:
   for x1, y1, x2, y2 in line:
     cv2.line(img, (x1, y1), (x2, y2), (255, 0, 0), 1)
   pass
 img = Image.fromarray(img, 'RGB')
 img.show()

if __name__ == "__main__":
 line_detect("1.jpg")
 pass

原图如下:

python hough变换检测直线的实现方法

检测结果:

python hough变换检测直线的实现方法

python hough变换检测直线的实现方法

来源:https://blog.csdn.net/wss794/article/details/93023013

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com