霍夫直线检测python_python+opencv实现霍夫变换检测直线的方法

# -*- coding: utf-8 -*-

import cv2

#两个回调函数

def HoughLinesP(minLineLength):

global minLINELENGTH

minLINELENGTH = minLineLength + 1

print "minLINELENGTH:",minLineLength + 1

tempIamge = scr.copy()

lines = cv2.HoughLinesP( edges, 1, cv2.cv.CV_PI/180, minLINELENGTH, 0 )

for x1,y1,x2,y2 in lines[0]:

cv2.line(tempIamge,(x1,y1),(x2,y2),(0,255,0),1)

cv2.imshow(window_name,tempIamge)

#临时变量

minLineLength = 20

#全局变量

minLINELENGTH = 20

max_value = 100

window_name = "HoughLines Demo"

trackbar_value = "minLineLength"

#读入图片,模式为灰度图,创建窗口

scr = cv2.imread("G:\\homework\\building.bmp")

gray = cv2.cvtColor(scr,cv2.COLOR_BGR2GRAY)

img = cv2.GaussianBlur(gray,(3,3),0)

edges = cv2.Canny(img, 50, 150, apertureSize = 3)

cv2.namedWindow(window_name)

#创建滑动条

cv2.createTrackbar( trackbar_value, window_name, \

minLineLength, max_value, HoughLinesP)

#初始化

HoughLinesP(20)

if cv2.waitKey(0) == 27:

cv2.destroyAllWindows()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
霍夫直线检测(Hough Line Transform)是一种经典的图像处理算法,用于检测图像中的直线。下面是一个使用 Python 实现的简单示例代码,不调用 OpenCV 库: ```python import numpy as np import math def hough_lines(image): # 定义参数 theta_res = 1 # 角度步长 rho_res = 1 # 距离步长 threshold = 50 # 阈值 theta_num = int(180 / theta_res) rows, cols = image.shape # 计算图像的最大距离 max_distance = int(math.sqrt(rows**2 + cols**2)) # 构造累加器矩阵 accumulator = np.zeros((int(max_distance / rho_res), theta_num), dtype=np.uint8) # 遍历图像中所有非零像素点 for r in range(rows): for c in range(cols): if image[r][c] > 0: for t in range(theta_num): theta = t * theta_res * math.pi / 180.0 rho = int((c * math.cos(theta) + r * math.sin(theta)) / rho_res + 0.5) # 累加器加一 accumulator[rho][t] += 1 # 获取直线的参数 lines = [] for r in range(int(max_distance / rho_res)): for t in range(theta_num): if accumulator[r][t] > threshold: a = math.cos(t * theta_res * math.pi / 180.0) b = math.sin(t * theta_res * math.pi / 180.0) x0 = a * r * rho_res y0 = b * r * rho_res x1 = int(x0 + 1000 * (-b)) y1 = int(y0 + 1000 * (a)) x2 = int(x0 - 1000 * (-b)) y2 = int(y0 - 1000 * (a)) lines.append((x1, y1, x2, y2)) return lines ``` 该代码实现了一个简单的霍夫直线检测算法,输入参数为二值化图像,返回值为检测到的直线参数。注意,该代码实现霍夫直线检测算法可能存在一定的性能问题,仅用于学习和实验之用。如果需要高性能和高精度的霍夫直线检测算法,建议使用 OpenCV 库提供的相关函数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值