opencv/samples/cpp/minarea.cpp

79 lines
2.2 KiB
C++
Raw Normal View History

2016-02-15 21:37:29 +08:00
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
2011-07-30 19:59:09 +08:00
2010-12-04 16:29:18 +08:00
#include <iostream>
2011-07-30 19:59:09 +08:00
2010-11-28 07:15:16 +08:00
using namespace cv;
2010-12-04 16:29:18 +08:00
using namespace std;
2012-06-08 01:21:29 +08:00
static void help()
2010-12-04 16:29:18 +08:00
{
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"
2017-10-08 18:22:13 +08:00
<< "Press ESC, 'q' or 'Q' to exit and any other key to regenerate the set of points.\n\n";
2010-12-04 16:29:18 +08:00
}
2010-12-21 19:37:08 +08:00
int main( int /*argc*/, char** /*argv*/ )
2010-11-28 07:15:16 +08:00
{
2010-12-04 16:29:18 +08:00
help();
2011-07-30 19:59:09 +08:00
2018-10-31 20:48:56 +08:00
Mat img(500, 500, CV_8UC3, Scalar::all(0));
2012-06-08 01:21:29 +08:00
RNG& rng = theRNG();
2011-07-30 19:59:09 +08:00
2010-11-28 07:15:16 +08:00
for(;;)
{
int i, count = rng.uniform(1, 101);
vector<Point> points;
// Generate a random set of points
2010-11-28 07:15:16 +08:00
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);
2012-06-08 01:21:29 +08:00
2010-11-28 07:15:16 +08:00
points.push_back(pt);
}
2012-06-08 01:21:29 +08:00
// Find the minimum area enclosing bounding box
2017-10-08 18:22:13 +08:00
Point2f vtx[4];
RotatedRect box = minAreaRect(points);
box.points(vtx);
2011-07-30 19:59:09 +08:00
// Find the minimum area enclosing triangle
2017-10-11 22:52:23 +08:00
vector<Point2f> triangle;
minEnclosingTriangle(points, triangle);
// Find the minimum area enclosing circle
2017-10-08 18:22:13 +08:00
Point2f center;
2010-11-28 07:15:16 +08:00
float radius = 0;
2017-10-08 18:22:13 +08:00
minEnclosingCircle(points, center, radius);
2012-06-08 01:21:29 +08:00
2010-11-28 07:15:16 +08:00
img = Scalar::all(0);
// Draw the points
2010-11-28 07:15:16 +08:00
for( i = 0; i < count; i++ )
circle( img, points[i], 3, Scalar(0, 0, 255), FILLED, LINE_AA );
2010-11-28 07:15:16 +08:00
// Draw the bounding box
2010-11-28 07:15:16 +08:00
for( i = 0; i < 4; i++ )
line(img, vtx[i], vtx[(i+1)%4], Scalar(0, 255, 0), 1, LINE_AA);
2012-06-08 01:21:29 +08:00
// 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
circle(img, center, cvRound(radius), Scalar(0, 255, 255), 1, LINE_AA);
2010-11-28 07:15:16 +08:00
imshow( "Rectangle, triangle & circle", img );
2010-11-28 07:15:16 +08:00
char key = (char)waitKey();
2010-11-28 07:15:16 +08:00
if( key == 27 || key == 'q' || key == 'Q' ) // 'ESC'
break;
}
2011-07-30 19:59:09 +08:00
2010-11-28 07:15:16 +08:00
return 0;
}