Skip to content

Commit 26c0a43

Browse files
committed
example 19-04
1 parent a4b2cc9 commit 26c0a43

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

example_19-04.cpp

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
// Example 19-4. Two-dimensional line fitting
2+
#include <opencv2/opencv.hpp>
3+
#include <iostream>
4+
#include <math.h>
5+
6+
using namespace std;
7+
8+
void help(char **argv) {
9+
cout << "\nExample 19-04, two dimensional line fitting"
10+
<< "\nCall"
11+
<< "\n" << argv[0] << "\n"
12+
<< "\n 'q', 'Q' or ESC to quit"
13+
<< "\n" << endl;
14+
}
15+
16+
int main(int argc, char **argv) {
17+
cv::Mat img(500, 500, CV_8UC3);
18+
cv::RNG rng(-1);
19+
help(argv);
20+
for (;;) {
21+
char key;
22+
int i, count = rng.uniform(0, 100) + 3, outliers = count / 5;
23+
float a = (float)rng.uniform(0., 200.);
24+
float b = (float)rng.uniform(0., 40.);
25+
float angle = (float)rng.uniform(0., CV_PI);
26+
float cos_a = cos(angle), sin_a = sin(angle);
27+
cv::Point pt1, pt2;
28+
vector<cv::Point> points(count);
29+
cv::Vec4f line;
30+
float d, t;
31+
b = MIN(a * 0.3f, b);
32+
33+
// generate some points that are close to the line
34+
for (i = 0; i < count - outliers; i++) {
35+
float x = (float)rng.uniform(-1., 1.) * a;
36+
float y = (float)rng.uniform(-1., 1.) * b;
37+
points[i].x = cvRound(x * cos_a - y * sin_a + img.cols / 2);
38+
points[i].y = cvRound(x * sin_a + y * cos_a + img.rows / 2);
39+
}
40+
41+
// generate outlier points
42+
for (; i < count; i++) {
43+
points[i].x = rng.uniform(0, img.cols);
44+
points[i].y = rng.uniform(0, img.rows);
45+
}
46+
47+
// find the optimal line
48+
cv::fitLine(points, line, cv::DIST_L1, 1, 0.001, 0.001);
49+
50+
// draw the points
51+
img = cv::Scalar::all(0);
52+
for (i = 0; i < count; i++)
53+
cv::circle(img, points[i], 2,
54+
i < count - outliers ? cv::Scalar(0, 0, 255)
55+
: cv::Scalar(0, 255, 255),
56+
cv::FILLED, CV_AA, 0);
57+
58+
// ... and the long enough line to cross the whole image
59+
d = sqrt((double)line[0] * line[0] + (double)line[1] * line[1]);
60+
line[0] /= d;
61+
line[1] /= d;
62+
t = (float)(img.cols + img.rows);
63+
pt1.x = cvRound(line[2] - line[0] * t);
64+
pt1.y = cvRound(line[3] - line[1] * t);
65+
pt2.x = cvRound(line[2] + line[0] * t);
66+
pt2.y = cvRound(line[3] + line[1] * t);
67+
cv::line(img, pt1, pt2, cv::Scalar(0, 255, 0), 3, CV_AA, 0);
68+
cv::imshow("Fit Line", img);
69+
key = (char)cv::waitKey(0);
70+
if (key == 27 || key == 'q' || key == 'Q') // 'ESC'
71+
break;
72+
}
73+
return 0;
74+
}

0 commit comments

Comments
 (0)