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