OpenCV  5.0.0alpha
Open Source Computer Vision
Loading...
Searching...
No Matches
samples/python/snippets/fitline.py

An example for fitting line in python

1#!/usr/bin/env python
2
3'''
4Robust line fitting.
5==================
6
7Example of using cv.fitLine function for fitting line
8to points in presence of outliers.
9
10Usage
11-----
12fitline.py
13
14Switch through different M-estimator functions and see,
15how well the robust functions fit the line even
16in case of ~50% of outliers.
17
18Keys
19----
20SPACE - generate random points
21f - change distance function
22ESC - exit
23'''
24
25import numpy as np
26import cv2 as cv
27
28# built-in modules
29import itertools as it
30
31# local modules
32from common import draw_str
33
34
35w, h = 512, 256
36
37def toint(p):
38 return tuple(map(int, p))
39
40def sample_line(p1, p2, n, noise=0.0):
41 p1 = np.float32(p1)
42 t = np.random.rand(n,1)
43 return p1 + (p2-p1)*t + np.random.normal(size=(n, 2))*noise
44
45dist_func_names = it.cycle('DIST_L2 DIST_L1 DIST_L12 DIST_FAIR DIST_WELSCH DIST_HUBER'.split())
46
47cur_func_name = next(dist_func_names)
48
49def update(_=None):
50 noise = cv.getTrackbarPos('noise', 'fit line')
51 n = cv.getTrackbarPos('point n', 'fit line')
52 r = cv.getTrackbarPos('outlier %', 'fit line') / 100.0
53 outn = int(n*r)
54
55 p0, p1 = (90, 80), (w-90, h-80)
56 img = np.zeros((h, w, 3), np.uint8)
57 cv.line(img, toint(p0), toint(p1), (0, 255, 0))
58
59 if n > 0:
60 line_points = sample_line(p0, p1, n-outn, noise)
61 outliers = np.random.rand(outn, 2) * (w, h)
62 points = np.vstack([line_points, outliers])
63 for p in line_points:
64 cv.circle(img, toint(p), 2, (255, 255, 255), -1)
65 for p in outliers:
66 cv.circle(img, toint(p), 2, (64, 64, 255), -1)
67 func = getattr(cv, cur_func_name)
68 vx, vy, cx, cy = cv.fitLine(np.float32(points), func, 0, 0.01, 0.01)
69 cv.line(img, (int(cx-vx*w), int(cy-vy*w)), (int(cx+vx*w), int(cy+vy*w)), (0, 0, 255))
70
71 draw_str(img, (20, 20), cur_func_name)
72 cv.imshow('fit line', img)
73
74def main():
75 cv.namedWindow('fit line')
76 cv.createTrackbar('noise', 'fit line', 3, 50, update)
77 cv.createTrackbar('point n', 'fit line', 100, 500, update)
78 cv.createTrackbar('outlier %', 'fit line', 30, 100, update)
79 while True:
80 update()
81 ch = cv.waitKey(0)
82 if ch == ord('f'):
83 global cur_func_name
84 cur_func_name = next(dist_func_names)
85 if ch == 27:
86 break
87
88 print('Done')
89
90
91if __name__ == '__main__':
92 print(__doc__)
93 main()
int getTrackbarPos(const String &trackbarname, const String &winname)
Returns the trackbar position.
void imshow(const String &winname, InputArray mat)
Displays an image in the specified window.
int waitKey(int delay=0)
Waits for a pressed key.
void namedWindow(const String &winname, int flags=WINDOW_AUTOSIZE)
Creates a window.
void destroyAllWindows()
Destroys all of the HighGUI windows.
int createTrackbar(const String &trackbarname, const String &winname, int *value, int count, TrackbarCallback onChange=0, void *userdata=0)
Creates a trackbar and attaches it to the specified window.
void line(InputOutputArray img, Point pt1, Point pt2, const Scalar &color, int thickness=1, int lineType=LINE_8, int shift=0)
Draws a line segment connecting two points.
void circle(InputOutputArray img, Point center, int radius, const Scalar &color, int thickness=1, int lineType=LINE_8, int shift=0)
Draws a circle.
void fitLine(InputArray points, OutputArray line, int distType, double param, double reps, double aeps)
Fits a line to a 2D or 3D point set.
int main(int argc, char *argv[])
Definition highgui_qt.cpp:3