houghlines.py 1.4 KB

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