houghlines.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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 pic1.png
  7. '''
  8. # Python 2/3 compatibility
  9. from __future__ import print_function
  10. import cv2 as cv
  11. import numpy as np
  12. import sys
  13. import math
  14. def main():
  15. try:
  16. fn = sys.argv[1]
  17. except IndexError:
  18. fn = 'pic1.png'
  19. src = cv.imread(cv.samples.findFile(fn))
  20. dst = cv.Canny(src, 50, 200)
  21. cdst = cv.cvtColor(dst, cv.COLOR_GRAY2BGR)
  22. if True: # HoughLinesP
  23. lines = cv.HoughLinesP(dst, 1, math.pi/180.0, 40, np.array([]), 50, 10)
  24. a, b, _c = lines.shape
  25. for i in range(a):
  26. cv.line(cdst, (lines[i][0][0], lines[i][0][1]), (lines[i][0][2], lines[i][0][3]), (0, 0, 255), 3, cv.LINE_AA)
  27. else: # HoughLines
  28. lines = cv.HoughLines(dst, 1, math.pi/180.0, 50, np.array([]), 0, 0)
  29. if lines is not None:
  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. cv.line(cdst, pt1, pt2, (0, 0, 255), 3, cv.LINE_AA)
  40. cv.imshow("detected lines", cdst)
  41. cv.imshow("source", src)
  42. cv.waitKey(0)
  43. print('Done')
  44. if __name__ == '__main__':
  45. print(__doc__)
  46. main()
  47. cv.destroyAllWindows()