hough_lines.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. """
  2. @file hough_lines.py
  3. @brief This program demonstrates line finding with the Hough transform
  4. """
  5. import sys
  6. import math
  7. import cv2 as cv
  8. import numpy as np
  9. def main(argv):
  10. ## [load]
  11. default_file = 'sudoku.png'
  12. filename = argv[0] if len(argv) > 0 else default_file
  13. # Loads an image
  14. src = cv.imread(cv.samples.findFile(filename), cv.IMREAD_GRAYSCALE)
  15. # Check if image is loaded fine
  16. if src is None:
  17. print ('Error opening image!')
  18. print ('Usage: hough_lines.py [image_name -- default ' + default_file + '] \n')
  19. return -1
  20. ## [load]
  21. ## [edge_detection]
  22. # Edge detection
  23. dst = cv.Canny(src, 50, 200, None, 3)
  24. ## [edge_detection]
  25. # Copy edges to the images that will display the results in BGR
  26. cdst = cv.cvtColor(dst, cv.COLOR_GRAY2BGR)
  27. cdstP = np.copy(cdst)
  28. ## [hough_lines]
  29. # Standard Hough Line Transform
  30. lines = cv.HoughLines(dst, 1, np.pi / 180, 150, None, 0, 0)
  31. ## [hough_lines]
  32. ## [draw_lines]
  33. # Draw the lines
  34. if lines is not None:
  35. for i in range(0, len(lines)):
  36. rho = lines[i][0][0]
  37. theta = lines[i][0][1]
  38. a = math.cos(theta)
  39. b = math.sin(theta)
  40. x0 = a * rho
  41. y0 = b * rho
  42. pt1 = (int(x0 + 1000*(-b)), int(y0 + 1000*(a)))
  43. pt2 = (int(x0 - 1000*(-b)), int(y0 - 1000*(a)))
  44. cv.line(cdst, pt1, pt2, (0,0,255), 3, cv.LINE_AA)
  45. ## [draw_lines]
  46. ## [hough_lines_p]
  47. # Probabilistic Line Transform
  48. linesP = cv.HoughLinesP(dst, 1, np.pi / 180, 50, None, 50, 10)
  49. ## [hough_lines_p]
  50. ## [draw_lines_p]
  51. # Draw the lines
  52. if linesP is not None:
  53. for i in range(0, len(linesP)):
  54. l = linesP[i][0]
  55. cv.line(cdstP, (l[0], l[1]), (l[2], l[3]), (0,0,255), 3, cv.LINE_AA)
  56. ## [draw_lines_p]
  57. ## [imshow]
  58. # Show results
  59. cv.imshow("Source", src)
  60. cv.imshow("Detected Lines (in red) - Standard Hough Line Transform", cdst)
  61. cv.imshow("Detected Lines (in red) - Probabilistic Line Transform", cdstP)
  62. ## [imshow]
  63. ## [exit]
  64. # Wait and Exit
  65. cv.waitKey()
  66. return 0
  67. ## [exit]
  68. if __name__ == "__main__":
  69. main(sys.argv[1:])