minarea.cpp 2.16 KB
Newer Older
1 2
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
3

Gary Bradski's avatar
Gary Bradski committed
4
#include <iostream>
5

6
using namespace cv;
Gary Bradski's avatar
Gary Bradski committed
7 8
using namespace std;

9
static void help()
Gary Bradski's avatar
Gary Bradski committed
10
{
11 12 13
    cout << "This program demonstrates finding the minimum enclosing box, triangle or circle of a set\n"
         << "of points using functions: minAreaRect() minEnclosingTriangle() minEnclosingCircle().\n"
         << "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";
Gary Bradski's avatar
Gary Bradski committed
15 16
}

17
int main( int /*argc*/, char** /*argv*/ )
18
{
Gary Bradski's avatar
Gary Bradski committed
19
    help();
20 21

    Mat img(500, 500, CV_8UC3);
22
    RNG& rng = theRNG();
23

24 25 26 27
    for(;;)
    {
        int i, count = rng.uniform(1, 101);
        vector<Point> points;
28 29

        // Generate a random set of points
30 31 32 33 34
        for( i = 0; i < count; i++ )
        {
            Point pt;
            pt.x = rng.uniform(img.cols/4, img.cols*3/4);
            pt.y = rng.uniform(img.rows/4, img.rows*3/4);
35

36 37
            points.push_back(pt);
        }
38

39
        // Find the minimum area enclosing bounding box
40 41 42
        Point2f vtx[4];
        RotatedRect box = minAreaRect(points);
        box.points(vtx);
43

44
        // Find the minimum area enclosing triangle
Suleyman TURKMEN's avatar
Suleyman TURKMEN committed
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 64 65 66 67
        // Draw the triangle
        for( i = 0; i < 3; i++ )
            line(img, triangle[i], triangle[(i+1)%3], Scalar(255, 255, 0), 1, LINE_AA);

        // 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 74 75
        if( key == 27 || key == 'q' || key == 'Q' ) // 'ESC'
            break;
    }
76

77 78
    return 0;
}