1#!/usr/bin/python 2''' 3This example illustrates how to use Hough Transform to find lines 4Usage: ./houghlines.py [<image_name>] 5image argument defaults to ../data/pic1.png 6''' 7import cv2 8import numpy as np 9import sys 10import math 11 12try: 13 fn = sys.argv[1] 14except: 15 fn = "../data/pic1.png" 16print __doc__ 17src = cv2.imread(fn) 18dst = cv2.Canny(src, 50, 200) 19cdst = cv2.cvtColor(dst, cv2.COLOR_GRAY2BGR) 20 21if True: # HoughLinesP 22 lines = cv2.HoughLinesP(dst, 1, math.pi/180.0, 40, np.array([]), 50, 10) 23 a,b,c = lines.shape 24 for i in range(a): 25 cv2.line(cdst, (lines[i][0][0], lines[i][0][1]), (lines[i][0][2], lines[i][0][3]), (0, 0, 255), 3, cv2.LINE_AA) 26 27else: # HoughLines 28 lines = cv2.HoughLines(dst, 1, math.pi/180.0, 50, np.array([]), 0, 0) 29 a,b,c = lines.shape 30 for i in range(a): 31 rho = lines[i][0][0] 32 theta = lines[i][0][1] 33 a = math.cos(theta) 34 b = math.sin(theta) 35 x0, y0 = a*rho, b*rho 36 pt1 = ( int(x0+1000*(-b)), int(y0+1000*(a)) ) 37 pt2 = ( int(x0-1000*(-b)), int(y0-1000*(a)) ) 38 cv2.line(cdst, pt1, pt2, (0, 0, 255), 3, cv2.LINE_AA) 39 40 41cv2.imshow("source", src) 42cv2.imshow("detected lines", cdst) 43cv2.waitKey(0) 44