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