Path: blob/master/modules/python/test/test_fitline.py
16337 views
#!/usr/bin/env python12'''3Robust line fitting.4==================56Example of using cv.fitLine function for fitting line7to points in presence of outliers.89Switch through different M-estimator functions and see,10how well the robust functions fit the line even11in case of ~50% of outliers.1213'''1415# Python 2/3 compatibility16from __future__ import print_function17import sys18PY3 = sys.version_info[0] == 31920import numpy as np21import cv2 as cv2223from tests_common import NewOpenCVTests2425w, h = 512, 2562627def toint(p):28return tuple(map(int, p))2930def sample_line(p1, p2, n, noise=0.0):31np.random.seed(10)32p1 = np.float32(p1)33t = np.random.rand(n,1)34return p1 + (p2-p1)*t + np.random.normal(size=(n, 2))*noise3536dist_func_names = ['DIST_L2', 'DIST_L1', 'DIST_L12', 'DIST_FAIR', 'DIST_WELSCH', 'DIST_HUBER']3738class fitline_test(NewOpenCVTests):3940def test_fitline(self):4142noise = 543n = 20044r = 5 / 100.045outn = int(n*r)4647p0, p1 = (90, 80), (w-90, h-80)48line_points = sample_line(p0, p1, n-outn, noise)49outliers = np.random.rand(outn, 2) * (w, h)50points = np.vstack([line_points, outliers])5152lines = []5354for name in dist_func_names:55func = getattr(cv, name)56vx, vy, cx, cy = cv.fitLine(np.float32(points), func, 0, 0.01, 0.01)57line = [float(vx), float(vy), float(cx), float(cy)]58lines.append(line)5960eps = 0.056162refVec = (np.float32(p1) - p0) / cv.norm(np.float32(p1) - p0)6364for i in range(len(lines)):65self.assertLessEqual(cv.norm(refVec - lines[i][0:2], cv.NORM_L2), eps)666768if __name__ == '__main__':69NewOpenCVTests.bootstrap()707172