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

文章来源:嗨学网 敏而好学论坛www.piaodoo.com 欢迎大家相互学习

1 原理

嗨学网

 2 检测步骤

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

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

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

 3 接口

嗨学网

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

原图如下:

嗨学网

检测结果:

嗨学网

嗨学网

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

原文地址是:http://www.piaodoo.com/thread-13549-1-17.html 蜜桃成熟时www.eplbx.com131www.buzc.org学习之外可赏心悦目有助更好地学习!非常好

猜你喜欢

转载自www.cnblogs.com/txdah/p/12108601.html