squares.cpp 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. // The "Square Detector" program.
  2. // It loads several images sequentially and tries to find squares in
  3. // each image
  4. #include "opencv2/core.hpp"
  5. #include "opencv2/imgproc.hpp"
  6. #include "opencv2/imgcodecs.hpp"
  7. #include "opencv2/highgui.hpp"
  8. #include <iostream>
  9. using namespace cv;
  10. using namespace std;
  11. static void help(const char* programName)
  12. {
  13. cout <<
  14. "\nA program using pyramid scaling, Canny, contours and contour simplification\n"
  15. "to find squares in a list of images (pic1-6.png)\n"
  16. "Returns sequence of squares detected on the image.\n"
  17. "Call:\n"
  18. "./" << programName << " [file_name (optional)]\n"
  19. "Using OpenCV version " << CV_VERSION << "\n" << endl;
  20. }
  21. int thresh = 50, N = 11;
  22. const char* wndname = "Square Detection Demo";
  23. // helper function:
  24. // finds a cosine of angle between vectors
  25. // from pt0->pt1 and from pt0->pt2
  26. static double angle( Point pt1, Point pt2, Point pt0 )
  27. {
  28. double dx1 = pt1.x - pt0.x;
  29. double dy1 = pt1.y - pt0.y;
  30. double dx2 = pt2.x - pt0.x;
  31. double dy2 = pt2.y - pt0.y;
  32. return (dx1*dx2 + dy1*dy2)/sqrt((dx1*dx1 + dy1*dy1)*(dx2*dx2 + dy2*dy2) + 1e-10);
  33. }
  34. // returns sequence of squares detected on the image.
  35. static void findSquares( const Mat& image, vector<vector<Point> >& squares )
  36. {
  37. squares.clear();
  38. Mat pyr, timg, gray0(image.size(), CV_8U), gray;
  39. // down-scale and upscale the image to filter out the noise
  40. pyrDown(image, pyr, Size(image.cols/2, image.rows/2));
  41. pyrUp(pyr, timg, image.size());
  42. vector<vector<Point> > contours;
  43. // find squares in every color plane of the image
  44. for( int c = 0; c < 3; c++ )
  45. {
  46. int ch[] = {c, 0};
  47. mixChannels(&timg, 1, &gray0, 1, ch, 1);
  48. // try several threshold levels
  49. for( int l = 0; l < N; l++ )
  50. {
  51. // hack: use Canny instead of zero threshold level.
  52. // Canny helps to catch squares with gradient shading
  53. if( l == 0 )
  54. {
  55. // apply Canny. Take the upper threshold from slider
  56. // and set the lower to 0 (which forces edges merging)
  57. Canny(gray0, gray, 0, thresh, 5);
  58. // dilate canny output to remove potential
  59. // holes between edge segments
  60. dilate(gray, gray, Mat(), Point(-1,-1));
  61. }
  62. else
  63. {
  64. // apply threshold if l!=0:
  65. // tgray(x,y) = gray(x,y) < (l+1)*255/N ? 255 : 0
  66. gray = gray0 >= (l+1)*255/N;
  67. }
  68. // find contours and store them all as a list
  69. findContours(gray, contours, RETR_LIST, CHAIN_APPROX_SIMPLE);
  70. vector<Point> approx;
  71. // test each contour
  72. for( size_t i = 0; i < contours.size(); i++ )
  73. {
  74. // approximate contour with accuracy proportional
  75. // to the contour perimeter
  76. approxPolyDP(contours[i], approx, arcLength(contours[i], true)*0.02, true);
  77. // square contours should have 4 vertices after approximation
  78. // relatively large area (to filter out noisy contours)
  79. // and be convex.
  80. // Note: absolute value of an area is used because
  81. // area may be positive or negative - in accordance with the
  82. // contour orientation
  83. if( approx.size() == 4 &&
  84. fabs(contourArea(approx)) > 1000 &&
  85. isContourConvex(approx) )
  86. {
  87. double maxCosine = 0;
  88. for( int j = 2; j < 5; j++ )
  89. {
  90. // find the maximum cosine of the angle between joint edges
  91. double cosine = fabs(angle(approx[j%4], approx[j-2], approx[j-1]));
  92. maxCosine = MAX(maxCosine, cosine);
  93. }
  94. // if cosines of all angles are small
  95. // (all angles are ~90 degree) then write quandrange
  96. // vertices to resultant sequence
  97. if( maxCosine < 0.3 )
  98. squares.push_back(approx);
  99. }
  100. }
  101. }
  102. }
  103. }
  104. int main(int argc, char** argv)
  105. {
  106. const char* names[] = { "pic1.png", "pic2.png", "pic3.png",
  107. "pic4.png", "pic5.png", "pic6.png", 0 };
  108. help(argv[0]);
  109. if( argc > 1)
  110. {
  111. names[0] = argv[1];
  112. names[1] = 0;
  113. }
  114. for( int i = 0; names[i] != 0; i++ )
  115. {
  116. string filename = samples::findFile(names[i]);
  117. Mat image = imread(filename, IMREAD_COLOR);
  118. if( image.empty() )
  119. {
  120. cout << "Couldn't load " << filename << endl;
  121. continue;
  122. }
  123. vector<vector<Point> > squares;
  124. findSquares(image, squares);
  125. polylines(image, squares, true, Scalar(0, 255, 0), 3, LINE_AA);
  126. imshow(wndname, image);
  127. int c = waitKey();
  128. if( c == 27 )
  129. break;
  130. }
  131. return 0;
  132. }