1 #include "opencv2/highgui.hpp"
2 #include "opencv2/imgproc.hpp"
3
4 #include <iostream>
5
6 using namespace cv;
7 using namespace std;
8
help()9 static void help()
10 {
11 cout << "This program demonstrates finding the minimum enclosing box, triangle or circle of a set\n"
12 << "of points using functions: minAreaRect() minEnclosingTriangle() minEnclosingCircle().\n"
13 << "Random points are generated and then enclosed.\n\n"
14 << "Press ESC, 'q' or 'Q' to exit and any other key to regenerate the set of points.\n\n";
15 }
16
main(int,char **)17 int main( int /*argc*/, char** /*argv*/ )
18 {
19 help();
20
21 Mat img(500, 500, CV_8UC3, Scalar::all(0));
22 RNG& rng = theRNG();
23
24 for(;;)
25 {
26 int i, count = rng.uniform(1, 101);
27 vector<Point> points;
28
29 // Generate a random set of points
30 for( i = 0; i < count; i++ )
31 {
32 Point pt;
33 pt.x = rng.uniform(img.cols/4, img.cols*3/4);
34 pt.y = rng.uniform(img.rows/4, img.rows*3/4);
35
36 points.push_back(pt);
37 }
38
39 // Find the minimum area enclosing bounding box
40 Point2f vtx[4];
41 RotatedRect box = minAreaRect(points);
42 box.points(vtx);
43
44 // Find the minimum area enclosing triangle
45 vector<Point2f> triangle;
46 minEnclosingTriangle(points, triangle);
47
48 // Find the minimum area enclosing circle
49 Point2f center;
50 float radius = 0;
51 minEnclosingCircle(points, center, radius);
52
53 img = Scalar::all(0);
54
55 // Draw the points
56 for( i = 0; i < count; i++ )
57 circle( img, points[i], 3, Scalar(0, 0, 255), FILLED, LINE_AA );
58
59 // Draw the bounding box
60 for( i = 0; i < 4; i++ )
61 line(img, vtx[i], vtx[(i+1)%4], Scalar(0, 255, 0), 1, LINE_AA);
62
63 // Draw the triangle
64 for( i = 0; i < 3; i++ )
65 line(img, triangle[i], triangle[(i+1)%3], Scalar(255, 255, 0), 1, LINE_AA);
66
67 // Draw the circle
68 circle(img, center, cvRound(radius), Scalar(0, 255, 255), 1, LINE_AA);
69
70 imshow( "Rectangle, triangle & circle", img );
71
72 char key = (char)waitKey();
73 if( key == 27 || key == 'q' || key == 'Q' ) // 'ESC'
74 break;
75 }
76
77 return 0;
78 }
79