minarea.cpp 2.2 KB

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