pointPolygonTest_demo.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /**
  2. * @function pointPolygonTest_demo.cpp
  3. * @brief Demo code to use the pointPolygonTest function...fairly easy
  4. * @author OpenCV team
  5. */
  6. #include "opencv2/highgui.hpp"
  7. #include "opencv2/imgproc.hpp"
  8. #include <iostream>
  9. using namespace cv;
  10. using namespace std;
  11. /**
  12. * @function main
  13. */
  14. int main( void )
  15. {
  16. /// Create an image
  17. const int r = 100;
  18. Mat src = Mat::zeros( Size( 4*r, 4*r ), CV_8U );
  19. /// Create a sequence of points to make a contour
  20. vector<Point2f> vert(6);
  21. vert[0] = Point( 3*r/2, static_cast<int>(1.34*r) );
  22. vert[1] = Point( 1*r, 2*r );
  23. vert[2] = Point( 3*r/2, static_cast<int>(2.866*r) );
  24. vert[3] = Point( 5*r/2, static_cast<int>(2.866*r) );
  25. vert[4] = Point( 3*r, 2*r );
  26. vert[5] = Point( 5*r/2, static_cast<int>(1.34*r) );
  27. /// Draw it in src
  28. for( int i = 0; i < 6; i++ )
  29. {
  30. line( src, vert[i], vert[(i+1)%6], Scalar( 255 ), 3 );
  31. }
  32. /// Get the contours
  33. vector<vector<Point> > contours;
  34. findContours( src, contours, RETR_TREE, CHAIN_APPROX_SIMPLE);
  35. /// Calculate the distances to the contour
  36. Mat raw_dist( src.size(), CV_32F );
  37. for( int i = 0; i < src.rows; i++ )
  38. {
  39. for( int j = 0; j < src.cols; j++ )
  40. {
  41. raw_dist.at<float>(i,j) = (float)pointPolygonTest( contours[0], Point2f((float)j, (float)i), true );
  42. }
  43. }
  44. double minVal, maxVal;
  45. Point maxDistPt; // inscribed circle center
  46. minMaxLoc(raw_dist, &minVal, &maxVal, NULL, &maxDistPt);
  47. minVal = abs(minVal);
  48. maxVal = abs(maxVal);
  49. /// Depicting the distances graphically
  50. Mat drawing = Mat::zeros( src.size(), CV_8UC3 );
  51. for( int i = 0; i < src.rows; i++ )
  52. {
  53. for( int j = 0; j < src.cols; j++ )
  54. {
  55. if( raw_dist.at<float>(i,j) < 0 )
  56. {
  57. drawing.at<Vec3b>(i,j)[0] = (uchar)(255 - abs(raw_dist.at<float>(i,j)) * 255 / minVal);
  58. }
  59. else if( raw_dist.at<float>(i,j) > 0 )
  60. {
  61. drawing.at<Vec3b>(i,j)[2] = (uchar)(255 - raw_dist.at<float>(i,j) * 255 / maxVal);
  62. }
  63. else
  64. {
  65. drawing.at<Vec3b>(i,j)[0] = 255;
  66. drawing.at<Vec3b>(i,j)[1] = 255;
  67. drawing.at<Vec3b>(i,j)[2] = 255;
  68. }
  69. }
  70. }
  71. circle(drawing, maxDistPt, (int)maxVal, Scalar(255,255,255));
  72. /// Show your results
  73. imshow( "Source", src );
  74. imshow( "Distance and inscribed circle", drawing );
  75. waitKey();
  76. return 0;
  77. }