test_houghlines.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #!/usr/bin/python
  2. '''
  3. This example illustrates how to use Hough Transform to find lines
  4. '''
  5. # Python 2/3 compatibility
  6. from __future__ import print_function
  7. import cv2 as cv
  8. import numpy as np
  9. import sys
  10. import math
  11. from tests_common import NewOpenCVTests
  12. def linesDiff(line1, line2):
  13. norm1 = cv.norm(line1 - line2, cv.NORM_L2)
  14. line3 = line1[2:4] + line1[0:2]
  15. norm2 = cv.norm(line3 - line2, cv.NORM_L2)
  16. return min(norm1, norm2)
  17. class houghlines_test(NewOpenCVTests):
  18. def test_houghlines(self):
  19. fn = "/samples/data/pic1.png"
  20. src = self.get_sample(fn)
  21. dst = cv.Canny(src, 50, 200)
  22. lines = cv.HoughLinesP(dst, 1, math.pi/180.0, 40, np.array([]), 50, 10)[:,0,:]
  23. eps = 5
  24. testLines = [
  25. #rect1
  26. [ 232, 25, 43, 25],
  27. [ 43, 129, 232, 129],
  28. [ 43, 129, 43, 25],
  29. [232, 129, 232, 25],
  30. #rect2
  31. [251, 86, 314, 183],
  32. [252, 86, 323, 40],
  33. [315, 183, 386, 137],
  34. [324, 40, 386, 136],
  35. #triangle
  36. [245, 205, 377, 205],
  37. [244, 206, 305, 278],
  38. [306, 279, 377, 205],
  39. #rect3
  40. [153, 177, 196, 177],
  41. [153, 277, 153, 179],
  42. [153, 277, 196, 277],
  43. [196, 177, 196, 277]]
  44. matches_counter = 0
  45. for i in range(len(testLines)):
  46. for j in range(len(lines)):
  47. if linesDiff(testLines[i], lines[j]) < eps:
  48. matches_counter += 1
  49. self.assertGreater(float(matches_counter) / len(testLines), .7)
  50. lines_acc = cv.HoughLinesWithAccumulator(dst, rho=1, theta=np.pi / 180, threshold=150, srn=0, stn=0)
  51. self.assertEqual(lines_acc[0,0,2], 192.0)
  52. self.assertEqual(lines_acc[1,0,2], 187.0)
  53. if __name__ == '__main__':
  54. NewOpenCVTests.bootstrap()