test_fitline.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #!/usr/bin/env python
  2. '''
  3. Robust line fitting.
  4. ==================
  5. Example of using cv.fitLine function for fitting line
  6. to points in presence of outliers.
  7. Switch through different M-estimator functions and see,
  8. how well the robust functions fit the line even
  9. in case of ~50% of outliers.
  10. '''
  11. # Python 2/3 compatibility
  12. from __future__ import print_function
  13. import sys
  14. PY3 = sys.version_info[0] == 3
  15. import numpy as np
  16. import cv2 as cv
  17. from tests_common import NewOpenCVTests
  18. w, h = 512, 256
  19. def toint(p):
  20. return tuple(map(int, p))
  21. def sample_line(p1, p2, n, noise=0.0):
  22. np.random.seed(10)
  23. p1 = np.float32(p1)
  24. t = np.random.rand(n,1)
  25. return p1 + (p2-p1)*t + np.random.normal(size=(n, 2))*noise
  26. dist_func_names = ['DIST_L2', 'DIST_L1', 'DIST_L12', 'DIST_FAIR', 'DIST_WELSCH', 'DIST_HUBER']
  27. class fitline_test(NewOpenCVTests):
  28. def test_fitline(self):
  29. noise = 5
  30. n = 200
  31. r = 5 / 100.0
  32. outn = int(n*r)
  33. p0, p1 = (90, 80), (w-90, h-80)
  34. line_points = sample_line(p0, p1, n-outn, noise)
  35. outliers = np.random.rand(outn, 2) * (w, h)
  36. points = np.vstack([line_points, outliers])
  37. lines = []
  38. for name in dist_func_names:
  39. func = getattr(cv, name)
  40. vx, vy, cx, cy = cv.fitLine(np.float32(points), func, 0, 0.01, 0.01)
  41. line = [float(vx), float(vy), float(cx), float(cy)]
  42. lines.append(line)
  43. eps = 0.05
  44. refVec = (np.float32(p1) - p0) / cv.norm(np.float32(p1) - p0)
  45. for i in range(len(lines)):
  46. self.assertLessEqual(cv.norm(refVec - lines[i][0:2], cv.NORM_L2), eps)
  47. if __name__ == '__main__':
  48. NewOpenCVTests.bootstrap()