1 #!/usr/bin/python 2 ''' 3 This example illustrates how to use Hough Transform to find lines 4 Usage: ./houghlines.py [<image_name>] 5 image argument defaults to ../data/pic1.png 6 ''' 7 import cv2 8 import numpy as np 9 import sys 10 import math 11 12 try: 13 fn = sys.argv[1] 14 except: 15 fn = "../data/pic1.png" 16 print __doc__ 17 src = cv2.imread(fn) 18 dst = cv2.Canny(src, 50, 200) 19 cdst = cv2.cvtColor(dst, cv2.COLOR_GRAY2BGR) 20 21 if 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 27 else: # 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 41 cv2.imshow("source", src) 42 cv2.imshow("detected lines", cdst) 43 cv2.waitKey(0) 44