Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Tetragramm
GitHub Repository: Tetragramm/opencv
Path: blob/master/samples/python/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
Usage
11
-----
12
fitline.py
13
14
Switch through different M-estimator functions and see,
15
how well the robust functions fit the line even
16
in case of ~50% of outliers.
17
18
Keys
19
----
20
SPACE - generate random points
21
f - change distance function
22
ESC - exit
23
'''
24
25
# Python 2/3 compatibility
26
from __future__ import print_function
27
import sys
28
PY3 = sys.version_info[0] == 3
29
30
import numpy as np
31
import cv2 as cv
32
33
# built-in modules
34
import itertools as it
35
36
# local modules
37
from common import draw_str
38
39
40
w, h = 512, 256
41
42
def toint(p):
43
return tuple(map(int, p))
44
45
def sample_line(p1, p2, n, noise=0.0):
46
p1 = np.float32(p1)
47
t = np.random.rand(n,1)
48
return p1 + (p2-p1)*t + np.random.normal(size=(n, 2))*noise
49
50
dist_func_names = it.cycle('DIST_L2 DIST_L1 DIST_L12 DIST_FAIR DIST_WELSCH DIST_HUBER'.split())
51
52
if PY3:
53
cur_func_name = next(dist_func_names)
54
else:
55
cur_func_name = dist_func_names.next()
56
57
def update(_=None):
58
noise = cv.getTrackbarPos('noise', 'fit line')
59
n = cv.getTrackbarPos('point n', 'fit line')
60
r = cv.getTrackbarPos('outlier %', 'fit line') / 100.0
61
outn = int(n*r)
62
63
p0, p1 = (90, 80), (w-90, h-80)
64
img = np.zeros((h, w, 3), np.uint8)
65
cv.line(img, toint(p0), toint(p1), (0, 255, 0))
66
67
if n > 0:
68
line_points = sample_line(p0, p1, n-outn, noise)
69
outliers = np.random.rand(outn, 2) * (w, h)
70
points = np.vstack([line_points, outliers])
71
for p in line_points:
72
cv.circle(img, toint(p), 2, (255, 255, 255), -1)
73
for p in outliers:
74
cv.circle(img, toint(p), 2, (64, 64, 255), -1)
75
func = getattr(cv, cur_func_name)
76
vx, vy, cx, cy = cv.fitLine(np.float32(points), func, 0, 0.01, 0.01)
77
cv.line(img, (int(cx-vx*w), int(cy-vy*w)), (int(cx+vx*w), int(cy+vy*w)), (0, 0, 255))
78
79
draw_str(img, (20, 20), cur_func_name)
80
cv.imshow('fit line', img)
81
82
if __name__ == '__main__':
83
print(__doc__)
84
85
cv.namedWindow('fit line')
86
cv.createTrackbar('noise', 'fit line', 3, 50, update)
87
cv.createTrackbar('point n', 'fit line', 100, 500, update)
88
cv.createTrackbar('outlier %', 'fit line', 30, 100, update)
89
while True:
90
update()
91
ch = cv.waitKey(0)
92
if ch == ord('f'):
93
if PY3:
94
cur_func_name = next(dist_func_names)
95
else:
96
cur_func_name = dist_func_names.next()
97
if ch == 27:
98
break
99
100