# -*- coding:utf-8 -*-
import cv2
import numpy as np
# Step1. 读入图像
src = cv2.imread('images/roof.jpg')
gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
# Step2. 边缘检测
edges = cv2.Canny(gray, 50, 150)
dst1 = cv2.cvtColor(edges, cv2.COLOR_GRAY2BGR)
dst2 = cv2.cvtColor(edges, cv2.COLOR_GRAY2BGR)
# Step3. Hough直线检测
minLineLength = 100
maxLineGap = 10
lines1 = cv2.HoughLines(edges, 1, np.pi/180.0, 200, minLineLength, maxLineGap)
if lines1 is not None:
_lines1 = lines1[:, 0, :] # 提取为二维
for rho,theta in _lines1[:]:
a = np.cos(theta)
b = np.sin(theta)
x0, y0 = a * rho, b * rho
pt1 = ( int(x0 + 1000 * (-b)), int(y0 + 1000 * (a)) )
pt2 = ( int(x0 - 1000 * (-b)), int(y0 - 1000 * (a)) )
cv2.line(dst1, pt1, pt2, (0, 255, 0), 2)
cv2.imshow("hough lines", dst1)
# Step4. HoughLineP直线检测
minLineLength = 50
maxLineGap = 10
lines2 = cv2.HoughLinesP(edges, 1, np.pi/180.0, 50, minLineLength, maxLineGap)
if lines2 is not None:
_lines2 = lines2[:,0,:]
for x1,y1,x2,y2 in _lines2[:]:
cv2.line(dst2,(x1, y1), (x2, y2), (0,255,0), 2)
cv2.imshow("hough lines P", dst2)
cv2.waitKey(0)