minarea.cpp 1.63 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
    cout << "This program demonstrates finding the minimum enclosing box or circle of a set\n"
12 13 14 15 16
            "of points using functions: minAreaRect() minEnclosingCircle().\n"
            "Random points are generated and then enclosed.\n"
            "Call:\n"
            "./minarea\n"
            "Using OpenCV version %s\n" << CV_VERSION << "\n" << endl;
Gary Bradski's avatar
Gary Bradski committed
17 18
}

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

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

26 27 28 29 30 31 32 33 34
    for(;;)
    {
        int i, count = rng.uniform(1, 101);
        vector<Point> points;
        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
        RotatedRect box = minAreaRect(Mat(points));
40

41 42 43 44
        Point2f center, vtx[4];
        float radius = 0;
        minEnclosingCircle(Mat(points), center, radius);
        box.points(vtx);
45

46 47 48 49 50 51
        img = Scalar::all(0);
        for( i = 0; i < count; i++ )
            circle( img, points[i], 3, Scalar(0, 0, 255), CV_FILLED, CV_AA );

        for( i = 0; i < 4; i++ )
            line(img, vtx[i], vtx[(i+1)%4], Scalar(0, 255, 0), 1, CV_AA);
52 53

        circle(img, center, cvRound(radius), Scalar(0, 255, 255), 1, CV_AA);
54 55 56 57 58 59 60

        imshow( "rect & circle", img );

        char key = (char)cvWaitKey();
        if( key == 27 || key == 'q' || key == 'Q' ) // 'ESC'
            break;
    }
61

62 63
    return 0;
}