minarea.cpp 2.28 KB
Newer Older
1 2
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/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 14 15 16 17
    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"
         << "Press ESC, 'q' or 'Q' to exit and any other key to regenerate the set of points.\n\n"
         << "Call:\n"
         << "./minarea\n"
         << "Using OpenCV v" << CV_VERSION << "\n" << endl;
Gary Bradski's avatar
Gary Bradski committed
18 19
}

20
int main( int /*argc*/, char** /*argv*/ )
21
{
Gary Bradski's avatar
Gary Bradski committed
22
    help();
23 24

    Mat img(500, 500, CV_8UC3);
25
    RNG& rng = theRNG();
26

27 28 29 30
    for(;;)
    {
        int i, count = rng.uniform(1, 101);
        vector<Point> points;
31 32

        // Generate a random set of points
33 34 35 36 37
        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);
38

39 40
            points.push_back(pt);
        }
41

42
        // Find the minimum area enclosing bounding box
43
        RotatedRect box = minAreaRect(Mat(points));
44

45 46 47
        // Find the minimum area enclosing triangle
        vector<Point2f> triangle;

48
        minEnclosingTriangle(points, triangle);
49 50

        // Find the minimum area enclosing circle
51 52 53 54
        Point2f center, vtx[4];
        float radius = 0;
        minEnclosingCircle(Mat(points), center, radius);
        box.points(vtx);
55

56
        img = Scalar::all(0);
57 58

        // Draw the points
59
        for( i = 0; i < count; i++ )
60
            circle( img, points[i], 3, Scalar(0, 0, 255), FILLED, LINE_AA );
61

62
        // Draw the bounding box
63
        for( i = 0; i < 4; i++ )
64
            line(img, vtx[i], vtx[(i+1)%4], Scalar(0, 255, 0), 1, LINE_AA);
65

66 67 68 69 70
        // 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
71
        circle(img, center, cvRound(radius), Scalar(0, 255, 255), 1, LINE_AA);
72

73
        imshow( "Rectangle, triangle & circle", img );
74

75
        char key = (char)waitKey();
76 77 78
        if( key == 27 || key == 'q' || key == 'Q' ) // 'ESC'
            break;
    }
79

80 81
    return 0;
}